Compare commits
43 Commits
e0c76ba965
...
v0.5.1
| Author | SHA1 | Date | |
|---|---|---|---|
| d42727618e | |||
| 335cb3c757 | |||
| 7ecc4474c5 | |||
| 726a5b922b | |||
| fe1da03f66 | |||
| edfc6cdc80 | |||
| 27360ffae7 | |||
| 8aafdcfb16 | |||
| d0e0e8926c | |||
| 4beaaacf0e | |||
| b79f6c9a4e | |||
| fb43ca8e99 | |||
| 46dcc231a7 | |||
| c05dbce580 | |||
| 69a327cd45 | |||
| 5c2903eeef | |||
| be8cf3c88a | |||
| b884616889 | |||
| acf582251f | |||
| 00e6fee9bd | |||
| 24deb8e69b | |||
| 4b17ca00db | |||
| 6e80699829 | |||
| a67e9ef458 | |||
| a6491f6ef6 | |||
| fe9d2aff3f | |||
| 1e7ec0cf15 | |||
| c10ff97670 | |||
| 2dc569256c | |||
| c7b01b31cb | |||
| 32616d5404 | |||
| 7e53bb5059 | |||
| 158dccddf1 | |||
| 2bec4102a2 | |||
| ecb3d5de7c | |||
| 9051b9cfc1 | |||
| d4cce4e001 | |||
| 749047ae9e | |||
| 16456c3c69 | |||
| 637629385a | |||
| 0c113e7a91 | |||
| 6dfddffc14 | |||
| 0b3ab76405 |
@@ -14,3 +14,11 @@ server/data/
|
|||||||
.smoke/
|
.smoke/
|
||||||
*.log
|
*.log
|
||||||
.DS_Store
|
.DS_Store
|
||||||
|
|
||||||
|
# Windows native-window build output
|
||||||
|
windows/launcher/webview2/bin/
|
||||||
|
windows/launcher/webview2/obj/
|
||||||
|
|
||||||
|
# Transfer-only Windows release archives
|
||||||
|
windows/releases/*.zip
|
||||||
|
windows/releases/*.exe
|
||||||
|
|||||||
@@ -62,16 +62,22 @@ changing the current filters.
|
|||||||
**Develop.** A WebGL2 multi-pass pipeline (`src/gl/renderer.ts`), per photo,
|
**Develop.** A WebGL2 multi-pass pipeline (`src/gl/renderer.ts`), per photo,
|
||||||
non-destructive:
|
non-destructive:
|
||||||
|
|
||||||
- white balance, exposure, contrast, highlights/shadows/whites/blacks
|
- white balance as a relative Temp/Tint offset or an absolute Kelvin value with a
|
||||||
- texture, clarity, dehaze, vibrance, saturation, black & white mix
|
5500 K daylight reference, exposure, contrast, and hue-preserving
|
||||||
- RGB and per-channel tone curves
|
highlights/shadows/whites/blacks
|
||||||
- 8-band HSL colour mixer, split toning / colour grading
|
- per-channel highlight recovery, texture, clarity, per-pixel dehaze, vibrance,
|
||||||
|
saturation, black & white mix
|
||||||
|
- input levels (black point, white point, midtone gamma), RGB and per-channel tone
|
||||||
|
curves
|
||||||
|
- 8-band HSL colour mixer evaluated in OkLCh (hue and chroma changes keep their
|
||||||
|
perceived lightness), split toning / colour grading
|
||||||
- sharpening, luminance noise reduction
|
- sharpening, luminance noise reduction
|
||||||
- vignette, grain
|
- vignette, grain
|
||||||
- crop with nine aspect ratios, straighten, 90° rotation, flips
|
- crop with nine aspect ratios, straighten, 90° rotation, flips
|
||||||
- local adjustments (up to four layers): brush, linear gradient and radial masks with
|
- local adjustments (up to eight layers): brush, linear gradient and radial masks
|
||||||
feather, invert, luminance/hue/saturation ranges, and per-layer exposure, contrast,
|
with feather, invert, luminance/hue/saturation ranges, and per-layer exposure,
|
||||||
highlights, shadows, temperature, tint and saturation. Masks follow crops, zoom,
|
contrast, highlights, shadows, whites, blacks, temperature, tint, saturation,
|
||||||
|
vibrance, hue, texture, clarity, dehaze and sharpening. Masks follow crops, zoom,
|
||||||
healing and lens correction; Copy mask / Paste mask move one layer between photos
|
healing and lens correction; Copy mask / Paste mask move one layer between photos
|
||||||
- full Lensfun profiles: distortion, transverse chromatic aberration and vignetting
|
- full Lensfun profiles: distortion, transverse chromatic aberration and vignetting
|
||||||
from the official database, with manual lens search, "Match EXIF lens"
|
from the official database, with manual lens search, "Match EXIF lens"
|
||||||
@@ -87,8 +93,8 @@ non-destructive:
|
|||||||
- histogram, built-in and saved presets, history with undo/redo, selective
|
- histogram, built-in and saved presets, history with undo/redo, selective
|
||||||
copy/paste and batch sync, named snapshots, virtual copies, before/after (**\**)
|
copy/paste and batch sync, named snapshots, virtual copies, before/after (**\**)
|
||||||
- on-device auto subject, sky and background masks (no model download), an
|
- on-device auto subject, sky and background masks (no model download), an
|
||||||
ISO/camera-aware noise starting point, edge-aware lens-softness compensation, and an
|
ISO/camera-aware noise starting point, edge-aware lens-softness compensation, and soft
|
||||||
approximate paper soft-proof preview
|
proofing through a loaded printer ICC profile (or a paper simulation when none is)
|
||||||
- HDR merge with alignment, horizontal panorama stitching and focus stacking; each
|
- HDR merge with alignment, horizontal panorama stitching and focus stacking; each
|
||||||
result is added to the catalog as a new editable photo
|
result is added to the catalog as a new editable photo
|
||||||
- browser print layouts (A4, Letter, 5×7) rendered through the develop pipeline
|
- browser print layouts (A4, Letter, 5×7) rendered through the develop pipeline
|
||||||
@@ -97,7 +103,9 @@ non-destructive:
|
|||||||
Clients need no account: they see that event's live photos, heart favourites, leave
|
Clients need no account: they see that event's live photos, heart favourites, leave
|
||||||
per-photo comments, mark a photo approved or needing changes, and download proofs
|
per-photo comments, mark a photo approved or needing changes, and download proofs
|
||||||
individually or as one ZIP. Feedback shows up on the library grid and in the "Client
|
individually or as one ZIP. Feedback shows up on the library grid and in the "Client
|
||||||
picks", "Approved" and "Changes" filters. Revoking a link drops its picks and feedback.
|
picks", "Approved" and "Changes" filters. Each link can carry a password, a closing
|
||||||
|
date, a download cap or downloads switched off, and a watermark that is rendered into
|
||||||
|
newly published proofs. Revoking a link drops its picks, feedback and access settings.
|
||||||
|
|
||||||
**Team accounts.** The first signup becomes the admin. Admins create single-use invite
|
**Team accounts.** The first signup becomes the admin. Admins create single-use invite
|
||||||
links (`/join/<token>`) with an optional email lock and 1–30 day expiry, copy them from
|
links (`/join/<token>`) with an optional email lock and 1–30 day expiry, copy them from
|
||||||
@@ -111,6 +119,22 @@ quota, schedule a 24-hour cleanup of the oldest content, send a warning immediat
|
|||||||
cancel a scheduled cleanup. Cleanups stop at a target percentage of the quota instead
|
cancel a scheduled cleanup. Cleanups stop at a target percentage of the quota instead
|
||||||
of deleting the whole original plan.
|
of deleting the whole original plan.
|
||||||
|
|
||||||
|
**Tethering.** Watch a folder on the server for an event: the editor polls it, pulls
|
||||||
|
each new JPEG/TIFF/WebP/raw, imports it through the normal path (raw decode, metadata,
|
||||||
|
cloud mirroring) and only then removes the file from the folder. Point a capture app or
|
||||||
|
a transfer folder at `<data>/tether/<event>`; nothing is lost if the tab closes.
|
||||||
|
|
||||||
|
**Cull assist.** Run a focus and duplicate pass over the selection from the command
|
||||||
|
palette. Every frame is scored from its own thumbnail with a Laplacian variance, and
|
||||||
|
near-duplicates are grouped by 64-bit difference hash, so the sharpest frame of a
|
||||||
|
burst can be kept and the alternatives flagged in one action. Nothing is rated or
|
||||||
|
rejected without confirmation.
|
||||||
|
|
||||||
|
**Sidecars.** Export the selected photos' develop settings as Lightroom-style `.xmp`
|
||||||
|
sidecars (crs: attributes plus a private payload for the rest of the grade) and import
|
||||||
|
a sidecar back onto a photo. Importing keeps the crop, masks and lens profile for every
|
||||||
|
field the file does not mention.
|
||||||
|
|
||||||
**Catalog workflow.** Editable title, caption, creator, copyright and keyword chips
|
**Catalog workflow.** Editable title, caption, creator, copyright and keyword chips
|
||||||
with a keyword library and reusable metadata presets. Save the current filters and sort
|
with a keyword library and reusable metadata presets. Save the current filters and sort
|
||||||
order as a smart collection. Virtual copies share the master file but keep independent
|
order as a smart collection. Virtual copies share the master file but keep independent
|
||||||
@@ -118,9 +142,10 @@ edits; named snapshots preserve alternative looks.
|
|||||||
|
|
||||||
**Export and print.** JPEG, PNG, WebP or uncompressed 16-bit TIFF; quality; resize by
|
**Export and print.** JPEG, PNG, WebP or uncompressed 16-bit TIFF; quality; resize by
|
||||||
long edge or percent; filename template (`{name}`, `{date}`, `{time}`, `{index}`); saved
|
long edge or percent; filename template (`{name}`, `{date}`, `{time}`, `{index}`); saved
|
||||||
export recipes; output sharpening; watermark; XMP metadata embedded in JPEGs; an
|
export recipes; output sharpening; watermark; XMP metadata embedded in JPEGs; sRGB,
|
||||||
embedded sRGB ICC profile; batch export as one ZIP or separate files. Full-resolution
|
Display P3 or Adobe RGB output with a matching generated ICC profile (JPEG/TIFF); batch
|
||||||
export runs through the same renderer as the screen preview.
|
export as one ZIP or separate files. Full-resolution export runs through the same
|
||||||
|
renderer as the screen preview.
|
||||||
|
|
||||||
**Administration.** Users, roles, invites, catalog backup/restore, per-account quotas,
|
**Administration.** Users, roles, invites, catalog backup/restore, per-account quotas,
|
||||||
email settings and a storage relocation tool are all in one panel.
|
email settings and a storage relocation tool are all in one panel.
|
||||||
@@ -199,9 +224,12 @@ 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 |
|
||||||
|
| `LUMINARY_16BIT` | `1` | Also keep the decoded samples as a 16-bit PNG beside the raw proxy; `0` saves the disk and download it costs, at the price of grading an 8-bit source |
|
||||||
| `LUMINARY_RAW_WORKERS` | `min(4, cores−1)` | Concurrent LibRaw decoders; each holds a worker and a few hundred MB |
|
| `LUMINARY_RAW_WORKERS` | `min(4, cores−1)` | Concurrent LibRaw decoders; each holds a worker and a few hundred MB |
|
||||||
| `LUMINARY_RAW_IDLE_MS` | `90000` | Idle decoders are disposed after this to release memory |
|
| `LUMINARY_RAW_IDLE_MS` | `90000` | Idle decoders are disposed after this to release memory |
|
||||||
| `LUMINARY_DENOISE_WORKERS` | `min(4, cores−1)` | Concurrent detail-denoise jobs (read directly from the environment) |
|
| `LUMINARY_DENOISE_WORKERS` | `min(4, cores−1)` | Concurrent detail-denoise jobs (read directly from the environment) |
|
||||||
@@ -230,6 +258,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.
|
||||||
@@ -244,6 +281,22 @@ npm run build # type-checks and bundles dist/
|
|||||||
npm start # serves dist/ and /api from one Node process
|
npm start # serves dist/ and /api from one Node process
|
||||||
```
|
```
|
||||||
|
|
||||||
|
To push a running install over ssh, `npm run deploy` runs the whole predeploy gate
|
||||||
|
first — a type error, a failing test or a clipping-overlay regression stops it before
|
||||||
|
anything is copied — then rsyncs the source, rebuilds, restarts the service and checks
|
||||||
|
that the server is serving the same bundle hashes. npm runs the `predeploy` script
|
||||||
|
before `deploy` on its own, so the gate runs exactly once; calling `node
|
||||||
|
scripts/deploy.mjs` directly runs the gate itself:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
LUMINARY_DEPLOY_HOST=bhursey@photos.example.org \
|
||||||
|
LUMINARY_DEPLOY_SUDO_PASS=… npm run deploy
|
||||||
|
```
|
||||||
|
|
||||||
|
`LUMINARY_DEPLOY_PATH` (default `/srv/luminary`), `LUMINARY_DEPLOY_SERVICE` (default
|
||||||
|
`luminary`) and `LUMINARY_DEPLOY_SSH_PASS` cover a different layout; without the
|
||||||
|
password variables it uses your ssh key and passwordless sudo.
|
||||||
|
|
||||||
The server serves the built UI with an SPA fallback (unknown non-API paths return
|
The server serves the built UI with an SPA fallback (unknown non-API paths return
|
||||||
`index.html`), caches `/assets/*` for a year as immutable, and returns `503` with a
|
`index.html`), caches `/assets/*` for a year as immutable, and returns `503` with a
|
||||||
build hint if `dist/index.html` is missing. JSON responses are `no-store`; image bytes
|
build hint if `dist/index.html` is missing. JSON responses are `no-store`; image bytes
|
||||||
@@ -299,7 +352,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
|
||||||
@@ -414,9 +469,14 @@ Data directory
|
|||||||
| `src/lib/import.ts` | File ingest, EXIF read, preview/thumb creation, upload scheduling |
|
| `src/lib/import.ts` | File ingest, EXIF read, preview/thumb creation, upload scheduling |
|
||||||
| `src/lib/export.ts` | Renderer-driven export, recipes, watermark, filenames, ZIP |
|
| `src/lib/export.ts` | Renderer-driven export, recipes, watermark, filenames, ZIP |
|
||||||
| `src/lib/tiff.ts`, `icc.ts` | Dependency-free 16-bit TIFF writer and sRGB profile |
|
| `src/lib/tiff.ts`, `icc.ts` | Dependency-free 16-bit TIFF writer and sRGB profile |
|
||||||
| `src/lib/lensfun.ts`, `lensNames.ts`, `lensDefaults.ts` | Lensfun client, EXIF matching, saved defaults |
|
| `src/lib/preview16.ts` | 16-bit raw-proxy PNG parser, camera matrix and half-float conversion for the RGBA16F source texture |
|
||||||
|
| `src/lib/softProof.ts` | ICC parsing (lut8/lut16/mAB), printer A2B/B2A round trip and the 3D proof cube |
|
||||||
|
| `src/lib/dcp.ts` | DCP tag reader and the camera-to-sRGB matrix recipe |
|
||||||
|
| `src/lib/lensDb.ts`, `lensEngine.ts`, `lensNames.ts`, `lensDefaults.ts` | Lens database, correction maps, EXIF matching, saved defaults |
|
||||||
| `src/lib/merge.ts` | HDR / panorama / focus-stack composition |
|
| `src/lib/merge.ts` | HDR / panorama / focus-stack composition |
|
||||||
| `src/lib/autoMask.ts`, `noiseProfile.ts` | On-device masks and ISO-aware noise starting points |
|
| `src/lib/autoMask.ts`, `noiseProfile.ts` | On-device masks and ISO-aware noise starting points |
|
||||||
|
| `src/lib/xmp.ts` | Lightroom-compatible XMP sidecar reader/writer |
|
||||||
|
| `src/lib/cull.ts` | Focus scoring and duplicate hashing for cull assist |
|
||||||
| `src/lib/curves.ts`, `whiteBalance.ts`, `clipPreview.ts`, `presets.ts` | Curve sampling, WB maths, clipping display, presets |
|
| `src/lib/curves.ts`, `whiteBalance.ts`, `clipPreview.ts`, `presets.ts` | Curve sampling, WB maths, clipping display, presets |
|
||||||
| `docs/user-guide/` | Source of the in-app user guide (`guide.html`), also shipped as PDF |
|
| `docs/user-guide/` | Source of the in-app user guide (`guide.html`), also shipped as PDF |
|
||||||
|
|
||||||
@@ -439,7 +499,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,
|
||||||
@@ -497,7 +557,17 @@ routes are public and are gated only by the share token.
|
|||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| GET | `/api/sync` | session | Everything the workspace needs: user, events, photos, presets, proof summary |
|
| GET | `/api/sync` | session | Everything the workspace needs: user, events, photos, presets, proof summary |
|
||||||
| GET | `/api/proofs` | session | Client pick/comment/review summary for the owner's events |
|
| GET | `/api/proofs` | session | Client pick/comment/review summary for the owner's events |
|
||||||
|
| PUT | `/api/events/:id/share/settings` | owner | Password, expiry, watermark, download switch and cap for the proofing link |
|
||||||
|
| GET | `/api/galleries/:token/status` | public | Whether the link is locked, its expiry and whether downloads are allowed |
|
||||||
|
| POST | `/api/galleries/:token/unlock` | public | Exchange the gallery password for a link-scoped unlock cookie |
|
||||||
|
| GET | `/api/events/:id/tether` | owner | Watch-folder path and the frames waiting in it |
|
||||||
|
| GET | `/api/events/:id/tether/file?name=` | owner | Stream one waiting frame to the editor |
|
||||||
|
| DELETE | `/api/events/:id/tether/file?name=` | owner | Remove a frame after it imported |
|
||||||
| PUT | `/api/presets` | session | Replace the stored preset library |
|
| PUT | `/api/presets` | session | Replace the stored preset library |
|
||||||
|
| GET | `/api/lens-profiles` | session | Team-measured lens calibrations, shared by every member |
|
||||||
|
| POST | `/api/lens-profiles` | session | Add a calibration; coefficient ranges and sample shapes are validated |
|
||||||
|
| PUT | `/api/lens-profiles/:id` | author or admin | Replace a calibration |
|
||||||
|
| DELETE | `/api/lens-profiles/:id` | author or admin | Remove a calibration |
|
||||||
| PUT | `/api/events/:id` | owner | Upsert an event record |
|
| PUT | `/api/events/:id` | owner | Upsert an event record |
|
||||||
| DELETE | `/api/events/:id` | owner | Delete an event (photos are handled separately) |
|
| DELETE | `/api/events/:id` | owner | Delete an event (photos are handled separately) |
|
||||||
| PUT | `/api/photos/:id` | owner | Upsert a photo record; accepts a data-URL thumbnail, which is written to `thumbs/` |
|
| PUT | `/api/photos/:id` | owner | Upsert a photo record; accepts a data-URL thumbnail, which is written to `thumbs/` |
|
||||||
@@ -524,7 +594,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 |
|
||||||
@@ -545,6 +615,8 @@ routes are public and are gated only by the share token.
|
|||||||
| POST | `/api/admin/catalog` | Restore a backup produced by the GET |
|
| POST | `/api/admin/catalog` | Restore a backup produced by the GET |
|
||||||
| GET | `/api/admin/storage` | Current and default storage roots, custom flag |
|
| GET | `/api/admin/storage` | Current and default storage roots, custom flag |
|
||||||
| PUT | `/api/admin/storage` | Move image storage to another absolute path |
|
| PUT | `/api/admin/storage` | Move image storage to another absolute path |
|
||||||
|
| GET | `/api/admin/previews/rebuild` | Progress of the raw proxy rebuild |
|
||||||
|
| POST | `/api/admin/previews/rebuild` | Re-decode every camera raw into a fresh proxy, thumbnail and 16-bit sidecar |
|
||||||
| PATCH | `/api/admin/quotas/:id` | Set an account's byte limit |
|
| PATCH | `/api/admin/quotas/:id` | Set an account's byte limit |
|
||||||
| POST | `/api/admin/quotas/:id/prune` | Compute the oldest-first plan and schedule it 24 h out |
|
| POST | `/api/admin/quotas/:id/prune` | Compute the oldest-first plan and schedule it 24 h out |
|
||||||
| DELETE | `/api/admin/quotas/:id/prune` | Cancel a scheduled cleanup |
|
| DELETE | `/api/admin/quotas/:id/prune` | Cancel a scheduled cleanup |
|
||||||
@@ -665,14 +737,130 @@ 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:
|
||||||
|
|
||||||
1. The original file is stored byte-for-byte in `originals/` with its real extension.
|
1. The original file is stored byte-for-byte in `originals/` with its real extension.
|
||||||
2. LibRaw (`libraw-wasm`) opens it in a pooled worker with camera white balance, sRGB
|
2. LibRaw (`libraw-wasm`) opens it in a pooled worker with camera white balance and the
|
||||||
output and the container's orientation, then `sharp` encodes an editable JPEG proxy
|
container's orientation and returns the frame **before** any output colourspace
|
||||||
at `LUMINARY_RAW_EDGE` (6000 px by default).
|
(`outputColor: 0`). The camera-to-sRGB step is then the body's own `rgb_cam` matrix,
|
||||||
|
applied in `server/color.mjs` — the same 3×3 matrix the editor applies to the sidecar,
|
||||||
|
so changing the camera profile is a matrix swap rather than a second decode. One
|
||||||
|
white point is chosen for the frame from the matrixed pixels (99th percentile, the
|
||||||
|
clipping policy LibRaw's auto-bright targets) and baked into both outputs; LibRaw's
|
||||||
|
own auto-bright measures each output path separately and would leave the JPEG a third
|
||||||
|
of a stop away from the sidecar. `sharp` encodes the editable JPEG proxy at
|
||||||
|
`LUMINARY_RAW_EDGE` (6000 px by default). The same decode also writes a 16-bit PNG of
|
||||||
|
the camera samples beside it (`previews/<id>.p16.png`, roughly 25× the JPEG) with the
|
||||||
|
matrix in a `tEXt` chunk: the editor inflates that sidecar into an `RGBA16F` source
|
||||||
|
texture and applies `rgb_cam` in the grade shader, so the grade has 65,536 levels per
|
||||||
|
channel instead of 256. A photo without a sidecar — one imported before this existed,
|
||||||
|
a non-raw file, or a build with `LUMINARY_16BIT=0` — simply grades the JPEG, so
|
||||||
|
nothing breaks either way. The grid and Compare read the same samples: on first
|
||||||
|
request the server writes a camera-native tile the size of the JPEG thumbnail at
|
||||||
|
`previews/<id>.t16.png`, and Compare loads the full sidecar, so a loaded DCP profile
|
||||||
|
shows in every view of the photo. Preset previews do the same.
|
||||||
3. If LibRaw cannot open the file, the largest JPEG embedded in the container is
|
3. If LibRaw cannot open the file, the largest JPEG embedded in the container is
|
||||||
extracted and normalised instead. The grid marks such photos `RAW` and the Info panel
|
extracted and normalised instead. The grid marks such photos `RAW` and the Info panel
|
||||||
reports which engine produced the proxy, so exotic or very new cameras still import.
|
reports which engine produced the proxy, so exotic or very new cameras still import.
|
||||||
@@ -683,6 +871,17 @@ Formats: CR2/CR3/CRW, NEF/NRW, ARW/SRF/SR2, ORF, RW2/RWL/RAW, RAF, PEF, DNG, SRW
|
|||||||
FFF, IIQ, X3F, ERF, K25/KDC, DCR, MOS, MRW, MEF, SRAW. Content sniffing checks the
|
FFF, IIQ, X3F, ERF, K25/KDC, DCR, MOS, MRW, MEF, SRAW. Content sniffing checks the
|
||||||
container signature before wasting a decode attempt.
|
container signature before wasting a decode attempt.
|
||||||
|
|
||||||
|
**Camera-native conversion, measured.** `rgb_cam` is applied to the sRGB-decoded camera
|
||||||
|
samples; `outputColor: 0` output is sRGB-encoded, not linear (a power curve fits it
|
||||||
|
1.8 ΔE worse). Against LibRaw's sRGB + auto-bright output on this repository's test
|
||||||
|
raws, the new proxy sits at mean ΔE 0.3–2.4 on normally exposed frames with the same
|
||||||
|
~1 % highlight clipping, and 5.5 on one very dark frame where the two auto-bright
|
||||||
|
policies disagree most — one shared white point cannot match a per-path heuristic
|
||||||
|
exactly. Applying the sidecar's matrix in the shader reproduces the server-encoded
|
||||||
|
proxy to within one 8-bit code, so the two outputs cannot drift apart. Deriving the
|
||||||
|
same matrix from a DCP `ColorMatrix1` — `inverse(rowNormalise(ColorMatrix · xyz_rgb))`
|
||||||
|
— matches LibRaw's `rgb_cam` to 2.2e-5 on a D700 NEF and 2.7e-5 on a 5D Mark II CR2.
|
||||||
|
|
||||||
**Parallel import.** Decoding runs in a bounded pool of LibRaw workers (default
|
**Parallel import.** Decoding runs in a bounded pool of LibRaw workers (default
|
||||||
`min(4, cores−1)`, `LUMINARY_RAW_WORKERS`), and the browser uploads several files at a
|
`min(4, cores−1)`, `LUMINARY_RAW_WORKERS`), and the browser uploads several files at a
|
||||||
time. Each instance owns one worker thread; extra jobs queue. Idle instances are
|
time. Each instance owns one worker thread; extra jobs queue. Idle instances are
|
||||||
@@ -730,28 +929,35 @@ licensed implementation.
|
|||||||
|
|
||||||
## Lens profiles
|
## Lens profiles
|
||||||
|
|
||||||
Lens correction uses the [Lensfun](https://lensfun.github.io/) camera and lens database
|
Lens correction uses the calibration data of the
|
||||||
through the [`@neoanaloglabkk/lensfun-wasm`](https://github.com/lexluthor0304/LensfunWasm)
|
[Lensfun](https://lensfun.github.io/) camera and lens database, converted at build time
|
||||||
build. Runtime assets are served from `public/lensfun/`.
|
into the compact profile file the editor ships. The correction maths is Luminary's own
|
||||||
|
(`src/lib/lensEngine.ts`): PanoTools, poly3 and poly5 distortion, poly3 TCA and `pa`
|
||||||
|
vignetting, evaluated in the same normalised coordinates Lensfun used. No WebAssembly
|
||||||
|
runtime, no XML parser and no `blob:` or eval allowance is involved, and a unit test
|
||||||
|
pins the output against maps captured from the previous implementation.
|
||||||
|
|
||||||
- **Database** — © Lensfun contributors, licensed
|
- **Database** — © Lensfun contributors, licensed
|
||||||
[CC BY-SA 3.0 Unported](https://creativecommons.org/licenses/by-sa/3.0/), taken from
|
[CC BY-SA 3.0 Unported](https://creativecommons.org/licenses/by-sa/3.0/), taken from
|
||||||
Lensfun `data/db` at commit
|
Lensfun `data/db` at commit
|
||||||
[`655a9c4`](https://github.com/lensfun/lensfun/tree/655a9c4e3e53c25bc04843c853e7e7a0121359e7/data).
|
[`655a9c4`](https://github.com/lensfun/lensfun/tree/655a9c4e3e53c25bc04843c853e7e7a0121359e7/data)
|
||||||
It is redistributed as bundled by the wrapper build; Luminary adds no profiles of its
|
and converted by `scripts/build-lens-db.mjs` into `public/lens-db/profiles.json`.
|
||||||
own.
|
Luminary adds no profiles of its own.
|
||||||
- **Library** — Lensfun is LGPL-3.0 (the bundled notice states "or later"), compiled to
|
- **Engine** — `src/lib/lensDb.ts` (loading, matching, camera lookup) and
|
||||||
WebAssembly. Corresponding source is the upstream repository at the pinned commit plus
|
`src/lib/lensEngine.ts` (maps, auto-scale), both MIT like the rest of the app code.
|
||||||
the wrapper's build scripts.
|
- **Team calibrations** — lenses the database lacks can be measured in-house and added
|
||||||
- **Bundled files** — `public/lensfun/LICENSE` is the **MIT licence of the WASM
|
from the Optics panel (“Team calibrations”). They are stored in the server's SQLite
|
||||||
wrapper**, not of the database or the library. `NOTICE.md`,
|
database (`lens_profiles`), searched next to the bundled profiles with the same sample
|
||||||
`THIRD_PARTY_LICENSES.md` and `UPSTREAM.md` record the other components and the pin.
|
layout, and are Luminary's own data rather than Lensfun content.
|
||||||
|
- **Bundled files** — `public/lens-db/NOTICE.md` records the attribution and the pin;
|
||||||
|
`public/lens-db/profiles.json` carries the same provenance in its `source` field.
|
||||||
|
|
||||||
See [Third-party attribution and licences](#third-party-attribution-and-licences) before
|
See [Third-party attribution and licences](#third-party-attribution-and-licences) before
|
||||||
redistributing the app or its container image.
|
redistributing the app or its container image.
|
||||||
|
|
||||||
Profiles load lazily the first time the Optics panel needs one, so a library that never
|
Profiles load lazily the first time the Optics panel needs one, so a library that never
|
||||||
uses lens correction does not download the ~5 MB database. A profile is built for the
|
uses lens correction does not download the ~1.8 MB database. Team calibrations are a
|
||||||
|
small extra request and are ignored when offline or signed out. A profile is built for the
|
||||||
photo's current focal length and aperture; it is not interpolated between zoom
|
photo's current focal length and aperture; it is not interpolated between zoom
|
||||||
positions. Camera-lens defaults require both a normalised camera and lens name to match.
|
positions. Camera-lens defaults require both a normalised camera and lens name to match.
|
||||||
|
|
||||||
@@ -766,6 +972,9 @@ positions. Camera-lens defaults require both a normalised camera and lens name t
|
|||||||
| `npm run dev` | Vite HMR on 5173 |
|
| `npm run dev` | Vite HMR on 5173 |
|
||||||
| `npm run typecheck` | `tsc --noEmit` |
|
| `npm run typecheck` | `tsc --noEmit` |
|
||||||
| `npm test` | Vitest, one pass then exit |
|
| `npm test` | Vitest, one pass then exit |
|
||||||
|
| `npm run check:render` | Headless Chrome check that the 16-bit sidecar and JPEG proxy upload in the same row order |
|
||||||
|
| `npm run predeploy` | Typecheck, unit suite, render check, then build — run this before pushing a deploy; the build is skipped when only test files changed since the last build |
|
||||||
|
| `npm run deploy` | Predeploy gate, then rsync, remote build, restart and bundle-hash check (see [Production deployment](#production-deployment)) |
|
||||||
|
|
||||||
Conventions worth knowing before changing code:
|
Conventions worth knowing before changing code:
|
||||||
|
|
||||||
@@ -784,7 +993,7 @@ Conventions worth knowing before changing code:
|
|||||||
|
|
||||||
### Tests
|
### Tests
|
||||||
|
|
||||||
`npm test` runs six Vitest files, all pure-logic:
|
`npm test` runs the pure-logic Vitest suite:
|
||||||
|
|
||||||
| File | Covers |
|
| File | Covers |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
@@ -794,9 +1003,25 @@ Conventions worth knowing before changing code:
|
|||||||
| `src/lib/lensNames.test.ts` | EXIF lens-name normalisation, search variants and match scoring |
|
| `src/lib/lensNames.test.ts` | EXIF lens-name normalisation, search variants and match scoring |
|
||||||
| `src/lib/lensDefaults.test.ts` | Camera + lens default selection and rejection rules |
|
| `src/lib/lensDefaults.test.ts` | Camera + lens default selection and rejection rules |
|
||||||
| `src/lib/editSections.test.ts` | Selective settings copy and the ISO-aware auto-noise curve |
|
| `src/lib/editSections.test.ts` | Selective settings copy and the ISO-aware auto-noise curve |
|
||||||
|
| `src/lib/preview16.test.ts` | 16-bit PNG proxy parsing, row order, half-float encoding and the camera matrix chunk |
|
||||||
|
| `src/lib/dcp.test.ts` | DCP tag parsing and the camera matrix recipe against LibRaw's own values |
|
||||||
|
| `src/lib/softProof.test.ts` | ICC parsing (including counted lut16 tables), the printer round trip, gamut threshold, rendering-intent selection and CMYK profiles |
|
||||||
|
| `src/lib/dcpLibrary.test.ts` | Per-camera DCP library: validation, replacement, forgetting and camera matching |
|
||||||
|
|
||||||
There are no server integration tests; the API is exercised through the UI.
|
There are no server integration tests; the API is exercised through the UI.
|
||||||
|
|
||||||
|
`npm run check:render` covers the one thing the unit suite cannot: what a shader does to
|
||||||
|
real GPU pixels. It encodes a 16-bit sidecar with the server's own encoder, serves it
|
||||||
|
beside the matching JPEG proxy and measures the rows that reach a WebGL2 texture in
|
||||||
|
headless Chrome. Then it renders that image through the real `Renderer` with the Ctrl
|
||||||
|
clipping preview on, so the overlay has to paint red for one clipped channel and yellow
|
||||||
|
for two instead of collapsing to white, and an unclipped band has to turn white once
|
||||||
|
Exposure is pushed past the top of the range. The same run checks the shadow warning:
|
||||||
|
red for one channel at black, yellow for red+green, cyan for green+blue. `npm run
|
||||||
|
predeploy` chains it with the typecheck, unit suite and build. It fails on either regression, printing the
|
||||||
|
measured values, needs Chrome (`CHROME_PATH` overrides discovery) and skips with a notice
|
||||||
|
when none is installed.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Troubleshooting
|
## Troubleshooting
|
||||||
@@ -818,20 +1043,60 @@ There are no server integration tests; the API is exercised through the UI.
|
|||||||
|
|
||||||
## Limitations
|
## Limitations
|
||||||
|
|
||||||
- **Not a cloud service.** No hosted deployment, no tethered capture, no sync client
|
- **Not a cloud service.** No hosted deployment and no camera driver: tethering is a
|
||||||
beyond one browser tab's whole-record push. The last writer wins per photo; it is
|
server drop folder, not a PTP/USB connection. No sync client beyond one browser tab's
|
||||||
|
whole-record push. The last writer wins per photo; it is
|
||||||
designed for a handful of people, not concurrent batch workflows.
|
designed for a handful of people, not concurrent batch workflows.
|
||||||
- **Per-account catalogs.** Workspaces are private to their owner; there is no shared
|
- **Per-account catalogs.** Workspaces are private to their owner; there is no shared
|
||||||
library between two members. Collaboration happens through client proofing links and
|
library between two members. Collaboration happens through client proofing links and
|
||||||
the admin overview.
|
the admin overview.
|
||||||
- **Proxy-bounded raw.** Raw editing works on the demosaiced JPEG proxy (6000 px
|
- **Proxy-bounded raw.** Raw editing works on the demosaiced proxy (6000 px default),
|
||||||
default), not the sensor mosaic; export size is bounded by the proxy.
|
not the sensor mosaic; export size is bounded by the proxy. Raw imports keep two
|
||||||
- **Approximate tools.** Temperature/tint are relative to the as-shot white balance.
|
files: the JPEG proxy every browser can decode, and a 16-bit PNG sidecar of the same
|
||||||
Auto masks are an on-device saliency/colour estimate, not a segmentation model. Soft
|
pixels. The editor grades the sidecar as a half-float source texture when it is
|
||||||
proofing approximates paper white, black point and print gamut but does not apply a
|
present, which is what keeps a heavy shadow lift or a 3200 K white balance from
|
||||||
printer ICC profile; use the browser print dialog for final ICC handling. The
|
posterising an 8-bit source; the JPEG and everything derived from it (thumbnails,
|
||||||
|
denoise renders, proofs) stay 8-bit. A per-photo DCP profile is applied wherever
|
||||||
|
the sidecar is: the Develop canvas, exports, Compare and preset previews. The grid
|
||||||
|
uses a camera-native tile built on demand beside the sidecar (`previews/<id>.t16.png`),
|
||||||
|
so a profile does not cost a 50 MB fetch per card; a photo that predates the tile or
|
||||||
|
was imported with `LUMINARY_16BIT=0` falls back to the JPEG, which already has the
|
||||||
|
body matrix baked in. The sidecar costs about 25× the JPEG in disk, one download per photo at open time and
|
||||||
|
one extra texture in GPU memory (about 8 bytes per pixel), so `LUMINARY_16BIT=0` turns
|
||||||
|
it off for libraries that would rather have the space. Either way the 16-bit TIFF export writes 65,536
|
||||||
|
samples per channel from the `RGBA16F` render target, so its precision is only more
|
||||||
|
than the source's when the sidecar was available; it never invents detail the decode
|
||||||
|
did not produce.
|
||||||
|
- **Approximate tools.** The relative Temp/Tint sliders and the absolute Kelvin
|
||||||
|
control are display-space gains; they are not a camera-specific white-balance
|
||||||
|
matrix pair. Raw decode uses the camera's own matrix; a DCP `ColorMatrix` reproduces
|
||||||
|
it exactly (`src/lib/dcp.ts` parses the file and derives the matrix), and **Develop →
|
||||||
|
Camera profile** loads a `.dcp` per photo, storing the derived 9-number matrix in
|
||||||
|
the edit so it follows presets, snapshots and XMP. A loaded matrix is also remembered
|
||||||
|
per camera body in a local profile library (`src/lib/dcpLibrary.ts`), so the next
|
||||||
|
frame from that body needs one menu pick instead of another file dialog; the edit
|
||||||
|
keeps its own copy, so the library is only a shortcut. The picker is available only on
|
||||||
|
camera-native sidecars; an older sRGB proxy needs a RAW reprocess first.
|
||||||
|
Auto masks are an on-device colour-model segmentation (border histogram, Otsu split,
|
||||||
|
connected components), not a trained segmentation network, so a subject that shares
|
||||||
|
its colour with the background needs a brush pass. Soft
|
||||||
|
proofing applies a printer profile's real A2B/B2A tables when one is loaded
|
||||||
|
(**Soft proofing → Load ICC profile**), and falls back to paper white, black point and
|
||||||
|
a gamut approximation otherwise. The loaded profile is remembered on this device (a
|
||||||
|
small IndexedDB store, not the photo record or the catalog) and the edit stores the
|
||||||
|
rendering intent — perceptual, relative colorimetric or saturation — so a proof
|
||||||
|
survives reloads and follows the photo. A profile without tables for the chosen intent
|
||||||
|
falls back to its perceptual pair. The print dialog still does its own colour
|
||||||
|
management. Both LUT layouts are
|
||||||
|
read: v2 `lut16` with fixed 256-entry tables and the counted v4 layout that MOAB/Epson
|
||||||
|
paper profiles and Ghostscript's press profiles actually use (4096 entries, counts at
|
||||||
|
offsets 48/50). Against LittleCMS on a MOAB/Epson ET-8550 profile the cube agrees to a
|
||||||
|
mean 0.97 and p95 3 of 255 per channel. The gamut warning uses a ΔE76 round-trip
|
||||||
|
threshold of 2.5 with no endpoint rule: on the repository's photos that flags 6–8 % of
|
||||||
|
pixels, the 90th percentile round trip is 1.5 ΔE, and the neutral ramp stays clean. The
|
||||||
auto-noise profile is an ISO/camera heuristic over the existing sliders, not a
|
auto-noise profile is an ISO/camera heuristic over the existing sliders, not a
|
||||||
calibrated sensor model.
|
calibrated sensor model, and sharpening is multi-scale unsharp masking rather than
|
||||||
|
deconvolution.
|
||||||
- **Merge scope.** HDR, panorama and focus stacking are translation-aligned and aimed at
|
- **Merge scope.** HDR, panorama and focus stacking are translation-aligned and aimed at
|
||||||
bracketed, stacked or horizontal sequences, not handheld multi-row composites. They
|
bracketed, stacked or horizontal sequences, not handheld multi-row composites. They
|
||||||
compose at a reduced working edge (2600 px).
|
compose at a reduced working edge (2600 px).
|
||||||
@@ -869,17 +1134,13 @@ including Lensfun's CC BY-SA 3.0 database, which the MIT licence does not relice
|
|||||||
|
|
||||||
| Component | Version / pin | Upstream | Licence | Notes |
|
| Component | Version / pin | Upstream | Licence | Notes |
|
||||||
| --- | --- | --- | --- | --- |
|
| --- | --- | --- | --- | --- |
|
||||||
| Lensfun library | `655a9c4` | [lensfun/lensfun](https://github.com/lensfun/lensfun) | LGPL-3.0; bundled notices say "or later" | Compiled to WebAssembly; distribution needs the licence text and corresponding source |
|
| Lensfun database | `655a9c4` | [lensfun `data/db`](https://github.com/lensfun/lensfun/tree/655a9c4e3e53c25bc04843c853e7e7a0121359e7/data) | CC BY-SA 3.0 Unported | © Lensfun contributors; shipped as `public/lens-db/profiles.json`; attribution and share-alike apply to the data only |
|
||||||
| Lensfun database | `655a9c4` | [lensfun `data/db`](https://github.com/lensfun/lensfun/tree/655a9c4e3e53c25bc04843c853e7e7a0121359e7/data) | CC BY-SA 3.0 Unported | © Lensfun contributors; shipped as `public/lensfun/lensfun-core.data`; attribution and share-alike apply |
|
|
||||||
| Lensfun WASM wrapper | 0.1.3 | [lexluthor0304/LensfunWasm](https://github.com/lexluthor0304/LensfunWasm) | MIT | `public/lensfun/LICENSE` is this licence and covers neither the database nor the library |
|
|
||||||
| LibRaw | via `libraw-wasm` 1.6.0 | [LibRaw/LibRaw](https://github.com/LibRaw/LibRaw) | LGPL-2.1 **or** CDDL-1.0 (dual) | The decoder compiled into the WASM |
|
| LibRaw | via `libraw-wasm` 1.6.0 | [LibRaw/LibRaw](https://github.com/LibRaw/LibRaw) | LGPL-2.1 **or** CDDL-1.0 (dual) | The decoder compiled into the WASM |
|
||||||
| `libraw-wasm` | 1.6.0 | [ybouane/LibRaw-Wasm](https://github.com/ybouane/LibRaw-Wasm) | ISC | Binding layer only; its metadata does not replace LibRaw's terms for the compiled library |
|
| `libraw-wasm` | 1.6.0 | [ybouane/LibRaw-Wasm](https://github.com/ybouane/LibRaw-Wasm) | ISC | Binding layer only; its metadata does not replace LibRaw's terms for the compiled library |
|
||||||
| `sharp` | 0.35.5 | [lovell/sharp](https://github.com/lovell/sharp) | Apache-2.0 | Prebuilt binaries bundle libvips |
|
| `sharp` | 0.35.5 | [lovell/sharp](https://github.com/lovell/sharp) | Apache-2.0 | Prebuilt binaries bundle libvips |
|
||||||
| libvips | bundled by `sharp` | [libvips/libvips](https://github.com/libvips/libvips) | LGPL-2.1-or-later | Applies when distributing binaries or container images |
|
| libvips | bundled by `sharp` | [libvips/libvips](https://github.com/libvips/libvips) | LGPL-2.1-or-later | Applies when distributing binaries or container images |
|
||||||
| tinyxml2 | bundled in Lensfun WASM | [leethomason/tinyxml2](https://github.com/leethomason/tinyxml2) | zlib | |
|
|
||||||
| utf8proc | bundled in Lensfun WASM | [JuliaStrings/utf8proc](https://github.com/JuliaStrings/utf8proc) | MIT | |
|
|
||||||
| `exifr` | 7.1.3 | [MikeKovarik/exifr](https://github.com/MikeKovarik/exifr) | MIT | Browser EXIF parsing |
|
| `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 | |
|
||||||
@@ -901,18 +1162,15 @@ Creative Commons content licence, and it grants neither patent nor trademark rig
|
|||||||
|
|
||||||
### Redistribution checklist
|
### Redistribution checklist
|
||||||
|
|
||||||
`public/lensfun/` currently ships the notices (`NOTICE.md`, `THIRD_PARTY_LICENSES.md`,
|
`public/lens-db/` currently ships the converted data and `NOTICE.md`, but **not** the
|
||||||
`UPSTREAM.md`) and the wrapper's MIT `LICENSE`, but **not** the full LGPL-3.0 or
|
full CC BY-SA 3.0 text. Before distributing Luminary or its container image:
|
||||||
CC BY-SA 3.0 texts. Before distributing Luminary or its container image:
|
|
||||||
|
|
||||||
1. Add the upstream licence texts beside the assets: Lensfun `COPYING` and
|
1. Add the upstream licence text beside the data: Lensfun
|
||||||
`COPYING.LESSER` (the LGPL incorporates GPL-3.0 by reference), and
|
`data/COPYING.CC_BY-SA_3.0`.
|
||||||
`data/COPYING.CC_BY-SA_3.0` for the database.
|
2. Keep the notice, the pinned commit and the attribution block above in the distributed
|
||||||
2. Keep the notices, the pinned commit and the attribution block above in the distributed
|
copy, served from `public/lens-db/` as it is today.
|
||||||
copy, served from `public/lensfun/` as they are today.
|
3. Provide corresponding source for the LGPL components still shipped: LibRaw at the
|
||||||
3. Provide corresponding source for the LGPL components: Lensfun and LibRaw at the
|
version actually built.
|
||||||
versions actually built, plus tinyxml2 and utf8proc. Leave
|
|
||||||
`dist/lensfun/lensfun-core.wasm` and its JS loader replaceable.
|
|
||||||
4. When publishing a container image, include the same files and the libvips, Node.js and
|
4. When publishing a container image, include the same files and the libvips, Node.js and
|
||||||
Debian notices.
|
Debian notices.
|
||||||
5. Do not relicense third-party assets under Luminary's own terms, and do not add
|
5. Do not relicense third-party assets under Luminary's own terms, and do not add
|
||||||
|
|||||||
@@ -3,35 +3,31 @@
|
|||||||
**Luminary** — notices resolved 23 November 2026.
|
**Luminary** — notices resolved 23 November 2026.
|
||||||
|
|
||||||
This file consolidates the notices for third-party software that Luminary bundles,
|
This file consolidates the notices for third-party software that Luminary bundles,
|
||||||
links, or ships in its build output and container image. `public/lensfun/NOTICE.md`
|
links, or ships in its build output and container image. `public/lens-db/NOTICE.md`
|
||||||
and `public/lensfun/THIRD_PARTY_LICENSES.md` remain the notices served with the
|
remains the notice served with the Lensfun-derived calibration data; this file does not
|
||||||
Lensfun assets; this file does not replace them.
|
replace it.
|
||||||
|
|
||||||
The Luminary application code is licensed under the [MIT licence](LICENSE). That licence
|
The Luminary application code is licensed under the [MIT licence](LICENSE). That licence
|
||||||
covers only Luminary's original code: it grants no rights in the components below and
|
covers only Luminary's original code: it grants no rights in the components below and
|
||||||
does not replace their terms.
|
does not replace their terms.
|
||||||
Versions are those resolved in `package-lock.json`; the Lensfun pin is
|
Versions are those resolved in `package-lock.json`; the lens database pin is
|
||||||
`655a9c4e3e53c25bc04843c853e7e7a0121359e7` (see `public/lensfun/UPSTREAM.md`).
|
`655a9c4e3e53c25bc04843c853e7e7a0121359e7` (see `public/lens-db/NOTICE.md`).
|
||||||
|
|
||||||
## Runtime components
|
## Runtime components
|
||||||
|
|
||||||
| Component | Version / pin | Licence | Notice |
|
| Component | Version / pin | Licence | Notice |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| Lensfun library | `655a9c4` | LGPL-3.0-or-later | © Lensfun contributors — https://github.com/lensfun/lensfun |
|
| Lensfun camera/lens database (data only) | `655a9c4` | CC BY-SA 3.0 Unported | © Lensfun contributors — https://creativecommons.org/licenses/by-sa/3.0/ |
|
||||||
| Lensfun camera/lens database | `655a9c4` | CC BY-SA 3.0 Unported | © Lensfun contributors — https://creativecommons.org/licenses/by-sa/3.0/ |
|
|
||||||
| Lensfun WebAssembly wrapper | 0.1.3 | MIT | © 2026 lex — https://github.com/lexluthor0304/LensfunWasm |
|
|
||||||
| LibRaw (compiled into `libraw-wasm`) | via `libraw-wasm` 1.6.0 | LGPL-2.1 **or** CDDL-1.0 | © LibRaw LLC — https://github.com/LibRaw/LibRaw |
|
| LibRaw (compiled into `libraw-wasm`) | via `libraw-wasm` 1.6.0 | LGPL-2.1 **or** CDDL-1.0 | © LibRaw LLC — https://github.com/LibRaw/LibRaw |
|
||||||
| `libraw-wasm` | 1.6.0 | ISC | Copyright holder not stated by the package — https://github.com/ybouane/LibRaw-Wasm |
|
| `libraw-wasm` | 1.6.0 | ISC | Copyright holder not stated by the package — https://github.com/ybouane/LibRaw-Wasm |
|
||||||
| `sharp` | 0.35.5 | Apache-2.0 | https://github.com/lovell/sharp |
|
| `sharp` | 0.35.5 | Apache-2.0 | https://github.com/lovell/sharp |
|
||||||
| libvips (bundled in `sharp` binaries) | shipped by `sharp` 0.35.5 | LGPL-2.1-or-later | © libvips contributors — https://github.com/libvips/libvips |
|
| libvips (bundled in `sharp` binaries) | shipped by `sharp` 0.35.5 | LGPL-2.1-or-later | © libvips contributors — https://github.com/libvips/libvips |
|
||||||
| tinyxml2 (in the Lensfun WASM) | — | zlib | © Lee Thomason — https://github.com/leethomason/tinyxml2 |
|
|
||||||
| utf8proc (in the Lensfun WASM) | — | MIT | © utf8proc contributors — https://github.com/JuliaStrings/utf8proc |
|
|
||||||
| `exifr` | 7.1.3 | MIT | © 2020 Mike Kovařík, Mutiny.cz — https://github.com/MikeKovarik/exifr |
|
| `exifr` | 7.1.3 | MIT | © 2020 Mike Kovařík, Mutiny.cz — https://github.com/MikeKovarik/exifr |
|
||||||
| `nodemailer` | 7.0.13 | MIT-0 | © 2011-2023 Andris Reinman — https://github.com/nodemailer/nodemailer |
|
| `nodemailer` | 7.0.13 | MIT-0 | © 2011-2023 Andris Reinman — https://github.com/nodemailer/nodemailer |
|
||||||
| React / React DOM | 18.3.1 | MIT | © Facebook, Inc. and its affiliates — https://github.com/facebook/react |
|
| React / React DOM | 18.3.1 | MIT | © Facebook, Inc. and its affiliates — https://github.com/facebook/react |
|
||||||
|
|
||||||
The Lensfun database is a separate asset from the Lensfun library: CC BY-SA 3.0
|
The lens database is a separate asset from Luminary's code: CC BY-SA 3.0 applies to
|
||||||
applies to the profile data, not to Luminary's application code. Attribution and
|
Lensfun's calibration data, not to the correction engine that reads it. Attribution and
|
||||||
share-alike requirements are summarised in the README under
|
share-alike requirements are summarised in the README under
|
||||||
[Third-party attribution and licences](README.md#third-party-attribution-and-licences).
|
[Third-party attribution and licences](README.md#third-party-attribution-and-licences).
|
||||||
|
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ This matters because an earlier design assumed an Electron desktop app. It is no
|
|||||||
- **Raw path:** `libraw-wasm` in a `worker_threads` pool (`server/libraw-pool.mjs`),
|
- **Raw path:** `libraw-wasm` in a `worker_threads` pool (`server/libraw-pool.mjs`),
|
||||||
`open()` + `imageData()` → 8-bit sRGB JPEG proxy at `RAW_PREVIEW_EDGE = 6000`
|
`open()` + `imageData()` → 8-bit sRGB JPEG proxy at `RAW_PREVIEW_EDGE = 6000`
|
||||||
long edge (`server/config.mjs:14`, `RAW_PREVIEW_EDGE`). `sharp` for JPEG ingest,
|
long edge (`server/config.mjs:14`, `RAW_PREVIEW_EDGE`). `sharp` for JPEG ingest,
|
||||||
`lensfun-wasm` for lens correction.
|
Lensfun's calibration data with Luminary's own correction engine (`src/lib/lensEngine.ts`).
|
||||||
- **Renderer:** `src/gl/renderer.ts`. `setImage()` uploads one `u_src` texture
|
- **Renderer:** `src/gl/renderer.ts`. `setImage()` uploads one `u_src` texture
|
||||||
(`:1144`), grade pass samples it at `:1296`, finish pass at `:1553`.
|
(`:1144`), grade pass samples it at `:1296`, finish pass at `:1553`.
|
||||||
- **Export:** `src/lib/export.ts` builds a fresh `Renderer` from `getBitmap()` — a
|
- **Export:** `src/lib/export.ts` builds a fresh `Renderer` from `getBitmap()` — a
|
||||||
|
|||||||
|
After Width: | Height: | Size: 488 KiB |
|
Before Width: | Height: | Size: 390 KiB After Width: | Height: | Size: 488 KiB |
|
Before Width: | Height: | Size: 18 KiB After Width: | Height: | Size: 23 KiB |
|
Before Width: | Height: | Size: 17 KiB After Width: | Height: | Size: 43 KiB |
|
Before Width: | Height: | Size: 373 KiB After Width: | Height: | Size: 764 KiB |
|
Before Width: | Height: | Size: 343 KiB After Width: | Height: | Size: 365 KiB |
|
Before Width: | Height: | Size: 342 KiB After Width: | Height: | Size: 651 KiB |
|
Before Width: | Height: | Size: 51 KiB After Width: | Height: | Size: 116 KiB |
|
Before Width: | Height: | Size: 42 KiB After Width: | Height: | Size: 126 KiB |
|
Before Width: | Height: | Size: 174 KiB After Width: | Height: | Size: 187 KiB |
|
Before Width: | Height: | Size: 202 KiB After Width: | Height: | Size: 246 KiB |
|
Before Width: | Height: | Size: 192 KiB After Width: | Height: | Size: 394 KiB |
|
Before Width: | Height: | Size: 146 KiB After Width: | Height: | Size: 343 KiB |
|
Before Width: | Height: | Size: 185 KiB |
|
After Width: | Height: | Size: 501 KiB |
|
After Width: | Height: | Size: 384 KiB |
|
After Width: | Height: | Size: 285 KiB |
|
After Width: | Height: | Size: 226 KiB |
|
After Width: | Height: | Size: 398 KiB |
|
After Width: | Height: | Size: 198 KiB |
|
After Width: | Height: | Size: 111 KiB |
|
After Width: | Height: | Size: 114 KiB |
@@ -0,0 +1,212 @@
|
|||||||
|
# Linux (Ubuntu) bundle (optional)
|
||||||
|
|
||||||
|
An additive, self-contained way to produce a double-clickable Linux desktop
|
||||||
|
install of Luminary. The server and Docker workflow stay the source of truth:
|
||||||
|
this folder only *packages* the existing `dist/` + `server/` output, and the
|
||||||
|
build writes its artifacts **outside the checkout** — exactly like
|
||||||
|
[`windows/`](../windows/README.md).
|
||||||
|
|
||||||
|
## Isolation guarantees
|
||||||
|
|
||||||
|
1. **The packaging tree is additive.** There is no `package.json` script for
|
||||||
|
this, and no change to `.gitignore` (beyond ignoring the tarball in
|
||||||
|
`releases/`), `.dockerignore`, `Dockerfile`, `docker-compose.yml` or
|
||||||
|
`scripts/deploy.mjs`. Invoke it directly: `node linux/build.mjs`. The only
|
||||||
|
app-side behaviour used is the opt-in desktop mode in `server/config.mjs` +
|
||||||
|
`server/index.mjs` (`LUMINARY_LOCAL=1`), which the Windows launcher already
|
||||||
|
introduced; it stays off unless the launcher sets it.
|
||||||
|
2. **Artifacts live outside the repo** (default: `~/.cache/luminary-linux`). The
|
||||||
|
script refuses an `--out` inside the checkout, because `scripts/deploy.mjs`
|
||||||
|
rsyncs the worktree to production and `docker build` would pull a ~300 MB
|
||||||
|
bundle into its context.
|
||||||
|
3. **The worktree must be clean outside `linux/`** before and after a build (the
|
||||||
|
untracked `logo.png` is tolerated). `--allow-dirty` overrides it.
|
||||||
|
4. **Nothing in the app changes at run time.** The bundle is the unchanged
|
||||||
|
`server/` + `dist/` + production `node_modules`, started with `PORT`, `HOST`,
|
||||||
|
`NODE_ENV` and `LUMINARY_DATA` — all variables the server already reads.
|
||||||
|
|
||||||
|
## What the end user needs
|
||||||
|
|
||||||
|
Ubuntu 22.04 or 24.04, 64-bit, and a browser. Nothing to install: Node 24 is
|
||||||
|
inside the bundle (`runtime/bin/node`), sharp's Linux binaries are bundled, and
|
||||||
|
there is no deb, no apt step and no root.
|
||||||
|
|
||||||
|
| Piece | What it uses |
|
||||||
|
| --- | --- |
|
||||||
|
| `runtime/bin/node` | the official Node 24 linux-x64 build, SHA-256 checked against nodejs.org |
|
||||||
|
| `sharp` | `@img/sharp-linux-x64` + `@img/sharp-libvips-linux-x64`, installed from this repo's lockfile |
|
||||||
|
| app window | Chrome, Chromium, Edge, Brave or Vivaldi `--app=`; Firefox and the default browser are fallbacks |
|
||||||
|
| Develop module | a browser with WebGL2 |
|
||||||
|
|
||||||
|
## Build
|
||||||
|
|
||||||
|
```bash
|
||||||
|
node linux/build.mjs # npm run build, then the bundle
|
||||||
|
node linux/build.mjs --skip-build # reuse the existing dist/
|
||||||
|
node linux/build.mjs --out /srv/builds/luminary-linux
|
||||||
|
node linux/build.mjs --skip-build --publish
|
||||||
|
```
|
||||||
|
|
||||||
|
Output:
|
||||||
|
|
||||||
|
```
|
||||||
|
<out>/
|
||||||
|
Luminary-0.5.1-linux-x64.tar.gz portable bundle
|
||||||
|
Luminary-0.5.1-linux-amd64.deb Ubuntu package, built from the same bundle
|
||||||
|
stage/Luminary/ the unpacked bundle (kept for inspection)
|
||||||
|
cache/node-v24.22.2-linux-x64.tar.gz
|
||||||
|
cache/SHASUMS256-v24.22.2.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
The build prints the archive size, its SHA-256, the Node version, the .deb size
|
||||||
|
and the staged folder. The tarball keeps the executable bits on `luminary` and
|
||||||
|
`runtime/bin/node`, so extracting it is enough — no `chmod` needed. The `.deb`
|
||||||
|
is built with the `dpkg` package's `dpkg-deb` when it is installed; on a host
|
||||||
|
without it the build prints a warning and produces only the tarball.
|
||||||
|
|
||||||
|
### Installing on Ubuntu
|
||||||
|
|
||||||
|
Easiest: install the `.deb`, which puts the app in `/opt/luminary`, adds
|
||||||
|
`/usr/bin/luminary`, an applications-menu entry and the icon. Your photos and
|
||||||
|
catalog still live in `~/.local/share/luminary`, so removing or upgrading the
|
||||||
|
package never touches them:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo apt install ./Luminary-0.5.1-linux-amd64.deb
|
||||||
|
luminary # or launch Luminary from the applications menu
|
||||||
|
```
|
||||||
|
|
||||||
|
`apt` pulls in the two runtime libraries it needs (`libstdc++6`, `libgomp1`);
|
||||||
|
Node, the server and sharp's Linux binaries are inside the package. Uninstall
|
||||||
|
with `sudo apt remove luminary`; `sudo apt purge luminary` also removes
|
||||||
|
`/opt/luminary` but never the data folder.
|
||||||
|
|
||||||
|
Or stay portable — nothing installed, nothing to root:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
tar -xzf Luminary-0.5.1-linux-x64.tar.gz
|
||||||
|
cd Luminary
|
||||||
|
./luminary # starts desktop mode and opens the app window
|
||||||
|
./install.sh # optional: add Luminary to the applications menu
|
||||||
|
```
|
||||||
|
|
||||||
|
`--publish` copies the tarball and a `SHA256SUMS.txt` into
|
||||||
|
[`releases/`](releases/), the hand-off folder for a USB stick, network share or
|
||||||
|
release upload. That is the only write the builder makes inside the checkout.
|
||||||
|
`scripts/deploy.mjs` rsyncs the worktree, so remove the tarball from `releases/`
|
||||||
|
after transferring if you do not want it on the server.
|
||||||
|
|
||||||
|
## What is in the bundle
|
||||||
|
|
||||||
|
```
|
||||||
|
Luminary/
|
||||||
|
luminary bash launcher: start, health wait, app window
|
||||||
|
install.sh adds ~/.local/share/applications/luminary.desktop
|
||||||
|
Luminary.png 256×256 icon for the menu
|
||||||
|
version.txt version, commit, and the Node pin (version, SHA-256, size)
|
||||||
|
README-linux.txt end-user instructions
|
||||||
|
LICENSE, THIRD_PARTY_NOTICES.md, licenses/
|
||||||
|
runtime/ official Node 24 linux-x64 (bin/node, lib/node_modules)
|
||||||
|
app/
|
||||||
|
server/ unchanged, minus server/data and *.test.mjs
|
||||||
|
dist/ the normal Vite build (UI, lens db, guide PDF)
|
||||||
|
package.json provenance
|
||||||
|
package-lock.json
|
||||||
|
node_modules/ production deps installed with --os=linux --cpu=x64
|
||||||
|
```
|
||||||
|
|
||||||
|
## Running it
|
||||||
|
|
||||||
|
`./luminary` picks a free loopback port from 8787, sets
|
||||||
|
`LUMINARY_DATA=~/.local/share/luminary`, starts the server with
|
||||||
|
`LUMINARY_LOCAL=1`, waits for `/api/health`, then opens a chromeless window:
|
||||||
|
|
||||||
|
```
|
||||||
|
google-chrome --app=http://127.0.0.1:8787 \
|
||||||
|
--user-data-dir=~/.local/share/luminary/window-profile \
|
||||||
|
--class=Luminary
|
||||||
|
```
|
||||||
|
|
||||||
|
No tabs, no address bar, its own profile and window size. `./luminary --browser`
|
||||||
|
opens a normal tab instead (`LUMINARY_WINDOW=browser` works too).
|
||||||
|
|
||||||
|
| Command | What it does |
|
||||||
|
| --- | --- |
|
||||||
|
| `./luminary` | start (or reuse a running server) and open the window |
|
||||||
|
| `./luminary --stop` | stop the server; data stays |
|
||||||
|
| `./luminary --status` | bundle, data folder, pid, URL and `/api/health` |
|
||||||
|
| `./luminary --verify` | list any missing piece of the bundle |
|
||||||
|
| `./luminary --install` | add the applications-menu entry |
|
||||||
|
| `./luminary --uninstall` | remove that entry, keep the catalog |
|
||||||
|
|
||||||
|
The `.deb` installs the same launcher as `/usr/bin/luminary`, so every flag
|
||||||
|
works there too (`luminary --stop`, `--status`, `--verify`). Its data folder is
|
||||||
|
the same `~/.local/share/luminary`.
|
||||||
|
|
||||||
|
### Single-user desktop mode
|
||||||
|
|
||||||
|
The launcher starts the server with `LUMINARY_LOCAL=1`, the same mode the
|
||||||
|
Windows bundle uses:
|
||||||
|
|
||||||
|
- one admin (`local@luminary`) is created on first start and reused afterwards;
|
||||||
|
- `/api/auth/me` answers without a cookie, so the UI never shows signup or
|
||||||
|
sign-in, and registration returns 403;
|
||||||
|
- the account is an admin, so every panel works, with no password to remember;
|
||||||
|
- the server binds `127.0.0.1`, so this is not reachable from the network.
|
||||||
|
Starting with `HOST=0.0.0.0` and `LUMINARY_LOCAL=1` logs a warning at boot.
|
||||||
|
|
||||||
|
## Smoke test
|
||||||
|
|
||||||
|
The automated first pass is [`SMOKE-LINUX.sh`](SMOKE-LINUX.sh). Run it from the
|
||||||
|
extracted bundle (or a `.deb` install):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
./SMOKE-LINUX.sh # bundle in this folder
|
||||||
|
./SMOKE-LINUX.sh --bundle /opt/luminary
|
||||||
|
```
|
||||||
|
|
||||||
|
It reports the distribution, browser and display, checks the bundle files and
|
||||||
|
`luminary --verify`, boots the real server through the launcher in desktop mode
|
||||||
|
(`local:true`, cookieless `/api/auth/me`, closed registration, `/api/sync`),
|
||||||
|
checks `--install`/`--uninstall` write and remove a real `.desktop` file, and
|
||||||
|
confirms `--stop` stops it. It uses a throwaway data folder and a private
|
||||||
|
`XDG_DATA_HOME`, so no real catalog or menu entry is touched, and it writes
|
||||||
|
`smoke-report.txt` next to the bundle. The app window itself stays a visual
|
||||||
|
check (the launcher runs with `LUMINARY_WINDOW=none` during the test).
|
||||||
|
|
||||||
|
## Data, updates and backups
|
||||||
|
|
||||||
|
- Catalog, originals, previews, `secret.key`, logs and the window profile live in
|
||||||
|
`~/.local/share/luminary` (or `$LUMINARY_DATA`), never inside the bundle.
|
||||||
|
- Update: `./luminary --stop`, replace `app/` and `runtime/` from a newer
|
||||||
|
bundle, start again. The SQLite schema migrates on boot.
|
||||||
|
- Back up: copy `~/.local/share/luminary` while Luminary is stopped, including
|
||||||
|
`lumenroom.db`, `lumenroom.db-wal`, `lumenroom.db-shm`.
|
||||||
|
|
||||||
|
## Verifying a build
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd <out>
|
||||||
|
sha256sum Luminary-0.5.1-linux-x64.tar.gz
|
||||||
|
tar -tzf Luminary-0.5.1-linux-x64.tar.gz | grep -E 'luminary$|runtime/bin/node$|app/server/index.mjs$'
|
||||||
|
tar -xzf Luminary-0.5.1-linux-x64.tar.gz -C /tmp/luminary-check
|
||||||
|
/tmp/luminary-check/Luminary/luminary --verify
|
||||||
|
```
|
||||||
|
|
||||||
|
On a real desktop also check the window opens, the UI is signed in as the local
|
||||||
|
admin, importing a RAW file works, and `--stop` closes the server.
|
||||||
|
|
||||||
|
## Limitations
|
||||||
|
|
||||||
|
- The `.deb` is unsigned (no repository, no signing key), so `apt` installs it
|
||||||
|
locally without verification and there is no auto-update. Only the portable
|
||||||
|
tarball and the `.deb` are produced — no AppImage or Snap in this version — and
|
||||||
|
there is no tray icon.
|
||||||
|
- The app window depends on a Chromium-based browser being installed; without
|
||||||
|
one it falls back to Firefox or the default browser as a normal window.
|
||||||
|
- Wayland compositors may ignore `--class=Luminary`, so the dock icon can be the
|
||||||
|
browser's.
|
||||||
|
- Loopback only by default; set `HOST=0.0.0.0` when starting the server by hand
|
||||||
|
for LAN proofing galleries.
|
||||||
|
- The launcher cannot clean up after a server crash; a stale PID file is ignored
|
||||||
|
on the next start (`--status` reports "stopped").
|
||||||
@@ -0,0 +1,277 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# One-command smoke test for an extracted Luminary Linux bundle.
|
||||||
|
#
|
||||||
|
# Run it from the extracted bundle folder (or pass --bundle):
|
||||||
|
#
|
||||||
|
# ./SMOKE-LINUX.sh
|
||||||
|
# ./SMOKE-LINUX.sh --bundle /opt/luminary
|
||||||
|
#
|
||||||
|
# It writes smoke-report.txt next to the bundle and prints the same lines.
|
||||||
|
# Exit code 0 means every check passed.
|
||||||
|
#
|
||||||
|
# What it covers without a human clicking:
|
||||||
|
# - distro, architecture, glibc, display, and which browser the launcher picks
|
||||||
|
# - the bundle files the launcher needs, and `luminary --verify`
|
||||||
|
# - a real boot through the launcher in desktop mode: /api/health local:true,
|
||||||
|
# /api/auth/me 200 without a cookie, registration closed, /api/sync 200
|
||||||
|
# - the menu entry install/uninstall writing and removing a real .desktop file
|
||||||
|
# - `luminary --stop` actually stopping the server
|
||||||
|
#
|
||||||
|
# It uses a throwaway data folder under $TMPDIR and a private XDG_DATA_HOME, so
|
||||||
|
# it never touches a real catalog or your applications menu. The app window is
|
||||||
|
# not opened (the launcher runs with LUMINARY_WINDOW=none); it is a visual check.
|
||||||
|
|
||||||
|
set -u
|
||||||
|
|
||||||
|
BUNDLE=""
|
||||||
|
while [ "$#" -gt 0 ]; do
|
||||||
|
case "$1" in
|
||||||
|
--bundle)
|
||||||
|
BUNDLE="${2:-}"
|
||||||
|
shift 2
|
||||||
|
;;
|
||||||
|
--help|-h)
|
||||||
|
sed -n '2,20p' "$0" | sed 's/^# \{0,1\}//'
|
||||||
|
exit 0
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
printf 'unknown option %s (see --help)\n' "$1" >&2
|
||||||
|
exit 2
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
[ -n "$BUNDLE" ] || BUNDLE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||||
|
BUNDLE="$(readlink -f "$BUNDLE")"
|
||||||
|
|
||||||
|
LINES=()
|
||||||
|
FAILED=0
|
||||||
|
SKIPPED=0
|
||||||
|
|
||||||
|
say() {
|
||||||
|
LINES+=("$*")
|
||||||
|
printf '%s\n' "$*"
|
||||||
|
}
|
||||||
|
|
||||||
|
check() {
|
||||||
|
local name="$1" ok="$2" detail="${3:-}"
|
||||||
|
if [ "$ok" = "0" ]; then
|
||||||
|
say " PASS $name${detail:+ — $detail}"
|
||||||
|
else
|
||||||
|
FAILED=$((FAILED + 1))
|
||||||
|
say " FAIL $name${detail:+ — $detail}"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
skip() {
|
||||||
|
SKIPPED=$((SKIPPED + 1))
|
||||||
|
say " SKIP $1${2:+ — $2}"
|
||||||
|
}
|
||||||
|
|
||||||
|
[ -x "$BUNDLE/runtime/bin/node" ] && NODE="$BUNDLE/runtime/bin/node" || NODE="$(command -v node 2>/dev/null || true)"
|
||||||
|
if [ -z "$NODE" ]; then
|
||||||
|
printf 'Luminary: no Node runtime found in the bundle or on PATH\n' >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
WORK_DIR="$(mktemp -d "${TMPDIR:-/tmp}/luminary-smoke.XXXXXX")" || exit 1
|
||||||
|
export XDG_DATA_HOME="$WORK_DIR/xdg"
|
||||||
|
export LUMINARY_DATA="$WORK_DIR/data"
|
||||||
|
export LUMINARY_WINDOW=none
|
||||||
|
BODY="$WORK_DIR/body.json"
|
||||||
|
URL=""
|
||||||
|
|
||||||
|
cleanup() {
|
||||||
|
if [ -x "$BUNDLE/luminary" ] && [ -f "$LUMINARY_DATA/luminary.pid" ]; then
|
||||||
|
"$BUNDLE/luminary" --stop >/dev/null 2>&1 || true
|
||||||
|
fi
|
||||||
|
rm -rf "$WORK_DIR"
|
||||||
|
}
|
||||||
|
trap cleanup EXIT
|
||||||
|
|
||||||
|
# http <method> <url> [json-body] -> status code on stdout, body in $BODY
|
||||||
|
http() {
|
||||||
|
"$NODE" -e '
|
||||||
|
const [method, url, payload, out] = process.argv.slice(-4);
|
||||||
|
const init = { method };
|
||||||
|
if (payload) {
|
||||||
|
init.headers = { "Content-Type": "application/json" };
|
||||||
|
init.body = payload;
|
||||||
|
}
|
||||||
|
fetch(url, init)
|
||||||
|
.then(async (r) => { require("node:fs").writeFileSync(out, await r.text()); process.stdout.write(String(r.status)); })
|
||||||
|
.catch(() => process.stdout.write("0"));
|
||||||
|
' "$1" "$2" "${3:-}" "$BODY"
|
||||||
|
}
|
||||||
|
|
||||||
|
# jget <dotted.path> -> value from the last response body
|
||||||
|
jget() {
|
||||||
|
"$NODE" -e '
|
||||||
|
const fs = require("node:fs");
|
||||||
|
let value;
|
||||||
|
try { value = JSON.parse(fs.readFileSync(process.argv.slice(-2)[0], "utf8")); } catch { process.exit(0); }
|
||||||
|
for (const key of process.argv.slice(-1)[0].split(".")) value = value == null ? value : value[key];
|
||||||
|
if (value !== undefined && value !== null) process.stdout.write(String(value));
|
||||||
|
' "$BODY" "$1"
|
||||||
|
}
|
||||||
|
|
||||||
|
browser_name() {
|
||||||
|
local name
|
||||||
|
for name in google-chrome google-chrome-stable chromium chromium-browser \
|
||||||
|
microsoft-edge microsoft-edge-stable brave-browser vivaldi-stable firefox; do
|
||||||
|
if command -v "$name" >/dev/null 2>&1; then
|
||||||
|
printf '%s' "$name"
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
say 'Luminary Linux smoke test'
|
||||||
|
say " bundle $BUNDLE"
|
||||||
|
say " time $(date -Is)"
|
||||||
|
|
||||||
|
say ''
|
||||||
|
say 'Environment'
|
||||||
|
if [ -r /etc/os-release ]; then
|
||||||
|
# shellcheck disable=SC1091
|
||||||
|
distro="$(. /etc/os-release && printf '%s' "${PRETTY_NAME:-${NAME:-unknown}}")"
|
||||||
|
else
|
||||||
|
distro="$(uname -s)"
|
||||||
|
fi
|
||||||
|
say " distro $distro"
|
||||||
|
say " arch $(uname -m)"
|
||||||
|
say " kernel $(uname -r)"
|
||||||
|
say " glibc $(ldd --version 2>/dev/null | head -n 1 || printf 'unknown')"
|
||||||
|
say " display ${DISPLAY:-none}${WAYLAND_DISPLAY:+ (wayland $WAYLAND_DISPLAY)}"
|
||||||
|
if browser="$(browser_name)"; then
|
||||||
|
say " browser $browser"
|
||||||
|
else
|
||||||
|
say ' browser none found (the launcher would fall back to the default browser)'
|
||||||
|
fi
|
||||||
|
|
||||||
|
say ''
|
||||||
|
say 'Bundle'
|
||||||
|
check 'luminary launcher present' $([ -x "$BUNDLE/luminary" ] && echo 0 || echo 1)
|
||||||
|
check 'runtime/bin/node present' $([ -x "$BUNDLE/runtime/bin/node" ] && echo 0 || echo 1) "$BUNDLE/runtime/bin/node"
|
||||||
|
check 'app/server/index.mjs present' $([ -f "$BUNDLE/app/server/index.mjs" ] && echo 0 || echo 1)
|
||||||
|
check 'app/dist/index.html present' $([ -f "$BUNDLE/app/dist/index.html" ] && echo 0 || echo 1)
|
||||||
|
check 'app/node_modules present' $([ -d "$BUNDLE/app/node_modules" ] && echo 0 || echo 1)
|
||||||
|
node_version="$("$NODE" --version 2>/dev/null)"
|
||||||
|
check 'node runs' $([ -n "$node_version" ] && echo 0 || echo 1) "$node_version"
|
||||||
|
check 'node is 24 or newer' "$("$NODE" -e 'process.exit(Number(process.versions.node.split(".")[0]) >= 24 ? 0 : 1)' 2>/dev/null; echo $?)"
|
||||||
|
|
||||||
|
if [ -x "$BUNDLE/luminary" ]; then
|
||||||
|
if "$BUNDLE/luminary" --verify >"$WORK_DIR/verify.txt" 2>&1; then
|
||||||
|
check '--verify exits 0' 0
|
||||||
|
else
|
||||||
|
check '--verify exits 0' 1 "$(tr '\n' ' ' <"$WORK_DIR/verify.txt")"
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
check '--verify exits 0' 1 'launcher missing'
|
||||||
|
fi
|
||||||
|
|
||||||
|
say ''
|
||||||
|
say 'Server (desktop mode, via the launcher)'
|
||||||
|
"$BUNDLE/luminary" >"$WORK_DIR/start.txt" 2>&1
|
||||||
|
start_status=$?
|
||||||
|
check 'launcher start exits 0' "$start_status" "$(head -n 1 "$WORK_DIR/start.txt")"
|
||||||
|
|
||||||
|
if [ -f "$LUMINARY_DATA/runtime.json" ]; then
|
||||||
|
check 'runtime.json written' 0
|
||||||
|
URL="http://127.0.0.1:$("$NODE" -p "JSON.parse(require('fs').readFileSync('$LUMINARY_DATA/runtime.json','utf8')).port")"
|
||||||
|
else
|
||||||
|
check 'runtime.json written' 1 "$LUMINARY_DATA/runtime.json"
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ -n "$URL" ]; then
|
||||||
|
code="$(http GET "$URL/api/health")"
|
||||||
|
check 'health answers' $([ "$code" = "200" ] && echo 0 || echo 1) "HTTP $code"
|
||||||
|
if [ "$code" = "200" ]; then
|
||||||
|
check 'local mode advertised' $([ "$(jget local)" = "true" ] && echo 0 || echo 1) "local=$(jget local)"
|
||||||
|
check 'version advertised' $([ -n "$(jget version)" ] && echo 0 || echo 1) "version=$(jget version)"
|
||||||
|
check 'no setup prompt' $([ "$(jget needsSetup)" = "false" ] && echo 0 || echo 1)
|
||||||
|
check 'registration closed' $([ "$(jget registrationOpen)" = "false" ] && echo 0 || echo 1)
|
||||||
|
check 'libraw ready' $([ "$(jget raw.libraw)" = "true" ] && echo 0 || echo 1)
|
||||||
|
check 'sharp ready' $([ "$(jget raw.sharp)" = "true" ] && echo 0 || echo 1)
|
||||||
|
fi
|
||||||
|
|
||||||
|
code="$(http GET "$URL/api/auth/me")"
|
||||||
|
me_email="$(jget user.email)"
|
||||||
|
me_role="$(jget user.role)"
|
||||||
|
check 'signed in without a cookie' $([ "$code" = "200" ] && echo 0 || echo 1) "HTTP $code $me_email ($me_role)"
|
||||||
|
|
||||||
|
code="$(http POST "$URL/api/auth/register" '{"email":"smoke@example.test","password":"smoke-test-password"}')"
|
||||||
|
check 'registration refused' $([ "$code" = "403" ] && echo 0 || echo 1) "HTTP $code"
|
||||||
|
|
||||||
|
code="$(http GET "$URL/api/sync")"
|
||||||
|
check '/api/sync answers' $([ "$code" = "200" ] && echo 0 || echo 1) "HTTP $code"
|
||||||
|
|
||||||
|
code="$(http GET "$URL/")"
|
||||||
|
check 'UI index served' $([ "$code" = "200" ] && echo 0 || echo 1) "HTTP $code"
|
||||||
|
if [ "$code" = "200" ] && grep -q 'src/assets\|assets/' "$BODY"; then
|
||||||
|
check 'UI references built assets' 0
|
||||||
|
else
|
||||||
|
check 'UI references built assets' 1
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
if "$BUNDLE/luminary" --status 2>/dev/null | grep -q 'Status: running'; then
|
||||||
|
check '--status reports running' 0
|
||||||
|
else
|
||||||
|
check '--status reports running' 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
say ''
|
||||||
|
say 'Menu entry'
|
||||||
|
if XDG_DATA_HOME="$WORK_DIR/xdg" "$BUNDLE/luminary" --install >/dev/null 2>&1 &&
|
||||||
|
[ -f "$WORK_DIR/xdg/applications/luminary.desktop" ]; then
|
||||||
|
check '--install writes a .desktop file' 0
|
||||||
|
if grep -q "^Exec=\"\?$BUNDLE/luminary\"\?$" "$WORK_DIR/xdg/applications/luminary.desktop"; then
|
||||||
|
check 'menu entry points at this bundle' 0
|
||||||
|
else
|
||||||
|
check 'menu entry points at this bundle' 1 "$(grep '^Exec=' "$WORK_DIR/xdg/applications/luminary.desktop")"
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
check '--install writes a .desktop file' 1
|
||||||
|
fi
|
||||||
|
if XDG_DATA_HOME="$WORK_DIR/xdg" "$BUNDLE/luminary" --uninstall >/dev/null 2>&1 &&
|
||||||
|
[ ! -f "$WORK_DIR/xdg/applications/luminary.desktop" ]; then
|
||||||
|
check '--uninstall removes it' 0
|
||||||
|
else
|
||||||
|
check '--uninstall removes it' 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
say ''
|
||||||
|
say 'Stop'
|
||||||
|
"$BUNDLE/luminary" --stop >/dev/null 2>&1
|
||||||
|
if [ -n "$URL" ]; then
|
||||||
|
code="$(http GET "$URL/api/health")"
|
||||||
|
check 'server stopped' $([ "$code" = "0" ] && echo 0 || echo 1) "HTTP $code"
|
||||||
|
else
|
||||||
|
check 'server stopped' 1 'server never started'
|
||||||
|
fi
|
||||||
|
if "$BUNDLE/luminary" --status 2>/dev/null | grep -q 'Status: stopped'; then
|
||||||
|
check '--status reports stopped' 0
|
||||||
|
else
|
||||||
|
check '--status reports stopped' 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
say ''
|
||||||
|
say 'Window'
|
||||||
|
skip 'app window opens' 'visual check; the launcher opened nothing during this run'
|
||||||
|
|
||||||
|
say ''
|
||||||
|
if [ "$FAILED" -eq 0 ]; then
|
||||||
|
say 'RESULT: PASS'
|
||||||
|
else
|
||||||
|
say "RESULT: FAIL ($FAILED check(s))"
|
||||||
|
fi
|
||||||
|
|
||||||
|
report="$BUNDLE/smoke-report.txt"
|
||||||
|
if ! { printf '%s\n' "${LINES[@]}" >"$report"; } 2>/dev/null; then
|
||||||
|
report="$(pwd)/smoke-report.txt"
|
||||||
|
printf '%s\n' "${LINES[@]}" >"$report" 2>/dev/null || true
|
||||||
|
fi
|
||||||
|
[ -f "$report" ] && say " report $report"
|
||||||
|
|
||||||
|
[ "$FAILED" -eq 0 ] && exit 0 || exit 1
|
||||||
@@ -0,0 +1,758 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
/**
|
||||||
|
* Build the optional Linux (Ubuntu) desktop bundle for Luminary.
|
||||||
|
*
|
||||||
|
* Like windows/build.mjs this is *outside* the main build: it only reads the
|
||||||
|
* repository (`dist/`, `server/`, `package.json`) and writes everything into a
|
||||||
|
* directory outside the checkout. Nothing in `src/`, `server/`, `package.json`,
|
||||||
|
* the Dockerfile, the deploy script or `dist/` is modified by this file, and no
|
||||||
|
* npm script is added for it. Run it directly:
|
||||||
|
*
|
||||||
|
* node linux/build.mjs # build dist/ then the bundle
|
||||||
|
* node linux/build.mjs --skip-build # reuse the existing dist/
|
||||||
|
* node linux/build.mjs --out /srv/lum # choose the output directory
|
||||||
|
*
|
||||||
|
* The bundle keeps the layout the server expects (it derives `DIST_DIR` from
|
||||||
|
* the parent of `server/`), so it is a plain folder plus a launcher:
|
||||||
|
*
|
||||||
|
* <out>/Luminary/
|
||||||
|
* luminary bash launcher: start, health wait, app window
|
||||||
|
* install.sh adds Luminary to the Ubuntu applications menu
|
||||||
|
* Luminary.png icon
|
||||||
|
* runtime/bin/node official Node 24 linux-x64, SHA-256 checked
|
||||||
|
* app/ unchanged server/, dist/, production node_modules/
|
||||||
|
* README-linux.txt
|
||||||
|
* version.txt
|
||||||
|
*/
|
||||||
|
import { createHash } from 'node:crypto';
|
||||||
|
import { spawnSync } from 'node:child_process';
|
||||||
|
import {
|
||||||
|
chmodSync,
|
||||||
|
cpSync,
|
||||||
|
existsSync,
|
||||||
|
lstatSync,
|
||||||
|
mkdirSync,
|
||||||
|
readFileSync,
|
||||||
|
readdirSync,
|
||||||
|
renameSync,
|
||||||
|
rmSync,
|
||||||
|
statSync,
|
||||||
|
symlinkSync,
|
||||||
|
writeFileSync,
|
||||||
|
} from 'node:fs';
|
||||||
|
import os from 'node:os';
|
||||||
|
import path from 'node:path';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
|
||||||
|
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
||||||
|
const ROOT = path.resolve(HERE, '..');
|
||||||
|
const LAUNCHER_FILES = path.join(HERE, 'launcher');
|
||||||
|
const RELEASES_DIR = path.join(HERE, 'releases');
|
||||||
|
const NPM = 'npm';
|
||||||
|
const DEFAULT_NODE = 'v24.22.2';
|
||||||
|
|
||||||
|
const HELP = `Luminary Linux (Ubuntu) bundle
|
||||||
|
|
||||||
|
Usage: node linux/build.mjs [options]
|
||||||
|
|
||||||
|
--out <dir> output directory (default: <cache>/luminary-linux).
|
||||||
|
Must be outside this repository; the bundle is staged in
|
||||||
|
<out>/stage and archived to
|
||||||
|
<out>/Luminary-<ver>-linux-x64.tar.gz.
|
||||||
|
--skip-build reuse the existing dist/ instead of running npm run build
|
||||||
|
--node <version> bundled Node version, e.g. v24.22.2 (must be >= 24)
|
||||||
|
--allow-dirty skip the check that the checkout is clean outside linux/
|
||||||
|
--publish copy the finished tar.gz and .deb to linux/releases (plus
|
||||||
|
a SHA256SUMS.txt) so they can be handed off or uploaded
|
||||||
|
--help print this text
|
||||||
|
|
||||||
|
Nothing in the repository is modified: the only writes outside the output
|
||||||
|
directory are the ones npm and nodejs.org make for their own caches.
|
||||||
|
`;
|
||||||
|
|
||||||
|
function fail(message) {
|
||||||
|
process.stderr.write(`linux: FAILED: ${message}\n`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
function log(step, message) {
|
||||||
|
process.stdout.write(`linux: ${step.padEnd(9)} ${message}\n`);
|
||||||
|
}
|
||||||
|
|
||||||
|
function warn(message) {
|
||||||
|
process.stderr.write(`linux: warning: ${message}\n`);
|
||||||
|
}
|
||||||
|
|
||||||
|
function defaultOutDir() {
|
||||||
|
return path.join(process.env.XDG_CACHE_HOME || path.join(os.homedir(), '.cache'), 'luminary-linux');
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseArgs(argv) {
|
||||||
|
const options = {
|
||||||
|
out: defaultOutDir(),
|
||||||
|
node: DEFAULT_NODE,
|
||||||
|
build: true,
|
||||||
|
allowDirty: false,
|
||||||
|
publish: false,
|
||||||
|
help: false,
|
||||||
|
};
|
||||||
|
const value = (index, flag) => {
|
||||||
|
const next = argv[index + 1];
|
||||||
|
if (!next || next.startsWith('--')) fail(`${flag} needs a value`);
|
||||||
|
return next;
|
||||||
|
};
|
||||||
|
for (let i = 0; i < argv.length; i++) {
|
||||||
|
const arg = argv[i];
|
||||||
|
if (arg === '--out') {
|
||||||
|
options.out = path.resolve(value(i, arg));
|
||||||
|
i += 1;
|
||||||
|
} else if (arg === '--node') {
|
||||||
|
const version = value(i, arg);
|
||||||
|
options.node = version.startsWith('v') ? version : `v${version}`;
|
||||||
|
i += 1;
|
||||||
|
} else if (arg === '--skip-build') {
|
||||||
|
options.build = false;
|
||||||
|
} else if (arg === '--allow-dirty') {
|
||||||
|
options.allowDirty = true;
|
||||||
|
} else if (arg === '--publish') {
|
||||||
|
options.publish = true;
|
||||||
|
} else if (arg === '--help' || arg === '-h') {
|
||||||
|
options.help = true;
|
||||||
|
} else {
|
||||||
|
fail(`unknown option ${arg} (see --help)`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!/^v\d+\.\d+\.\d+$/.test(options.node)) {
|
||||||
|
fail(`--node must look like v24.22.2 (got ${options.node})`);
|
||||||
|
}
|
||||||
|
return options;
|
||||||
|
}
|
||||||
|
|
||||||
|
function git(args, { trim = true } = {}) {
|
||||||
|
const result = spawnSync('git', args, { cwd: ROOT, encoding: 'utf8' });
|
||||||
|
if (result.error || result.status !== 0) return null;
|
||||||
|
return trim ? result.stdout.trim() : result.stdout;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The bundle must not land in the checkout: a staged Node runtime and
|
||||||
|
* node_modules would otherwise be rsynced to production by scripts/deploy.mjs
|
||||||
|
* and grow the Docker build context.
|
||||||
|
*/
|
||||||
|
function assertOutsideRepo(outDir) {
|
||||||
|
const relative = path.relative(ROOT, outDir);
|
||||||
|
const inside = !relative.startsWith('..') && !path.isAbsolute(relative);
|
||||||
|
if (inside) {
|
||||||
|
fail(
|
||||||
|
`--out resolves inside the repository (${outDir}).\n` +
|
||||||
|
'The bundle is large and would be copied by the deploy rsync; pick an\n' +
|
||||||
|
'output directory outside the checkout, or omit --out to use the cache.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Only this folder may be dirty. `logo.png` is a long-standing untracked asset
|
||||||
|
* in this checkout and is not part of the app, so it is tolerated.
|
||||||
|
*/
|
||||||
|
function checkRepoClean(options) {
|
||||||
|
const status = git(['status', '--porcelain'], { trim: false });
|
||||||
|
if (status === null) {
|
||||||
|
warn('git is unavailable here; skipping the worktree check');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const unexpected = status
|
||||||
|
.split('\n')
|
||||||
|
.filter((line) => line.length > 3)
|
||||||
|
.map((line) => line.slice(3).replace(/^"|"$/g, '').replace(/^.* -> /, '').trim())
|
||||||
|
.filter((file) => file && !file.startsWith('linux/') && file !== 'logo.png');
|
||||||
|
if (!unexpected.length) return;
|
||||||
|
if (options.allowDirty) {
|
||||||
|
warn(`building from a modified checkout: ${unexpected.join(', ')}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
fail(
|
||||||
|
`the checkout has changes outside linux/:\n ${unexpected.join('\n ')}\n` +
|
||||||
|
'Commit or stash them, or pass --allow-dirty to build anyway.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function readPackage() {
|
||||||
|
const file = path.join(ROOT, 'package.json');
|
||||||
|
if (!existsSync(file)) fail('run this from a Luminary checkout (package.json missing)');
|
||||||
|
return JSON.parse(readFileSync(file, 'utf8'));
|
||||||
|
}
|
||||||
|
|
||||||
|
function run(command, args, cwd, extraEnv) {
|
||||||
|
log('run', [command, ...args].join(' '));
|
||||||
|
const result = spawnSync(command, args, {
|
||||||
|
cwd,
|
||||||
|
stdio: 'inherit',
|
||||||
|
env: extraEnv ? { ...process.env, ...extraEnv } : process.env,
|
||||||
|
});
|
||||||
|
if (result.error) fail(`${command} could not start: ${result.error.message}`);
|
||||||
|
if (result.status !== 0) fail(`${command} ${args.join(' ')} exited with ${result.status}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
function ensureUi(options) {
|
||||||
|
const dist = path.join(ROOT, 'dist', 'index.html');
|
||||||
|
if (options.build) {
|
||||||
|
log('ui', 'npm run build (typecheck + vite build, the normal artifact)');
|
||||||
|
run(NPM, ['run', 'build'], ROOT);
|
||||||
|
} else {
|
||||||
|
log('ui', 'reusing the existing dist/ (--skip-build)');
|
||||||
|
}
|
||||||
|
if (!existsSync(dist)) {
|
||||||
|
fail('dist/index.html is missing; drop --skip-build or run "npm run build" first');
|
||||||
|
}
|
||||||
|
return dist;
|
||||||
|
}
|
||||||
|
|
||||||
|
function copyServer(bundle) {
|
||||||
|
const server = path.join(bundle, 'app', 'server');
|
||||||
|
cpSync(path.join(ROOT, 'server'), server, {
|
||||||
|
recursive: true,
|
||||||
|
filter: (source) => {
|
||||||
|
const relative = path.relative(path.join(ROOT, 'server'), source).split(path.sep).join('/');
|
||||||
|
// The developer catalog and the test files never belong in a bundle.
|
||||||
|
if (relative === 'data' || relative.startsWith('data/')) return false;
|
||||||
|
if (/\.test\.mjs$/.test(relative)) return false;
|
||||||
|
return true;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function copyLegal(bundle) {
|
||||||
|
for (const name of ['LICENSE', 'THIRD_PARTY_NOTICES.md']) {
|
||||||
|
const source = path.join(ROOT, name);
|
||||||
|
if (existsSync(source)) cpSync(source, path.join(bundle, name));
|
||||||
|
}
|
||||||
|
const licenses = path.join(ROOT, 'licenses');
|
||||||
|
if (existsSync(licenses)) cpSync(licenses, path.join(bundle, 'licenses'), { recursive: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
function installLinuxDeps(bundle) {
|
||||||
|
const appDir = path.join(bundle, 'app');
|
||||||
|
cpSync(path.join(ROOT, 'package.json'), path.join(appDir, 'package.json'));
|
||||||
|
cpSync(path.join(ROOT, 'package-lock.json'), path.join(appDir, 'package-lock.json'));
|
||||||
|
log('deps', 'npm ci --omit=dev --os=linux --cpu=x64 (sharp linux-x64 prebuild)');
|
||||||
|
// --ignore-scripts is safe: sharp 0.35 has no install step, it resolves the
|
||||||
|
// prebuilt binary through optionalDependencies.
|
||||||
|
run(
|
||||||
|
NPM,
|
||||||
|
['ci', '--omit=dev', '--os=linux', '--cpu=x64', '--no-audit', '--no-fund', '--ignore-scripts'],
|
||||||
|
appDir,
|
||||||
|
);
|
||||||
|
// .bin shims are for an interactive shell, not for `node server/index.mjs`.
|
||||||
|
rmSync(path.join(appDir, 'node_modules', '.bin'), { recursive: true, force: true });
|
||||||
|
verifySharp(appDir);
|
||||||
|
}
|
||||||
|
|
||||||
|
function verifySharp(appDir) {
|
||||||
|
const dir = path.join(appDir, 'node_modules', '@img', 'sharp-linux-x64');
|
||||||
|
if (!existsSync(dir)) {
|
||||||
|
warn('@img/sharp-linux-x64 is missing; the server will fall back to PNG proxies');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const binaries = [];
|
||||||
|
const walk = (current) => {
|
||||||
|
for (const entry of readdirSync(current, { withFileTypes: true })) {
|
||||||
|
const absolute = path.join(current, entry.name);
|
||||||
|
if (entry.isDirectory()) walk(absolute);
|
||||||
|
else if (/\.(node|so(\.\d+)*)$/i.test(entry.name)) binaries.push(path.relative(dir, absolute));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
walk(dir);
|
||||||
|
if (!binaries.some((file) => file.endsWith('.node'))) {
|
||||||
|
warn('@img/sharp-linux-x64 has no .node binary; check the installed package');
|
||||||
|
} else {
|
||||||
|
log('deps', `sharp linux-x64 ready (${binaries.length} native files)`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function sha256File(file) {
|
||||||
|
return createHash('sha256').update(readFileSync(file)).digest('hex');
|
||||||
|
}
|
||||||
|
|
||||||
|
async function download(url) {
|
||||||
|
const response = await fetch(url);
|
||||||
|
if (!response.ok) throw new Error(`${response.status} ${response.statusText} from ${url}`);
|
||||||
|
return Buffer.from(await response.arrayBuffer());
|
||||||
|
}
|
||||||
|
|
||||||
|
function extractTar(archive, destination) {
|
||||||
|
mkdirSync(destination, { recursive: true });
|
||||||
|
const result = spawnSync(
|
||||||
|
'tar',
|
||||||
|
['-xzf', archive, '-C', destination, '--strip-components=1'],
|
||||||
|
{ stdio: 'inherit' },
|
||||||
|
);
|
||||||
|
if (result.error || result.status !== 0) {
|
||||||
|
fail(`could not extract ${path.basename(archive)} (is tar installed?)`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function ensureNode(outDir, version) {
|
||||||
|
const major = Number(version.slice(1).split('.')[0]);
|
||||||
|
if (major < 24) {
|
||||||
|
fail(`Node ${version} is too old: node:sqlite and type stripping need 24 LTS`);
|
||||||
|
}
|
||||||
|
const cache = path.join(outDir, 'cache');
|
||||||
|
mkdirSync(cache, { recursive: true });
|
||||||
|
const name = `node-${version}-linux-x64.tar.gz`;
|
||||||
|
const archive = path.join(cache, name);
|
||||||
|
const sums = path.join(cache, `SHASUMS256-${version}.txt`);
|
||||||
|
const base = `https://nodejs.org/dist/${version}`;
|
||||||
|
if (!existsSync(archive)) {
|
||||||
|
// Unlike the Windows node.exe, the Linux tarballs sit at the dist root.
|
||||||
|
log('node', `downloading ${base}/${name}`);
|
||||||
|
try {
|
||||||
|
writeFileSync(archive, await download(`${base}/${name}`));
|
||||||
|
} catch (error) {
|
||||||
|
fail(`could not download ${name}: ${error.message}`);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
log('node', `using cached ${name}`);
|
||||||
|
}
|
||||||
|
if (!existsSync(sums)) {
|
||||||
|
try {
|
||||||
|
writeFileSync(sums, (await download(`${base}/SHASUMS256.txt`)).toString('utf8'));
|
||||||
|
} catch (error) {
|
||||||
|
warn(`could not fetch SHASUMS256.txt (${error.message}); the cached tarball is unverified`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const hash = sha256File(archive);
|
||||||
|
if (existsSync(sums)) {
|
||||||
|
const line = readFileSync(sums, 'utf8')
|
||||||
|
.split('\n')
|
||||||
|
.map((row) => row.trim().split(/\s+/))
|
||||||
|
.find((row) => row[1] === name);
|
||||||
|
if (!line) fail(`SHASUMS256.txt for ${version} has no ${name} entry`);
|
||||||
|
if (hash !== line[0]) {
|
||||||
|
rmSync(archive, { force: true });
|
||||||
|
fail(`${name} failed its SHA-256 check (${hash} != ${line[0]}); re-run to download again`);
|
||||||
|
}
|
||||||
|
log('node', `${version} linux-x64 verified (sha256 ${hash.slice(0, 12)}…)`);
|
||||||
|
} else {
|
||||||
|
warn(`using the Node tarball without a published checksum (sha256 ${hash})`);
|
||||||
|
}
|
||||||
|
return { archive, hash };
|
||||||
|
}
|
||||||
|
|
||||||
|
function installRuntime(bundle, archive) {
|
||||||
|
const runtime = path.join(bundle, 'runtime');
|
||||||
|
rmSync(runtime, { recursive: true, force: true });
|
||||||
|
log('runtime', 'extracting Node into runtime/ (bin/node, lib/node_modules)');
|
||||||
|
extractTar(archive, runtime);
|
||||||
|
const nodeBin = path.join(runtime, 'bin', 'node');
|
||||||
|
if (!existsSync(nodeBin)) fail('the Node tarball did not contain runtime/bin/node');
|
||||||
|
chmodSync(nodeBin, 0o755);
|
||||||
|
const check = spawnSync(nodeBin, ['--version'], { encoding: 'utf8' });
|
||||||
|
if (check.status !== 0) fail(`the bundled node binary does not run here: ${check.stderr || ''}`);
|
||||||
|
log('runtime', `bundled ${check.stdout.trim()} runs on this host`);
|
||||||
|
return nodeBin;
|
||||||
|
}
|
||||||
|
|
||||||
|
function installLauncher(bundle) {
|
||||||
|
const launcher = path.join(bundle, 'luminary');
|
||||||
|
cpSync(path.join(LAUNCHER_FILES, 'luminary'), launcher);
|
||||||
|
chmodSync(launcher, 0o755);
|
||||||
|
const installer = path.join(bundle, 'install.sh');
|
||||||
|
cpSync(path.join(LAUNCHER_FILES, 'install.sh'), installer);
|
||||||
|
chmodSync(installer, 0o755);
|
||||||
|
// Ships with the bundle so the first-run check is one command, and travels
|
||||||
|
// into /opt/luminary in the .deb.
|
||||||
|
const smoke = path.join(HERE, 'SMOKE-LINUX.sh');
|
||||||
|
if (existsSync(smoke)) {
|
||||||
|
cpSync(smoke, path.join(bundle, 'SMOKE-LINUX.sh'));
|
||||||
|
chmodSync(path.join(bundle, 'SMOKE-LINUX.sh'), 0o755);
|
||||||
|
}
|
||||||
|
log('launcher', 'luminary (app window + --stop/--status/--install), install.sh, SMOKE-LINUX.sh');
|
||||||
|
}
|
||||||
|
|
||||||
|
async function writeIcon(bundle) {
|
||||||
|
const logo = path.join(ROOT, 'logo.png');
|
||||||
|
const target = path.join(bundle, 'Luminary.png');
|
||||||
|
if (!existsSync(logo)) {
|
||||||
|
warn('logo.png is missing; the bundle has no menu icon');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const { default: sharp } = await import('sharp');
|
||||||
|
await sharp(logo).resize(256, 256, { fit: 'cover' }).png().toFile(target);
|
||||||
|
log('icon', `Luminary.png (${(statSync(target).size / 1024).toFixed(0)} KB)`);
|
||||||
|
} catch (error) {
|
||||||
|
cpSync(logo, target);
|
||||||
|
warn(`could not resize logo.png (${error.message}); copied it unchanged`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function writeVersion(bundle, pkg, nodeVersion, nodeHash, nodeSize) {
|
||||||
|
const commit = git(['rev-parse', '--short', 'HEAD']) ?? 'unknown';
|
||||||
|
const lines = [
|
||||||
|
`Luminary ${pkg.version}`,
|
||||||
|
`commit ${commit}`,
|
||||||
|
`built ${new Date().toISOString()}`,
|
||||||
|
`node ${nodeVersion} linux-x64 sha256 ${nodeHash} size ${nodeSize}`,
|
||||||
|
'launcher luminary (bash)',
|
||||||
|
];
|
||||||
|
writeFileSync(path.join(bundle, 'version.txt'), `${lines.join('\n')}\n`);
|
||||||
|
return { version: pkg.version, commit };
|
||||||
|
}
|
||||||
|
|
||||||
|
function writeBundleReadme(bundle, info) {
|
||||||
|
const body = `Luminary ${info.version} for Linux (x64) — portable bundle
|
||||||
|
==============================================
|
||||||
|
|
||||||
|
Start: ./luminary
|
||||||
|
Stop: ./luminary --stop
|
||||||
|
Menu: ./install.sh (adds Luminary to your applications menu)
|
||||||
|
Open tab: ./luminary --browser
|
||||||
|
Status: ./luminary --status
|
||||||
|
Data: ~/.local/share/luminary (originals, previews, SQLite catalog)
|
||||||
|
Logs: ~/.local/share/luminary/logs/server.out.log and server.err.log
|
||||||
|
Sign-in: none — single-user desktop mode, no account setup
|
||||||
|
|
||||||
|
Requirements
|
||||||
|
- Ubuntu 22.04 or 24.04, 64-bit (any glibc distribution of similar age works).
|
||||||
|
- A Chromium-based browser for the app window: Chrome, Chromium, Edge, Brave
|
||||||
|
or Vivaldi. Firefox is used as a normal window, and the default browser is
|
||||||
|
the last resort. WebGL2 is needed for the Develop module.
|
||||||
|
- Nothing to install: Node.js is included in runtime/, and sharp's Linux
|
||||||
|
binaries are bundled. No root, no apt, no deb package.
|
||||||
|
- About 250 MB free where the data folder lives.
|
||||||
|
|
||||||
|
Extract the tarball anywhere, then run ./luminary from the extracted folder.
|
||||||
|
Nothing is written into /usr or /opt, so moving or deleting the folder is safe;
|
||||||
|
the catalog lives in ~/.local/share/luminary and is not touched on removal.
|
||||||
|
|
||||||
|
./install.sh adds a menu entry (~/.local/share/applications/luminary.desktop)
|
||||||
|
using this folder's absolute path, so install after you have put the folder
|
||||||
|
where you want to keep it. ./luminary --uninstall removes the entry again.
|
||||||
|
|
||||||
|
Back up the catalog by copying ~/.local/share/luminary while Luminary is
|
||||||
|
stopped, including lumenroom.db, lumenroom.db-wal, lumenroom.db-shm and
|
||||||
|
secret.key.
|
||||||
|
|
||||||
|
Updating: stop Luminary, replace app/ and runtime/ from a newer bundle, start
|
||||||
|
again. The data folder is outside the bundle and is untouched.
|
||||||
|
|
||||||
|
Notes
|
||||||
|
- The server listens on 127.0.0.1 only. Set HOST=0.0.0.0 when starting it
|
||||||
|
directly with node if client proofing galleries must reach other devices.
|
||||||
|
- The app window is the browser's own app mode with a private profile, so it
|
||||||
|
has no tabs or address bar. Some Wayland desktops ignore the requested
|
||||||
|
window class; the window still opens.
|
||||||
|
- RAW decoding uses the bundled libraw WebAssembly, so no system codec
|
||||||
|
packages are needed.
|
||||||
|
- Photo libraries on NTFS/exFAT drives work, but SQLite is happiest on a
|
||||||
|
native Linux filesystem.
|
||||||
|
`;
|
||||||
|
writeFileSync(path.join(bundle, 'README-linux.txt'), body);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ deb ---- */
|
||||||
|
|
||||||
|
function walkBytes(dir) {
|
||||||
|
let total = 0;
|
||||||
|
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
||||||
|
const absolute = path.join(dir, entry.name);
|
||||||
|
if (entry.isDirectory()) total += walkBytes(absolute);
|
||||||
|
else total += lstatSync(absolute).size;
|
||||||
|
}
|
||||||
|
return total;
|
||||||
|
}
|
||||||
|
|
||||||
|
const DEB_MAINTAINER_SCRIPT = `#!/bin/sh
|
||||||
|
set -e
|
||||||
|
|
||||||
|
# Refresh the menu and icon caches so Luminary appears without a logout.
|
||||||
|
if command -v update-desktop-database >/dev/null 2>&1; then
|
||||||
|
update-desktop-database -q /usr/share/applications || true
|
||||||
|
fi
|
||||||
|
if command -v gtk-update-icon-cache >/dev/null 2>&1; then
|
||||||
|
gtk-update-icon-cache -q -t -f /usr/share/icons/hicolor || true
|
||||||
|
fi
|
||||||
|
|
||||||
|
exit 0
|
||||||
|
`;
|
||||||
|
|
||||||
|
function debControlFile(pkg, installedBytes) {
|
||||||
|
return [
|
||||||
|
'Package: luminary',
|
||||||
|
`Version: ${pkg.version}`,
|
||||||
|
'Architecture: amd64',
|
||||||
|
'Maintainer: Brian Hursey <bhursey@gmail.com>',
|
||||||
|
`Installed-Size: ${Math.ceil(installedBytes / 1024)}`,
|
||||||
|
'Depends: libc6, libstdc++6, libgomp1',
|
||||||
|
'Recommends: chromium | google-chrome-stable | microsoft-edge-stable | firefox',
|
||||||
|
'Section: graphics',
|
||||||
|
'Priority: optional',
|
||||||
|
'Homepage: https://git.maple-street.net/bhursey/luminary',
|
||||||
|
'Description: photo library and raw editor',
|
||||||
|
' Luminary catalogs photos, develops camera raw files and serves client',
|
||||||
|
' proofing galleries. This package bundles the Node runtime and the server,',
|
||||||
|
' so it installs with no other dependencies. Photos and the catalog live in',
|
||||||
|
' ~/.local/share/luminary and are kept when the package is removed.',
|
||||||
|
'',
|
||||||
|
].join('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
function debDesktopEntry() {
|
||||||
|
return [
|
||||||
|
'[Desktop Entry]',
|
||||||
|
'Type=Application',
|
||||||
|
'Version=1.0',
|
||||||
|
'Name=Luminary',
|
||||||
|
'GenericName=Photo library',
|
||||||
|
'Comment=Photo library and raw editor',
|
||||||
|
'Exec=/usr/bin/luminary',
|
||||||
|
'Path=/opt/luminary',
|
||||||
|
'Icon=luminary',
|
||||||
|
'Terminal=false',
|
||||||
|
'Categories=Graphics;Photography;',
|
||||||
|
'Keywords=photo;raw;catalog;editor;',
|
||||||
|
'StartupNotify=true',
|
||||||
|
'StartupWMClass=Luminary',
|
||||||
|
'',
|
||||||
|
].join('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
function debCopyright() {
|
||||||
|
return [
|
||||||
|
'Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/',
|
||||||
|
'Upstream-Name: Luminary',
|
||||||
|
'Source: https://git.maple-street.net/bhursey/luminary',
|
||||||
|
'',
|
||||||
|
'Files: *',
|
||||||
|
'Copyright: 2026 Brian Hursey',
|
||||||
|
'License: MIT',
|
||||||
|
' The full MIT licence text is in /opt/luminary/LICENSE.',
|
||||||
|
'',
|
||||||
|
].join('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Builds the opt-in Ubuntu package from the same staged bundle. Installed as
|
||||||
|
* /opt/luminary so the bundle layout (and therefore the launcher's bundle
|
||||||
|
* detection) is unchanged; the data folder stays in the user's home.
|
||||||
|
*/
|
||||||
|
function buildDeb(outDir, pkg, bundle) {
|
||||||
|
const probe = spawnSync('dpkg-deb', ['--version'], { encoding: 'utf8' });
|
||||||
|
if (probe.error || probe.status !== 0) {
|
||||||
|
warn('dpkg-deb is not installed; skipping the .deb (install the dpkg package)');
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const work = path.join(outDir, 'deb.next');
|
||||||
|
rmSync(work, { recursive: true, force: true });
|
||||||
|
const root = path.join(work, 'root');
|
||||||
|
|
||||||
|
log('deb', 'staging /opt/luminary, /usr/bin/luminary and the menu entry');
|
||||||
|
const appTarget = path.join(root, 'opt', 'luminary');
|
||||||
|
mkdirSync(path.dirname(appTarget), { recursive: true });
|
||||||
|
cpSync(bundle, appTarget, { recursive: true });
|
||||||
|
|
||||||
|
const binDir = path.join(root, 'usr', 'bin');
|
||||||
|
mkdirSync(binDir, { recursive: true });
|
||||||
|
// Relative link so the package works whatever the prefix.
|
||||||
|
symlinkSync('../opt/luminary/luminary', path.join(binDir, 'luminary'));
|
||||||
|
|
||||||
|
const appsDir = path.join(root, 'usr', 'share', 'applications');
|
||||||
|
mkdirSync(appsDir, { recursive: true });
|
||||||
|
writeFileSync(path.join(appsDir, 'luminary.desktop'), debDesktopEntry());
|
||||||
|
|
||||||
|
const icon = path.join(bundle, 'Luminary.png');
|
||||||
|
const iconDir = path.join(root, 'usr', 'share', 'icons', 'hicolor', '256x256', 'apps');
|
||||||
|
mkdirSync(iconDir, { recursive: true });
|
||||||
|
if (existsSync(icon)) cpSync(icon, path.join(iconDir, 'luminary.png'));
|
||||||
|
else warn('the bundle has no Luminary.png; the menu entry will use a generic icon');
|
||||||
|
|
||||||
|
const docDir = path.join(root, 'usr', 'share', 'doc', 'luminary');
|
||||||
|
mkdirSync(docDir, { recursive: true });
|
||||||
|
cpSync(path.join(bundle, 'README-linux.txt'), path.join(docDir, 'README-linux.txt'));
|
||||||
|
writeFileSync(path.join(docDir, 'copyright'), debCopyright());
|
||||||
|
|
||||||
|
const installedBytes = walkBytes(root);
|
||||||
|
const controlDir = path.join(root, 'DEBIAN');
|
||||||
|
mkdirSync(controlDir, { recursive: true });
|
||||||
|
writeFileSync(path.join(controlDir, 'control'), debControlFile(pkg, installedBytes));
|
||||||
|
for (const name of ['postinst', 'postrm']) {
|
||||||
|
const file = path.join(controlDir, name);
|
||||||
|
writeFileSync(file, DEB_MAINTAINER_SCRIPT);
|
||||||
|
chmodSync(file, 0o755);
|
||||||
|
}
|
||||||
|
|
||||||
|
const debPath = path.join(outDir, `Luminary-${pkg.version}-linux-amd64.deb`);
|
||||||
|
rmSync(debPath, { force: true });
|
||||||
|
const result = spawnSync(
|
||||||
|
'dpkg-deb',
|
||||||
|
['--root-owner-group', '-Zxz', '--build', root, debPath],
|
||||||
|
{ stdio: 'inherit' },
|
||||||
|
);
|
||||||
|
if (result.error || result.status !== 0) fail('dpkg-deb could not build the package');
|
||||||
|
|
||||||
|
const listed = spawnSync('dpkg-deb', ['--contents', debPath], { encoding: 'utf8' });
|
||||||
|
if (listed.status !== 0) fail('the .deb could not be read back');
|
||||||
|
for (const required of [
|
||||||
|
'opt/luminary/luminary',
|
||||||
|
'opt/luminary/runtime/bin/node',
|
||||||
|
'usr/bin/luminary',
|
||||||
|
'usr/share/applications/luminary.desktop',
|
||||||
|
]) {
|
||||||
|
if (!listed.stdout.includes(required)) fail(`the .deb is missing ${required}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
log('deb', `${path.basename(debPath)} (${(statSync(debPath).size / 1024 / 1024).toFixed(1)} MB)`);
|
||||||
|
rmSync(work, { recursive: true, force: true });
|
||||||
|
return debPath;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ tar ---- */
|
||||||
|
|
||||||
|
function createArchive(workRoot, tarPath) {
|
||||||
|
rmSync(tarPath, { force: true });
|
||||||
|
const deterministic = [
|
||||||
|
'--sort=name',
|
||||||
|
'--owner=0',
|
||||||
|
'--group=0',
|
||||||
|
'--numeric-owner',
|
||||||
|
'--mtime=@1577836800',
|
||||||
|
'-czf',
|
||||||
|
tarPath,
|
||||||
|
'-C',
|
||||||
|
workRoot,
|
||||||
|
'Luminary',
|
||||||
|
];
|
||||||
|
let result = spawnSync('tar', deterministic, { stdio: 'inherit' });
|
||||||
|
if (result.error || result.status !== 0) {
|
||||||
|
warn('this tar has no --sort/--owner support; writing a plain archive instead');
|
||||||
|
result = spawnSync('tar', ['-czf', tarPath, '-C', workRoot, 'Luminary'], { stdio: 'inherit' });
|
||||||
|
}
|
||||||
|
if (result.error || result.status !== 0) fail('tar could not create the archive');
|
||||||
|
const list = spawnSync('tar', ['-tzf', tarPath], { encoding: 'utf8' });
|
||||||
|
if (list.status !== 0) fail('the archive could not be read back');
|
||||||
|
const entries = list.stdout.split('\n').filter(Boolean);
|
||||||
|
for (const required of [
|
||||||
|
'Luminary/luminary',
|
||||||
|
'Luminary/runtime/bin/node',
|
||||||
|
'Luminary/app/server/index.mjs',
|
||||||
|
'Luminary/app/dist/index.html',
|
||||||
|
]) {
|
||||||
|
if (!entries.includes(required)) fail(`the archive is missing ${required}`);
|
||||||
|
}
|
||||||
|
return { files: entries.length, bytes: statSync(tarPath).size };
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ----------------------------------------------------------------- main ---- */
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
const options = parseArgs(process.argv.slice(2));
|
||||||
|
if (options.help) {
|
||||||
|
process.stdout.write(HELP);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
assertOutsideRepo(options.out);
|
||||||
|
const pkg = readPackage();
|
||||||
|
log('repo', `${pkg.name} ${pkg.version} at ${ROOT}`);
|
||||||
|
log('out', options.out);
|
||||||
|
checkRepoClean(options);
|
||||||
|
ensureUi(options);
|
||||||
|
|
||||||
|
// Build into a sibling and swap at the end, so a failed run never replaces
|
||||||
|
// the last complete bundle with a partial tree.
|
||||||
|
const stageRoot = path.join(options.out, 'stage');
|
||||||
|
const workRoot = path.join(options.out, 'stage.next');
|
||||||
|
const bundle = path.join(workRoot, 'Luminary');
|
||||||
|
rmSync(workRoot, { recursive: true, force: true });
|
||||||
|
mkdirSync(path.join(bundle, 'app'), { recursive: true });
|
||||||
|
|
||||||
|
log('stage', 'copying dist/ and server/ (unchanged layout the server expects)');
|
||||||
|
cpSync(path.join(ROOT, 'dist'), path.join(bundle, 'app', 'dist'), { recursive: true });
|
||||||
|
copyServer(bundle);
|
||||||
|
copyLegal(bundle);
|
||||||
|
installLinuxDeps(bundle);
|
||||||
|
|
||||||
|
const node = await ensureNode(options.out, options.node);
|
||||||
|
const nodeBin = installRuntime(bundle, node.archive);
|
||||||
|
// Remember the size now: the bundle is renamed into stage/ before the summary.
|
||||||
|
const nodeBinSize = statSync(nodeBin).size;
|
||||||
|
|
||||||
|
installLauncher(bundle);
|
||||||
|
await writeIcon(bundle);
|
||||||
|
|
||||||
|
const info = writeVersion(
|
||||||
|
bundle,
|
||||||
|
pkg,
|
||||||
|
options.node,
|
||||||
|
node.hash,
|
||||||
|
statSync(node.archive).size,
|
||||||
|
);
|
||||||
|
writeBundleReadme(bundle, info);
|
||||||
|
|
||||||
|
const tarPath = path.join(options.out, `Luminary-${pkg.version}-linux-x64.tar.gz`);
|
||||||
|
log('tar', path.basename(tarPath));
|
||||||
|
const archive = createArchive(workRoot, tarPath);
|
||||||
|
|
||||||
|
// The .deb is built from the same staged bundle, before it is moved into
|
||||||
|
// stage/, so both artifacts are guaranteed to come from one build.
|
||||||
|
const debPath = buildDeb(options.out, pkg, bundle);
|
||||||
|
|
||||||
|
rmSync(stageRoot, { recursive: true, force: true });
|
||||||
|
renameSync(workRoot, stageRoot);
|
||||||
|
|
||||||
|
// The isolation contract: nothing outside linux/ may have changed.
|
||||||
|
if (!options.allowDirty) checkRepoClean(options);
|
||||||
|
const stagedBundle = path.join(stageRoot, 'Luminary');
|
||||||
|
|
||||||
|
// Hand-off copy. Staging and the archives stay outside the checkout; this is
|
||||||
|
// the one write into the repository, into linux/releases.
|
||||||
|
const published = [];
|
||||||
|
if (options.publish) {
|
||||||
|
mkdirSync(RELEASES_DIR, { recursive: true });
|
||||||
|
const sums = [];
|
||||||
|
for (const artifact of [tarPath, ...(debPath ? [debPath] : [])]) {
|
||||||
|
const target = path.join(RELEASES_DIR, path.basename(artifact));
|
||||||
|
cpSync(artifact, target);
|
||||||
|
sums.push(`${sha256File(target)} ${path.basename(target)}`);
|
||||||
|
log('publish', path.relative(ROOT, target));
|
||||||
|
published.push(target);
|
||||||
|
}
|
||||||
|
writeFileSync(path.join(RELEASES_DIR, 'SHA256SUMS.txt'), `${sums.join('\n')}\n`);
|
||||||
|
}
|
||||||
|
|
||||||
|
process.stdout.write(
|
||||||
|
[
|
||||||
|
'',
|
||||||
|
'linux build PASSED',
|
||||||
|
` artifact ${tarPath}`,
|
||||||
|
` size ${(archive.bytes / 1024 / 1024).toFixed(1)} MB (${archive.files} entries)`,
|
||||||
|
` sha256 ${sha256File(tarPath)}`,
|
||||||
|
` node ${options.node} linux-x64 (${(nodeBinSize / 1024 / 1024).toFixed(0)} MB binary)`,
|
||||||
|
` launcher luminary (bash)`,
|
||||||
|
...(debPath
|
||||||
|
? [
|
||||||
|
` deb ${debPath}`,
|
||||||
|
` deb size ${(statSync(debPath).size / 1024 / 1024).toFixed(1)} MB`,
|
||||||
|
]
|
||||||
|
: []),
|
||||||
|
` staged ${stagedBundle}`,
|
||||||
|
...published.map((file) => ` publish ${path.relative(ROOT, file)}`),
|
||||||
|
'',
|
||||||
|
published.length
|
||||||
|
? 'Only linux/ was written: the archives in linux/releases are ready to transfer.'
|
||||||
|
: 'The repository was not modified; only linux/ and the output directory were touched.',
|
||||||
|
'',
|
||||||
|
].join('\n'),
|
||||||
|
);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
main().then(
|
||||||
|
(code) => {
|
||||||
|
process.exitCode = code;
|
||||||
|
},
|
||||||
|
(error) => {
|
||||||
|
fail(error instanceof Error ? error.message : String(error));
|
||||||
|
},
|
||||||
|
);
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Add this Luminary bundle to the Ubuntu applications menu.
|
||||||
|
#
|
||||||
|
# Creates ~/.local/share/applications/luminary.desktop pointing at this folder,
|
||||||
|
# so keep the folder where it is (or re-run this after moving it). Photos and the
|
||||||
|
# catalog stay in ~/.local/share/luminary and are never touched by the menu entry.
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||||
|
exec "$here/luminary" --install
|
||||||
@@ -0,0 +1,357 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Luminary desktop launcher for Linux.
|
||||||
|
#
|
||||||
|
# Starts the bundled server in single-user desktop mode on a free loopback port,
|
||||||
|
# waits for /api/health, then opens the UI in a chromeless app window (Chrome,
|
||||||
|
# Chromium, Edge, Brave or Vivaldi). Firefox, or the default browser, is the
|
||||||
|
# fallback.
|
||||||
|
#
|
||||||
|
# ./luminary start and open the window
|
||||||
|
# ./luminary --stop stop the running server
|
||||||
|
# ./luminary --status report pid, URL, data folder and health
|
||||||
|
# ./luminary --browser open a normal browser tab instead
|
||||||
|
# ./luminary --verify check that this is a complete bundle
|
||||||
|
# ./luminary --install add Luminary to the applications menu
|
||||||
|
# ./luminary --uninstall remove that menu entry
|
||||||
|
#
|
||||||
|
# Everything the app writes lives in ~/.local/share/luminary (or $LUMINARY_DATA),
|
||||||
|
# never inside this folder, so the bundle can be moved or deleted safely.
|
||||||
|
|
||||||
|
set -u
|
||||||
|
|
||||||
|
SELF="$(readlink -f "${BASH_SOURCE[0]}")"
|
||||||
|
BUNDLE="$(dirname "$SELF")"
|
||||||
|
APP="$BUNDLE/app"
|
||||||
|
DATA_DIR="${LUMINARY_DATA:-${XDG_DATA_HOME:-$HOME/.local/share}/luminary}"
|
||||||
|
LOG_DIR="$DATA_DIR/logs"
|
||||||
|
PID_FILE="$DATA_DIR/luminary.pid"
|
||||||
|
RUNTIME_FILE="$DATA_DIR/runtime.json"
|
||||||
|
FIRST_PORT=8787
|
||||||
|
LAST_PORT=8887
|
||||||
|
WINDOW_MODE="${LUMINARY_WINDOW:-window}"
|
||||||
|
|
||||||
|
say() { printf '%s\n' "$*"; }
|
||||||
|
problem() { printf 'Luminary: %s\n' "$*" >&2; }
|
||||||
|
|
||||||
|
usage() {
|
||||||
|
sed -n '2,18p' "$SELF" | sed 's/^# \{0,1\}//'
|
||||||
|
}
|
||||||
|
|
||||||
|
find_node() {
|
||||||
|
if [ -x "$BUNDLE/runtime/bin/node" ]; then
|
||||||
|
NODE="$BUNDLE/runtime/bin/node"
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
if command -v node >/dev/null 2>&1; then
|
||||||
|
NODE="$(command -v node)"
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
problem "No Node runtime found: runtime/bin/node is missing and there is no node on PATH."
|
||||||
|
problem "Download this bundle again, or install Node 24 (https://nodejs.org)."
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
node_is_recent() {
|
||||||
|
"$NODE" -e 'process.exit(Number(process.versions.node.split(".")[0]) >= 24 ? 0 : 1)' 2>/dev/null
|
||||||
|
}
|
||||||
|
|
||||||
|
port_free() {
|
||||||
|
! (exec 3<>"/dev/tcp/127.0.0.1/$1") 2>/dev/null
|
||||||
|
}
|
||||||
|
|
||||||
|
choose_port() {
|
||||||
|
local port="$FIRST_PORT"
|
||||||
|
while [ "$port" -le "$LAST_PORT" ]; do
|
||||||
|
if port_free "$port"; then
|
||||||
|
printf '%s' "$port"
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
port=$((port + 1))
|
||||||
|
done
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
running_pid() {
|
||||||
|
[ -f "$PID_FILE" ] || return 1
|
||||||
|
local pid
|
||||||
|
pid="$(cat "$PID_FILE" 2>/dev/null)"
|
||||||
|
[ -n "$pid" ] || return 1
|
||||||
|
kill -0 "$pid" 2>/dev/null || return 1
|
||||||
|
printf '%s' "$pid"
|
||||||
|
}
|
||||||
|
|
||||||
|
current_port() {
|
||||||
|
[ -f "$RUNTIME_FILE" ] || return 1
|
||||||
|
sed -n 's/.*"port": *\([0-9][0-9]*\).*/\1/p' "$RUNTIME_FILE" | head -n 1
|
||||||
|
}
|
||||||
|
|
||||||
|
wait_health() {
|
||||||
|
local url="http://127.0.0.1:$1/api/health" tries=0
|
||||||
|
while [ "$tries" -lt 150 ]; do
|
||||||
|
if "$NODE" -e "fetch('$url').then(r => process.exit(r.ok ? 0 : 1)).catch(() => process.exit(1))" >/dev/null 2>&1; then
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
tries=$((tries + 1))
|
||||||
|
sleep 0.2
|
||||||
|
done
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
verify_bundle() {
|
||||||
|
local missing=0
|
||||||
|
for rel in runtime/bin/node app/server/index.mjs app/dist/index.html luminary; do
|
||||||
|
if [ ! -e "$BUNDLE/$rel" ]; then
|
||||||
|
problem "missing: $rel"
|
||||||
|
missing=1
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
if [ -d "$APP/node_modules" ]; then
|
||||||
|
say "node_modules: present"
|
||||||
|
else
|
||||||
|
problem "missing: app/node_modules (production dependencies)"
|
||||||
|
missing=1
|
||||||
|
fi
|
||||||
|
if [ "$missing" -ne 0 ]; then
|
||||||
|
problem "This folder is not a complete Luminary bundle; extract the whole tarball."
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
say "Bundle: $BUNDLE"
|
||||||
|
say "Version: $(sed -n '1p' "$BUNDLE/version.txt" 2>/dev/null)"
|
||||||
|
if find_node; then
|
||||||
|
say "Node: $("$NODE" --version 2>/dev/null) ($NODE)"
|
||||||
|
fi
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
start() {
|
||||||
|
local pid port
|
||||||
|
pid="$(running_pid)" && {
|
||||||
|
port="$(current_port)"
|
||||||
|
if [ -n "${port:-}" ]; then
|
||||||
|
say "Luminary is already running at http://127.0.0.1:$port (pid $pid)."
|
||||||
|
open_window "http://127.0.0.1:$port"
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
say "Luminary is already running (pid $pid)."
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
verify_bundle >/dev/null || return 1
|
||||||
|
find_node || return 1
|
||||||
|
if ! node_is_recent; then
|
||||||
|
problem "Node $("$NODE" --version 2>/dev/null) is too old; Luminary needs Node 24 or newer."
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
mkdir -p "$DATA_DIR" "$LOG_DIR" || {
|
||||||
|
problem "could not create $DATA_DIR"
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
chmod 700 "$DATA_DIR" 2>/dev/null || true
|
||||||
|
|
||||||
|
port="$(choose_port)" || {
|
||||||
|
problem "no free loopback port between $FIRST_PORT and $LAST_PORT"
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
(
|
||||||
|
cd "$APP" || exit 1
|
||||||
|
LUMINARY_LOCAL=1 \
|
||||||
|
PORT="$port" \
|
||||||
|
HOST=127.0.0.1 \
|
||||||
|
NODE_ENV=production \
|
||||||
|
LUMINARY_DATA="$DATA_DIR" \
|
||||||
|
nohup "$NODE" server/index.mjs >>"$LOG_DIR/server.out.log" 2>>"$LOG_DIR/server.err.log" &
|
||||||
|
printf '%s\n' "$!" >"$PID_FILE"
|
||||||
|
)
|
||||||
|
|
||||||
|
pid="$(cat "$PID_FILE" 2>/dev/null)"
|
||||||
|
if ! wait_health "$port"; then
|
||||||
|
problem "the server did not answer on /api/health."
|
||||||
|
problem "See $LOG_DIR/server.err.log, or run: cd \"$APP\" && \"$NODE\" server/index.mjs"
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
printf '{"pid": %s, "port": %s, "url": "http://127.0.0.1:%s", "data": "%s"}\n' \
|
||||||
|
"$pid" "$port" "$port" "$DATA_DIR" >"$RUNTIME_FILE"
|
||||||
|
|
||||||
|
say "Luminary is running at http://127.0.0.1:$port (pid $pid)"
|
||||||
|
say "Data: $DATA_DIR"
|
||||||
|
if [ "$WINDOW_MODE" = "browser" ]; then
|
||||||
|
open_tab "http://127.0.0.1:$port"
|
||||||
|
elif [ "$WINDOW_MODE" = "none" ]; then
|
||||||
|
# Used by SMOKE-LINUX.sh: start the server but do not open anything.
|
||||||
|
:
|
||||||
|
else
|
||||||
|
open_window "http://127.0.0.1:$port" || open_tab "http://127.0.0.1:$port"
|
||||||
|
fi
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
stop() {
|
||||||
|
local pid
|
||||||
|
if ! pid="$(running_pid)"; then
|
||||||
|
rm -f "$PID_FILE" "$RUNTIME_FILE"
|
||||||
|
say "Luminary is not running."
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
kill "$pid" 2>/dev/null
|
||||||
|
local tries=0
|
||||||
|
while kill -0 "$pid" 2>/dev/null && [ "$tries" -lt 50 ]; do
|
||||||
|
tries=$((tries + 1))
|
||||||
|
sleep 0.1
|
||||||
|
done
|
||||||
|
if kill -0 "$pid" 2>/dev/null; then
|
||||||
|
kill -9 "$pid" 2>/dev/null
|
||||||
|
fi
|
||||||
|
rm -f "$PID_FILE" "$RUNTIME_FILE"
|
||||||
|
say "Stopped Luminary (pid $pid)."
|
||||||
|
}
|
||||||
|
|
||||||
|
status() {
|
||||||
|
local pid port
|
||||||
|
say "Bundle: $BUNDLE"
|
||||||
|
say "Data: $DATA_DIR"
|
||||||
|
if pid="$(running_pid)"; then
|
||||||
|
port="$(current_port)"
|
||||||
|
say "Status: running (pid $pid)"
|
||||||
|
if [ -n "${port:-}" ]; then
|
||||||
|
say "URL: http://127.0.0.1:$port"
|
||||||
|
find_node >/dev/null 2>&1 &&
|
||||||
|
"$NODE" -e "fetch('http://127.0.0.1:$port/api/health').then(r => process.exit(r.ok ? 0 : 1)).catch(() => process.exit(1))" >/dev/null 2>&1 &&
|
||||||
|
say "Health: ok" || say "Health: unreachable"
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
say "Status: stopped"
|
||||||
|
fi
|
||||||
|
say "Logs: $LOG_DIR"
|
||||||
|
}
|
||||||
|
|
||||||
|
browser_candidates() {
|
||||||
|
printf '%s\n' google-chrome google-chrome-stable chromium chromium-browser \
|
||||||
|
microsoft-edge microsoft-edge-stable brave-browser vivaldi-stable
|
||||||
|
}
|
||||||
|
|
||||||
|
open_window() {
|
||||||
|
local url="$1" name browser
|
||||||
|
while IFS= read -r name; do
|
||||||
|
if browser="$(command -v "$name" 2>/dev/null)"; then
|
||||||
|
say "Opening the app window with $name"
|
||||||
|
setsid "$browser" \
|
||||||
|
--app="$url" \
|
||||||
|
--user-data-dir="$DATA_DIR/window-profile" \
|
||||||
|
--class=Luminary \
|
||||||
|
--no-first-run \
|
||||||
|
--no-default-browser-check \
|
||||||
|
>/dev/null 2>&1 &
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
done <<EOF
|
||||||
|
$(browser_candidates)
|
||||||
|
EOF
|
||||||
|
if command -v firefox >/dev/null 2>&1; then
|
||||||
|
say "No Chromium-based browser found; opening Firefox."
|
||||||
|
setsid firefox --new-window "$url" >/dev/null 2>&1 &
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
open_tab() {
|
||||||
|
local url="$1"
|
||||||
|
if command -v xdg-open >/dev/null 2>&1; then
|
||||||
|
setsid xdg-open "$url" >/dev/null 2>&1 &
|
||||||
|
say "Opening $url in your browser."
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
say "Open $url in your browser."
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
desktop_dir() {
|
||||||
|
printf '%s' "${XDG_DATA_HOME:-$HOME/.local/share}/applications"
|
||||||
|
}
|
||||||
|
|
||||||
|
icon_dir() {
|
||||||
|
printf '%s' "${XDG_DATA_HOME:-$HOME/.local/share}/icons/hicolor/256x256/apps"
|
||||||
|
}
|
||||||
|
|
||||||
|
install_menu_entry() {
|
||||||
|
local apps icons entry
|
||||||
|
apps="$(desktop_dir)"
|
||||||
|
icons="$(icon_dir)"
|
||||||
|
mkdir -p "$apps" "$icons" || {
|
||||||
|
problem "could not create $apps"
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
if [ -f "$BUNDLE/Luminary.png" ]; then
|
||||||
|
cp "$BUNDLE/Luminary.png" "$icons/luminary.png"
|
||||||
|
fi
|
||||||
|
entry="$apps/luminary.desktop"
|
||||||
|
cat >"$entry" <<EOF
|
||||||
|
[Desktop Entry]
|
||||||
|
Type=Application
|
||||||
|
Version=1.0
|
||||||
|
Name=Luminary
|
||||||
|
GenericName=Photo library
|
||||||
|
Comment=Photo library and raw editor
|
||||||
|
Exec="$SELF"
|
||||||
|
Path=$BUNDLE
|
||||||
|
Icon=$icons/luminary.png
|
||||||
|
Terminal=false
|
||||||
|
Categories=Graphics;Photography;
|
||||||
|
Keywords=photo;raw;catalog;editor;
|
||||||
|
StartupNotify=true
|
||||||
|
StartupWMClass=Luminary
|
||||||
|
EOF
|
||||||
|
chmod +x "$entry"
|
||||||
|
if command -v update-desktop-database >/dev/null 2>&1; then
|
||||||
|
update-desktop-database "$apps" >/dev/null 2>&1 || true
|
||||||
|
fi
|
||||||
|
say "Added Luminary to your applications menu: $entry"
|
||||||
|
say "If it does not appear yet, log out and back in."
|
||||||
|
}
|
||||||
|
|
||||||
|
uninstall_menu_entry() {
|
||||||
|
local entry
|
||||||
|
entry="$(desktop_dir)/luminary.desktop"
|
||||||
|
rm -f "$entry"
|
||||||
|
rm -f "$(icon_dir)/luminary.png"
|
||||||
|
if command -v update-desktop-database >/dev/null 2>&1; then
|
||||||
|
update-desktop-database "$(desktop_dir)" >/dev/null 2>&1 || true
|
||||||
|
fi
|
||||||
|
say "Removed the menu entry. Your photos and catalog in $DATA_DIR were kept."
|
||||||
|
}
|
||||||
|
|
||||||
|
case "${1:-}" in
|
||||||
|
""|--start)
|
||||||
|
start
|
||||||
|
;;
|
||||||
|
--stop)
|
||||||
|
stop
|
||||||
|
;;
|
||||||
|
--status)
|
||||||
|
status
|
||||||
|
;;
|
||||||
|
--browser)
|
||||||
|
WINDOW_MODE=browser
|
||||||
|
start
|
||||||
|
;;
|
||||||
|
--verify)
|
||||||
|
verify_bundle
|
||||||
|
;;
|
||||||
|
--install)
|
||||||
|
install_menu_entry
|
||||||
|
;;
|
||||||
|
--uninstall)
|
||||||
|
uninstall_menu_entry
|
||||||
|
;;
|
||||||
|
--help|-h)
|
||||||
|
usage
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
problem "unknown option $1"
|
||||||
|
usage >&2
|
||||||
|
exit 2
|
||||||
|
;;
|
||||||
|
esac
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
# Transfer-only release archives: keep the checksums reviewable, not the tarballs.
|
||||||
|
*.tar.gz
|
||||||
|
*.deb
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
# Linux release hand-off
|
||||||
|
|
||||||
|
`node linux/build.mjs --skip-build --publish` drops the finished artifacts here:
|
||||||
|
|
||||||
|
```
|
||||||
|
Luminary-0.5.1-linux-x64.tar.gz portable bundle
|
||||||
|
Luminary-0.5.1-linux-amd64.deb Ubuntu package
|
||||||
|
SHA256SUMS.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
The archives are git-ignored; only `SHA256SUMS.txt` and this note are tracked,
|
||||||
|
so the checksums stay reviewable while the multi-hundred-megabyte archives do
|
||||||
|
not end up in the repository (or in the deploy rsync).
|
||||||
|
|
||||||
|
Verify a copy with:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sha256sum -c SHA256SUMS.txt
|
||||||
|
tar -tzf Luminary-0.5.1-linux-x64.tar.gz | head
|
||||||
|
dpkg-deb --info Luminary-0.5.1-linux-amd64.deb
|
||||||
|
```
|
||||||
|
|
||||||
|
On Ubuntu the easiest install is `sudo apt install ./Luminary-0.5.1-linux-amd64.deb`,
|
||||||
|
which adds Luminary to the applications menu. The portable route is to extract
|
||||||
|
the whole tarball and run `./luminary` from the extracted `Luminary` folder;
|
||||||
|
`./install.sh` adds that copy to the applications menu.
|
||||||
|
|
||||||
|
After publishing, the product site needs the new `.deb` copied to
|
||||||
|
`luminary-site/downloads/` with the size and SHA-256 in its download card.
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
7b2f91d603b49aa19734e681278a16f8024018c618b1c342d2607c75a2e6722f Luminary-0.5.1-linux-x64.tar.gz
|
||||||
|
5649939b748946409a99d6e8e99a4d5a5613f7602458b23d9af23ef9b7f65d04 Luminary-0.5.1-linux-amd64.deb
|
||||||
@@ -1,17 +1,17 @@
|
|||||||
{
|
{
|
||||||
"name": "luminary",
|
"name": "luminary",
|
||||||
"version": "1.0.0",
|
"version": "0.5.1",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "luminary",
|
"name": "luminary",
|
||||||
"version": "1.0.0",
|
"version": "0.5.1",
|
||||||
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@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"
|
||||||
@@ -1306,12 +1306,6 @@
|
|||||||
"@jridgewell/sourcemap-codec": "^1.4.14"
|
"@jridgewell/sourcemap-codec": "^1.4.14"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@neoanaloglabkk/lensfun-wasm": {
|
|
||||||
"version": "0.1.3",
|
|
||||||
"resolved": "https://registry.npmjs.org/@neoanaloglabkk/lensfun-wasm/-/lensfun-wasm-0.1.3.tgz",
|
|
||||||
"integrity": "sha512-+Me+P4kqr2CgJ7Tg+VatLSTfWxJkBt/xE9kG0qxD3KCcVY4MVgm/kkMwiVWTJt4EgzdIi3mFwUGO7HEuyziBpw==",
|
|
||||||
"license": "LGPL-3.0-or-later"
|
|
||||||
},
|
|
||||||
"node_modules/@rolldown/pluginutils": {
|
"node_modules/@rolldown/pluginutils": {
|
||||||
"version": "1.0.0-beta.27",
|
"version": "1.0.0-beta.27",
|
||||||
"resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-beta.27.tgz",
|
"resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-beta.27.tgz",
|
||||||
@@ -2330,12 +2324,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": {
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
"name": "luminary",
|
"name": "luminary",
|
||||||
"private": true,
|
"private": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"version": "1.0.0",
|
"version": "0.5.1",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
@@ -12,13 +12,16 @@
|
|||||||
"start": "node server/index.mjs",
|
"start": "node server/index.mjs",
|
||||||
"preview": "vite preview",
|
"preview": "vite preview",
|
||||||
"typecheck": "tsc --noEmit",
|
"typecheck": "tsc --noEmit",
|
||||||
"test": "vitest run"
|
"test": "vitest run",
|
||||||
|
"check:render": "node scripts/render-check.mjs",
|
||||||
|
"predeploy": "node scripts/predeploy.mjs",
|
||||||
|
"deploy": "node scripts/deploy.mjs",
|
||||||
|
"build:lens-db": "node scripts/build-lens-db.mjs"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@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"
|
||||||
|
|||||||
@@ -0,0 +1,21 @@
|
|||||||
|
# Lens database notice
|
||||||
|
|
||||||
|
`profiles.json` in this directory is a converted copy of the Lensfun camera and lens
|
||||||
|
database, produced by `scripts/build-lens-db.mjs`.
|
||||||
|
|
||||||
|
```text
|
||||||
|
Lens database: © Lensfun contributors, CC BY-SA 3.0 Unported
|
||||||
|
https://lensfun.github.io/ · https://creativecommons.org/licenses/by-sa/3.0/
|
||||||
|
Pinned source: https://github.com/lensfun/lensfun/tree/655a9c4e3e53c25bc04843c853e7e7a0121359e7/data
|
||||||
|
```
|
||||||
|
|
||||||
|
- Only the calibration measurements come from Lensfun. The correction maths, the
|
||||||
|
search/matching code and the file format are Luminary's own (MIT).
|
||||||
|
- The data remains under CC BY-SA 3.0. Keep this attribution with it, and if you edit
|
||||||
|
`profiles.json` or regenerate it with different calibration data, distribute the
|
||||||
|
result under CC BY-SA 3.0 or a compatible licence and indicate the changes.
|
||||||
|
- Do not describe the database as MIT, public domain or OSI-approved open source: it is
|
||||||
|
a Creative Commons content licence and grants neither patent nor trademark rights.
|
||||||
|
- The full licence text is not bundled here; add Lensfun's
|
||||||
|
`data/COPYING.CC_BY-SA_3.0` beside this file before redistributing the app or its
|
||||||
|
container image.
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
MIT License
|
|
||||||
|
|
||||||
Copyright (c) 2026 lex
|
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
||||||
of this software and associated documentation files (the "Software"), to deal
|
|
||||||
in the Software without restriction, including without limitation the rights
|
|
||||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
||||||
copies of the Software, and to permit persons to whom the Software is
|
|
||||||
furnished to do so, subject to the following conditions:
|
|
||||||
|
|
||||||
The above copyright notice and this permission notice shall be included in all
|
|
||||||
copies or substantial portions of the Software.
|
|
||||||
|
|
||||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
||||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
||||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
||||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
||||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
||||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
||||||
SOFTWARE.
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
# Notices
|
|
||||||
|
|
||||||
This project bundles and/or links the following third-party components:
|
|
||||||
|
|
||||||
1. Lensfun library source code (`third_party/lensfun/libs`) under LGPL-3.0-or-later.
|
|
||||||
2. Lensfun camera/lens database (`third_party/lensfun/data/db`) under CC BY-SA 3.0.
|
|
||||||
3. tinyxml2 (`third_party/tinyxml2`) under zlib license.
|
|
||||||
4. utf8proc (`third_party/utf8proc`) under MIT license.
|
|
||||||
|
|
||||||
Refer to `THIRD_PARTY_LICENSES.md` for license texts and links.
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
# Third-Party Licenses
|
|
||||||
|
|
||||||
## Lensfun
|
|
||||||
|
|
||||||
- Repository: https://github.com/lensfun/lensfun
|
|
||||||
- Library license: GNU LGPL v3.0 or later
|
|
||||||
- Database license: Creative Commons Attribution-ShareAlike 3.0
|
|
||||||
- Copyright: Lensfun contributors
|
|
||||||
|
|
||||||
## tinyxml2
|
|
||||||
|
|
||||||
- Repository: https://github.com/leethomason/tinyxml2
|
|
||||||
- License: zlib
|
|
||||||
- Copyright: Lee Thomason
|
|
||||||
|
|
||||||
## utf8proc
|
|
||||||
|
|
||||||
- Repository: https://github.com/JuliaStrings/utf8proc
|
|
||||||
- License: MIT
|
|
||||||
- Copyright: utf8proc contributors
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
# Upstream Tracking
|
|
||||||
|
|
||||||
## Source of truth
|
|
||||||
|
|
||||||
- Upstream repo: https://github.com/lensfun/lensfun.git
|
|
||||||
- Integration mode: git submodule (`third_party/lensfun`)
|
|
||||||
- Current pinned commit: `655a9c4e3e53c25bc04843c853e7e7a0121359e7`
|
|
||||||
- Commit date: `2026-02-28`
|
|
||||||
- Commit subject: `Add tca data for Meike SL 35mm F1.8 STM PRO`
|
|
||||||
|
|
||||||
## Update policy
|
|
||||||
|
|
||||||
- Pin exact commits.
|
|
||||||
- Upgrade manually via PR.
|
|
||||||
- Run full build/test after each bump.
|
|
||||||
|
|
||||||
## Update steps
|
|
||||||
|
|
||||||
1. `scripts/sync-upstream.sh origin/master`
|
|
||||||
2. Review upstream diff impact (API, DB changes, compile behavior)
|
|
||||||
3. Rebuild wasm assets
|
|
||||||
4. Run tests
|
|
||||||
5. Update this file with new commit metadata
|
|
||||||
|
After Width: | Height: | Size: 15 KiB |
@@ -0,0 +1,308 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
/**
|
||||||
|
* Builds the lens profile database the editor ships.
|
||||||
|
*
|
||||||
|
* The calibration measurements come from the Lensfun project's database
|
||||||
|
* (CC BY-SA 3.0, © Lensfun contributors); this script only converts the XML
|
||||||
|
* into the compact form `src/lib/lensDb.ts` reads, so the app no longer needs
|
||||||
|
* the Lensfun WebAssembly runtime. Data, not code: the maths lives in
|
||||||
|
* `src/lib/lensEngine.ts`.
|
||||||
|
*
|
||||||
|
* Usage:
|
||||||
|
* node scripts/build-lens-db.mjs --db <lensfun/data/db> [--out <file>]
|
||||||
|
*
|
||||||
|
* `--db` is a checkout of https://github.com/lensfun/lensfun at the pinned commit
|
||||||
|
* recorded in `public/lens-db/NOTICE.md`; only its `data/db/*.xml` files are read.
|
||||||
|
* The generated file is committed, so a normal build does not need the checkout.
|
||||||
|
*/
|
||||||
|
import { readFileSync, writeFileSync, readdirSync, mkdirSync, existsSync } from 'node:fs';
|
||||||
|
import { dirname, join, resolve } from 'node:path';
|
||||||
|
|
||||||
|
const DIST_MODELS = ['poly3', 'poly5', 'ptlens', 'linear', 'acm'];
|
||||||
|
const TCA_MODELS = ['poly3', 'linear', 'acm'];
|
||||||
|
|
||||||
|
const args = process.argv.slice(2);
|
||||||
|
const argValue = (name, fallback) => {
|
||||||
|
const at = args.indexOf(name);
|
||||||
|
return at >= 0 && args[at + 1] ? args[at + 1] : fallback;
|
||||||
|
};
|
||||||
|
const DB_DIR = argValue('--db', '');
|
||||||
|
const OUT = resolve(argValue('--out', 'public/lens-db/profiles.json'));
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ parsing */
|
||||||
|
|
||||||
|
/** Rounds to six decimals and drops trailing zeros, to keep the file small. */
|
||||||
|
function round(n) {
|
||||||
|
return Number.isFinite(n) ? Math.round(n * 1e6) / 1e6 : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
function num(value) {
|
||||||
|
if (value == null || value === '') return 0;
|
||||||
|
return round(Number(value));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** "3:2" or "1.5" as a number, 0 when absent so the engine can use the image. */
|
||||||
|
function aspectRatio(value) {
|
||||||
|
if (!value) return 0;
|
||||||
|
const parts = value.split(':').map(Number);
|
||||||
|
if (parts.length === 2 && parts[0] > 0 && parts[1] > 0) return round(parts[0] / parts[1]);
|
||||||
|
return num(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
const TAG = /<(\/?)([a-zA-Z0-9_:.-]+)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
|
||||||
|
const ATTR = /([a-zA-Z0-9_:.-]+)\s*=\s*("([^"]*)"|'([^']*)')/g;
|
||||||
|
|
||||||
|
function attributes(source) {
|
||||||
|
const out = {};
|
||||||
|
for (const match of source.matchAll(ATTR)) {
|
||||||
|
out[match[1]] = decode(match[3] ?? match[4] ?? '');
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Minimal XML reader for the Lensfun schema: elements, attributes and text.
|
||||||
|
* Comments and the doctype are skipped; nothing here needs namespaces,
|
||||||
|
* entities beyond the five predefined ones, or CDATA.
|
||||||
|
*/
|
||||||
|
function parseXml(source) {
|
||||||
|
// Comments carry prose (and markup examples) that must not reach the tag
|
||||||
|
// scanner, or they unbalance the element stack.
|
||||||
|
const xml = source.replace(/<!--[\s\S]*?-->/g, '');
|
||||||
|
const root = { name: '#root', attrs: {}, children: [], text: '' };
|
||||||
|
const stack = [root];
|
||||||
|
let cursor = 0;
|
||||||
|
TAG.lastIndex = 0;
|
||||||
|
for (let match = TAG.exec(xml); match; match = TAG.exec(xml)) {
|
||||||
|
const [whole, closing, name, rawAttrs, selfClosing] = match;
|
||||||
|
const between = xml.slice(cursor, match.index);
|
||||||
|
cursor = match.index + whole.length;
|
||||||
|
if (between.trim()) stack[stack.length - 1].text += decode(between.trim());
|
||||||
|
if (closing) {
|
||||||
|
if (stack.length > 1) stack.pop();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const node = { name, attrs: attributes(rawAttrs), children: [], text: '' };
|
||||||
|
stack[stack.length - 1].children.push(node);
|
||||||
|
if (!selfClosing) stack.push(node);
|
||||||
|
}
|
||||||
|
return root;
|
||||||
|
}
|
||||||
|
|
||||||
|
function decode(text) {
|
||||||
|
return text
|
||||||
|
.replace(/</g, '<')
|
||||||
|
.replace(/>/g, '>')
|
||||||
|
.replace(/"/g, '"')
|
||||||
|
.replace(/'/g, "'")
|
||||||
|
.replace(/&/g, '&');
|
||||||
|
}
|
||||||
|
|
||||||
|
const kids = (node, name) => node.children.filter((child) => child.name === name);
|
||||||
|
const kid = (node, name) => kids(node, name)[0];
|
||||||
|
const text = (node) => (node ? node.text.trim() : '');
|
||||||
|
|
||||||
|
/** Picks the untagged value, falling back to English. */
|
||||||
|
function localized(node, name) {
|
||||||
|
const all = kids(node, name);
|
||||||
|
if (!all.length) return '';
|
||||||
|
const plain = all.find((entry) => !entry.attrs.lang);
|
||||||
|
if (plain) return text(plain);
|
||||||
|
const english = all.find((entry) => entry.attrs.lang === 'en' || entry.attrs.lang === 'en_US');
|
||||||
|
return text(english ?? all[0]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --------------------------------------------------------------- conversion */
|
||||||
|
|
||||||
|
function convertFile(xml, db) {
|
||||||
|
const doc = parseXml(xml);
|
||||||
|
const root = kid(doc, 'lensdatabase');
|
||||||
|
if (!root) return;
|
||||||
|
|
||||||
|
for (const mount of kids(root, 'mount')) {
|
||||||
|
const name = text(kid(mount, 'name'));
|
||||||
|
if (name) db.mounts.add(name);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const camera of kids(root, 'camera')) {
|
||||||
|
const maker = localized(camera, 'maker');
|
||||||
|
const model = localized(camera, 'model');
|
||||||
|
if (!maker || !model) continue;
|
||||||
|
db.cameras.push({ maker, model, mount: text(kid(camera, 'mount')), crop: num(text(kid(camera, 'cropfactor'))) || 1 });
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const lens of kids(root, 'lens')) {
|
||||||
|
const maker = localized(lens, 'maker');
|
||||||
|
const model = localized(lens, 'model');
|
||||||
|
if (!maker || !model) continue;
|
||||||
|
const record = {
|
||||||
|
maker,
|
||||||
|
model,
|
||||||
|
crop: num(text(kid(lens, 'cropfactor'))) || 1,
|
||||||
|
mounts: kids(lens, 'mount').map((entry) => text(entry)).filter(Boolean),
|
||||||
|
aspect: aspectRatio(text(kid(lens, 'aspect-ratio'))),
|
||||||
|
centerX: num(text(kid(lens, 'center-x'))),
|
||||||
|
centerY: num(text(kid(lens, 'center-y'))),
|
||||||
|
d: [],
|
||||||
|
t: [],
|
||||||
|
v: [],
|
||||||
|
};
|
||||||
|
const calibration = kid(lens, 'calibration');
|
||||||
|
if (calibration) {
|
||||||
|
for (const entry of kids(calibration, 'distortion')) {
|
||||||
|
const terms = distortionTerms(entry);
|
||||||
|
if (!terms) continue;
|
||||||
|
// A few calibrations were measured at a focal length other than the
|
||||||
|
// nominal one; Lensfun scales by the ratio, so keep it (0 = same focal).
|
||||||
|
record.d.push([
|
||||||
|
num(entry.attrs.focal),
|
||||||
|
terms.model,
|
||||||
|
...terms.terms,
|
||||||
|
num(entry.attrs['real-focal']),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
for (const entry of kids(calibration, 'tca')) {
|
||||||
|
const terms = tcaTerms(entry);
|
||||||
|
if (!terms) continue;
|
||||||
|
record.t.push([num(entry.attrs.focal), terms.model, ...terms.terms]);
|
||||||
|
}
|
||||||
|
for (const entry of kids(calibration, 'vignetting')) {
|
||||||
|
const model = entry.attrs.model;
|
||||||
|
if (model !== 'pa' && model !== 'acm') continue;
|
||||||
|
record.v.push([
|
||||||
|
num(entry.attrs.focal),
|
||||||
|
num(entry.attrs.aperture),
|
||||||
|
num(entry.attrs.distance),
|
||||||
|
num(entry.attrs.k1),
|
||||||
|
num(entry.attrs.k2),
|
||||||
|
num(entry.attrs.k3),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
db.stats.lenses += 1;
|
||||||
|
if (record.d.length || record.t.length || record.v.length) db.lenses.push(record);
|
||||||
|
else db.stats.withoutCalibration += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Lensfun stores poly3 as `k1`, polygon (poly5) as `k1`/`k2`, and PanoTools as
|
||||||
|
* `a`/`b`/`c`. Everything is normalised to the `a·r³ + b·r² + c·r + 1` form the
|
||||||
|
* engine evaluates, with the PanoTools `d = 1 - a - b - c` factor divided out
|
||||||
|
* the way Lensfun does so the focal length is preserved.
|
||||||
|
*/
|
||||||
|
function distortionTerms(entry) {
|
||||||
|
const attrs = entry.attrs;
|
||||||
|
switch (attrs.model) {
|
||||||
|
case 'poly3': {
|
||||||
|
const k1 = num(attrs.k1);
|
||||||
|
const d = 1 - k1;
|
||||||
|
return { model: DIST_MODELS.indexOf('poly3'), terms: [0, round(k1 / d ** 3), 0] };
|
||||||
|
}
|
||||||
|
case 'poly5':
|
||||||
|
return { model: DIST_MODELS.indexOf('poly5'), terms: [0, num(attrs.k1), num(attrs.k2)] };
|
||||||
|
case 'ptlens': {
|
||||||
|
const a = num(attrs.a);
|
||||||
|
const b = num(attrs.b);
|
||||||
|
const c = num(attrs.c);
|
||||||
|
const d = 1 - a - b - c;
|
||||||
|
return {
|
||||||
|
model: DIST_MODELS.indexOf('ptlens'),
|
||||||
|
terms: [round(a / d ** 4), round(b / d ** 3), round(c / d ** 2)],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
case 'linear':
|
||||||
|
return { model: DIST_MODELS.indexOf('linear'), terms: [0, 0, 0] };
|
||||||
|
default:
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function tcaTerms(entry) {
|
||||||
|
const attrs = entry.attrs;
|
||||||
|
if (attrs.model === 'poly3') {
|
||||||
|
// Stored per channel as [br, cr, vr] / [bb, cb, vb], matching the term
|
||||||
|
// order the engine evaluates: r_d = r * (v + c*r + b*r^2).
|
||||||
|
return {
|
||||||
|
model: TCA_MODELS.indexOf('poly3'),
|
||||||
|
terms: [num(attrs.br), num(attrs.cr), num(attrs.vr || 1), num(attrs.bb), num(attrs.cb), num(attrs.vb || 1)],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (attrs.model === 'linear') {
|
||||||
|
return { model: TCA_MODELS.indexOf('linear'), terms: [num(attrs.kr || 1), num(attrs.kb || 1)] };
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --------------------------------------------------------------------- main */
|
||||||
|
|
||||||
|
function loadXmlFiles() {
|
||||||
|
if (!DB_DIR) {
|
||||||
|
throw new Error(
|
||||||
|
'pass --db <path to lensfun/data/db>; the profiles are committed, so this is only ' +
|
||||||
|
'needed when refreshing them',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const dir = resolve(DB_DIR);
|
||||||
|
if (!existsSync(dir)) throw new Error(`database directory not found: ${dir}`);
|
||||||
|
return readdirSync(dir)
|
||||||
|
.filter((name) => name.endsWith('.xml'))
|
||||||
|
.sort()
|
||||||
|
.map((name) => readFileSync(join(dir, name), 'utf8'));
|
||||||
|
}
|
||||||
|
|
||||||
|
const db = { mounts: new Set(), cameras: [], lenses: [], stats: { lenses: 0, withoutCalibration: 0 } };
|
||||||
|
for (const xml of loadXmlFiles()) {
|
||||||
|
try {
|
||||||
|
convertFile(xml, db);
|
||||||
|
} catch (err) {
|
||||||
|
console.warn(`skipped a database file: ${err.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const slug = (value) =>
|
||||||
|
value
|
||||||
|
.toLowerCase()
|
||||||
|
.replace(/[^a-z0-9]+/g, '-')
|
||||||
|
.replace(/^-|-$/g, '');
|
||||||
|
|
||||||
|
const seen = new Map();
|
||||||
|
const lenses = db.lenses.map((lens) => {
|
||||||
|
const base = `${slug(lens.maker)}-${slug(lens.model)}`;
|
||||||
|
const count = (seen.get(base) ?? 0) + 1;
|
||||||
|
seen.set(base, count);
|
||||||
|
return {
|
||||||
|
id: count === 1 ? base : `${base}-${count}`,
|
||||||
|
maker: lens.maker,
|
||||||
|
model: lens.model,
|
||||||
|
crop: lens.crop,
|
||||||
|
mounts: lens.mounts,
|
||||||
|
aspect: lens.aspect,
|
||||||
|
centerX: lens.centerX,
|
||||||
|
centerY: lens.centerY,
|
||||||
|
d: lens.d.sort((a, b) => a[0] - b[0]),
|
||||||
|
t: lens.t.sort((a, b) => a[0] - b[0]),
|
||||||
|
v: lens.v.sort((a, b) => a[0] - b[0] || a[1] - b[1] || a[2] - b[2]),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
const payload = {
|
||||||
|
source: {
|
||||||
|
project: 'lensfun',
|
||||||
|
commit: '655a9c4e3e53c25bc04843c853e7e7a0121359e7',
|
||||||
|
licence: 'CC BY-SA 3.0 Unported',
|
||||||
|
note: 'Calibration data only; the correction maths is Luminary\u2019s own.',
|
||||||
|
},
|
||||||
|
models: { distortion: DIST_MODELS, tca: TCA_MODELS },
|
||||||
|
mounts: [...db.mounts].sort(),
|
||||||
|
cameras: db.cameras.sort((a, b) => a.maker.localeCompare(b.maker) || a.model.localeCompare(b.model)),
|
||||||
|
lenses,
|
||||||
|
};
|
||||||
|
|
||||||
|
mkdirSync(dirname(OUT), { recursive: true });
|
||||||
|
writeFileSync(OUT, `${JSON.stringify(payload)}\n`);
|
||||||
|
console.log(
|
||||||
|
`wrote ${OUT}: ${lenses.length} lenses with calibration (${db.stats.withoutCalibration} of ` +
|
||||||
|
`${db.stats.lenses} entries have none), ${payload.cameras.length} cameras, ` +
|
||||||
|
`${lenses.reduce((n, lens) => n + lens.v.length, 0)} vignetting samples`,
|
||||||
|
);
|
||||||
@@ -0,0 +1,166 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
/**
|
||||||
|
* Deploy Luminary: run the predeploy gate, then copy the source to the server,
|
||||||
|
* rebuild it there and restart the service.
|
||||||
|
*
|
||||||
|
* The gate runs first and a failure exits before anything touches the server,
|
||||||
|
* so a type error, a failing test or a shader regression caught by the render
|
||||||
|
* check cannot reach production. The local bundle is compared with the one the
|
||||||
|
* server just built, so a deploy that silently ships stale assets is visible.
|
||||||
|
*
|
||||||
|
* Exits via process.exitCode rather than process.exit(): stdout/stderr are
|
||||||
|
* async when piped, and exiting early truncates the very lines that explain
|
||||||
|
* why a deploy stopped.
|
||||||
|
*
|
||||||
|
* Environment:
|
||||||
|
* LUMINARY_DEPLOY_HOST ssh target, e.g. bhursey@photos.example.org (required)
|
||||||
|
* LUMINARY_DEPLOY_PATH remote checkout of this repo (default /srv/luminary)
|
||||||
|
* LUMINARY_DEPLOY_SERVICE systemd unit to restart (default luminary)
|
||||||
|
* LUMINARY_DEPLOY_SSH_PASS optional ssh password, passed to sshpass via env
|
||||||
|
* LUMINARY_DEPLOY_SUDO_PASS optional sudo password for the remote build/restart
|
||||||
|
*/
|
||||||
|
import { execFileSync } from 'node:child_process';
|
||||||
|
import { existsSync, readdirSync } from 'node:fs';
|
||||||
|
import path from 'node:path';
|
||||||
|
|
||||||
|
const env = process.env;
|
||||||
|
const HOST = env.LUMINARY_DEPLOY_HOST;
|
||||||
|
const REMOTE_PATH = env.LUMINARY_DEPLOY_PATH || '/srv/luminary';
|
||||||
|
const SERVICE = env.LUMINARY_DEPLOY_SERVICE || 'luminary';
|
||||||
|
const SSH_PASS = env.LUMINARY_DEPLOY_SSH_PASS || '';
|
||||||
|
const SUDO_PASS = env.LUMINARY_DEPLOY_SUDO_PASS || '';
|
||||||
|
|
||||||
|
/** Local-only state that must never be copied over the server's copy. */
|
||||||
|
const EXCLUDES = [
|
||||||
|
'node_modules',
|
||||||
|
'dist',
|
||||||
|
'data',
|
||||||
|
'.git',
|
||||||
|
'.freebuff',
|
||||||
|
'.check',
|
||||||
|
'.smoke',
|
||||||
|
'logo.png',
|
||||||
|
'*.log',
|
||||||
|
];
|
||||||
|
|
||||||
|
function run(command, args, extraEnv) {
|
||||||
|
execFileSync(command, args, {
|
||||||
|
stdio: 'inherit',
|
||||||
|
env: extraEnv ? { ...process.env, ...extraEnv } : process.env,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function sshArgs(script) {
|
||||||
|
return ['-o', 'StrictHostKeyChecking=accept-new', HOST, script];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Runs a remote script with stdout echoed, returning what it printed. */
|
||||||
|
function sshCapture(script, input) {
|
||||||
|
const piped = input !== undefined;
|
||||||
|
const output = execFileSync(
|
||||||
|
SSH_PASS ? 'sshpass' : 'ssh',
|
||||||
|
SSH_PASS ? ['-e', 'ssh', ...sshArgs(script)] : sshArgs(script),
|
||||||
|
{
|
||||||
|
stdio: [piped ? 'pipe' : 'inherit', 'pipe', 'inherit'],
|
||||||
|
input,
|
||||||
|
encoding: 'utf8',
|
||||||
|
env: SSH_PASS ? { ...process.env, SSHPASS: SSH_PASS } : process.env,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
process.stdout.write(output);
|
||||||
|
return output;
|
||||||
|
}
|
||||||
|
|
||||||
|
function localBundles() {
|
||||||
|
const dir = path.join(process.cwd(), 'dist', 'assets');
|
||||||
|
if (!existsSync(dir)) return [];
|
||||||
|
return readdirSync(dir)
|
||||||
|
.filter((file) => /^index-.*\.(js|css)$/.test(file))
|
||||||
|
.sort();
|
||||||
|
}
|
||||||
|
|
||||||
|
function main() {
|
||||||
|
if (!HOST) {
|
||||||
|
console.error('deploy: set LUMINARY_DEPLOY_HOST to the ssh target, e.g. user@server.');
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1. Gate. Nothing below this line may run if the gate fails.
|
||||||
|
// npm runs a script called "predeploy" before "deploy", so under `npm run
|
||||||
|
// deploy` the gate has already passed before this process starts; running it
|
||||||
|
// again would typecheck and render-check the same source twice. Invoked
|
||||||
|
// directly, this script has to run the gate itself.
|
||||||
|
if (env.npm_lifecycle_event === 'deploy') {
|
||||||
|
console.log('deploy: predeploy gate passed (npm predeploy hook)');
|
||||||
|
} else {
|
||||||
|
console.log('deploy: predeploy gate');
|
||||||
|
try {
|
||||||
|
run(process.execPath, [path.join('scripts', 'predeploy.mjs')]);
|
||||||
|
} catch {
|
||||||
|
console.error('deploy: aborted - predeploy failed, nothing was sent to the server.');
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Copy the source, keeping server-side data and build output.
|
||||||
|
console.log(`\ndeploy: rsync to ${HOST}:${REMOTE_PATH}`);
|
||||||
|
const rsyncArgs = ['-az'];
|
||||||
|
for (const item of EXCLUDES) rsyncArgs.push(`--exclude=${item}`);
|
||||||
|
const remoteShell = SSH_PASS
|
||||||
|
? `sshpass -e ssh -o StrictHostKeyChecking=accept-new`
|
||||||
|
: `ssh -o StrictHostKeyChecking=accept-new`;
|
||||||
|
rsyncArgs.push('-e', remoteShell, './', `${HOST}:${REMOTE_PATH}/`);
|
||||||
|
try {
|
||||||
|
run('rsync', rsyncArgs, SSH_PASS ? { SSHPASS: SSH_PASS } : undefined);
|
||||||
|
} catch {
|
||||||
|
console.error('deploy: aborted - rsync failed.');
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Rebuild and restart there, then report what is actually being served.
|
||||||
|
const sudo = SUDO_PASS ? `sudo -S -p '' ` : '';
|
||||||
|
const sudoLines = SUDO_PASS ? `${SUDO_PASS}\n${SUDO_PASS}\n` : undefined;
|
||||||
|
const script = [
|
||||||
|
`cd ${REMOTE_PATH} || exit 3`,
|
||||||
|
`${sudo}npm run build`,
|
||||||
|
'build=$?',
|
||||||
|
'[ "$build" -eq 0 ] || { echo "deploy: remote build failed ($build)"; exit "$build"; }',
|
||||||
|
`${sudo}systemctl restart ${SERVICE}`,
|
||||||
|
'sleep 2',
|
||||||
|
`systemctl is-active ${SERVICE}`,
|
||||||
|
'sha256sum dist/assets/*.js dist/assets/*.css',
|
||||||
|
].join('\n');
|
||||||
|
|
||||||
|
console.log(`\ndeploy: build and restart ${SERVICE} on ${HOST}`);
|
||||||
|
let output;
|
||||||
|
try {
|
||||||
|
output = sshCapture(script, sudoLines);
|
||||||
|
} catch {
|
||||||
|
console.error('deploy: aborted - the remote build or restart failed.');
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. The server must be serving the bundle the gate just reviewed.
|
||||||
|
const remoteHashes = new Map();
|
||||||
|
for (const line of output.split('\n')) {
|
||||||
|
const match = /^([0-9a-f]{64})\s+dist\/assets\/(index-[^/\s]+)$/.exec(line.trim());
|
||||||
|
if (match) remoteHashes.set(match[2], match[1]);
|
||||||
|
}
|
||||||
|
const missing = localBundles().filter((file) => !remoteHashes.has(file));
|
||||||
|
if (missing.length) {
|
||||||
|
console.error(
|
||||||
|
`\ndeploy: FAILED - the server is not serving ${missing.join(', ')}; check the remote build.`,
|
||||||
|
);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
const served = [...remoteHashes.entries()];
|
||||||
|
console.log(
|
||||||
|
`\ndeploy PASSED: ${SERVICE} is active on ${HOST} serving ${served
|
||||||
|
.map(([file, hash]) => `${file} (${hash.slice(0, 12)})`)
|
||||||
|
.join(', ')}.`,
|
||||||
|
);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
process.exitCode = main();
|
||||||
@@ -0,0 +1,672 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
/**
|
||||||
|
* Render film-look sample frames and build the film gallery page.
|
||||||
|
*
|
||||||
|
* Every frame is produced by the app's own WebGL renderer with the preset's real
|
||||||
|
* edits, so the gallery shows what Luminary actually does rather than a mock-up.
|
||||||
|
* Black and white looks are documented with the contrast filter they carry, and
|
||||||
|
* one stock is rendered through every colour filter the editor offers.
|
||||||
|
*
|
||||||
|
* node scripts/film-samples.mjs --photo sample.jpg
|
||||||
|
* node scripts/film-samples.mjs --photo sample.jpg --out /tmp/film --per-category 2
|
||||||
|
*
|
||||||
|
* Output stays outside the checkout (default ~/.cache/luminary-film-gallery):
|
||||||
|
*
|
||||||
|
* <out>/original.jpg the untouched frame
|
||||||
|
* <out>/<preset-id>.jpg one frame per sampled stock
|
||||||
|
* <out>/<preset-id>--<filter>.jpg the black and white filter demo
|
||||||
|
* <out>/film.html the gallery page
|
||||||
|
* <out>/film-looks.json the catalogue data
|
||||||
|
*
|
||||||
|
* Copy the frames to the site's assets/film/ and film.html to the site root.
|
||||||
|
* Needs Chrome/Chromium with WebGL2 (SwiftShader is used when there is no GPU).
|
||||||
|
*/
|
||||||
|
import { spawn } from 'node:child_process';
|
||||||
|
import { existsSync } from 'node:fs';
|
||||||
|
import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';
|
||||||
|
import os from 'node:os';
|
||||||
|
import path from 'node:path';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
import sharp from 'sharp';
|
||||||
|
import { createServer } from 'vite';
|
||||||
|
import { FILM_PRESETS } from '../src/lib/presets.ts';
|
||||||
|
|
||||||
|
// Filled from Vite's ssrLoadModule below: edits.ts imports './curves' without an
|
||||||
|
// extension, which Node's own resolver cannot follow from a plain import here.
|
||||||
|
let BW_FILTERS = [];
|
||||||
|
|
||||||
|
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||||
|
const DIR = path.join(ROOT, '.film-samples');
|
||||||
|
const PAGE = path.join(DIR, 'index.html');
|
||||||
|
const PORT = 5201;
|
||||||
|
const RENDER_WIDTH = 1000;
|
||||||
|
const RENDER_HEIGHT = 667;
|
||||||
|
const JPEG_QUALITY = 84;
|
||||||
|
|
||||||
|
/** The stock used to show what each B&W contrast filter does. */
|
||||||
|
const BW_DEMO_STOCK = 'film-tri-x-400';
|
||||||
|
|
||||||
|
const FILTER_HINTS = {
|
||||||
|
none: 'No filter: the stock as it renders by default',
|
||||||
|
yellow: 'Mild: slightly darker sky, natural skin',
|
||||||
|
orange: 'Stronger: deeper sky, warmer skin separation',
|
||||||
|
red: 'Dramatic: near-black sky, bright skin and foliage highlights',
|
||||||
|
green: 'Lifts foliage, darkens lips and skin blemishes',
|
||||||
|
blue: 'Lightens haze and shadow detail, darkens skin',
|
||||||
|
};
|
||||||
|
|
||||||
|
const CATEGORY_ORDER = [
|
||||||
|
'Colour Negative',
|
||||||
|
'Colour Slide',
|
||||||
|
'Black & White',
|
||||||
|
'Cinema',
|
||||||
|
'Instant',
|
||||||
|
'Redscale',
|
||||||
|
'Experimental',
|
||||||
|
];
|
||||||
|
|
||||||
|
const CATEGORY_HINTS = {
|
||||||
|
'Colour Negative':
|
||||||
|
'C-41 print films: warm skin, open shadows and the colour people mean by "film".',
|
||||||
|
'Colour Slide':
|
||||||
|
'E-6 and K-14 reversal films: dense blacks, saturated colour and very little latitude.',
|
||||||
|
'Black & White':
|
||||||
|
'Panchromatic stocks and chromogenic B&W, each with its own grain, contrast and colour filter.',
|
||||||
|
Cinema: 'Motion-picture negatives: flat midtones and soft shoulders, built to grade.',
|
||||||
|
Instant: 'Integral and peel-apart instant film: lifted blacks, soft colour, gentle contrast.',
|
||||||
|
Redscale: 'Film exposed through its base: amber highlights, red midtones, deep shadows.',
|
||||||
|
Experimental:
|
||||||
|
'Cross-process, faded print, infrared and other deliberate departures from a normal negative.',
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Three representative stocks per category: the ones people ask for by name. */
|
||||||
|
const SAMPLE_PICKS = {
|
||||||
|
'Colour Negative': ['film-portra-400', 'film-gold-200', 'film-ektar-100'],
|
||||||
|
'Colour Slide': ['film-velvia-50', 'film-provia-100f', 'film-kodachrome-64'],
|
||||||
|
'Black & White': ['film-tri-x-400', 'film-tmax-100', 'film-hp5-plus-400'],
|
||||||
|
Cinema: ['film-cinestill-800t', 'film-vision3-250d', 'film-cinestill-50d'],
|
||||||
|
Instant: ['film-polaroid-600', 'film-instax-mini', 'film-fp-100c'],
|
||||||
|
Redscale: ['film-redscale-xr', 'film-redscale-deep', 'film-redscale-gold-200'],
|
||||||
|
Experimental: ['film-lomochrome-purple', 'film-xpro-cross-process', 'film-aerochrome'],
|
||||||
|
};
|
||||||
|
|
||||||
|
const HELP = `Luminary film gallery generator
|
||||||
|
|
||||||
|
Usage: node scripts/film-samples.mjs --photo <file> [options]
|
||||||
|
|
||||||
|
--photo <file> source frame (JPEG/PNG) to render every look onto
|
||||||
|
--out <dir> output directory (default: <cache>/luminary-film-gallery)
|
||||||
|
--per-category <n> sampled stocks per category (default: 3, max: all picks)
|
||||||
|
--quality <1-100> JPEG quality for the frames (default: ${JPEG_QUALITY})
|
||||||
|
--help print this text
|
||||||
|
|
||||||
|
Frames come from the app's own renderer in headless Chrome, so WebGL2 must work
|
||||||
|
there (SwiftShader is fine). ${BW_DEMO_STOCK} is also rendered through every B&W
|
||||||
|
colour filter. The repository is not modified; the temporary render page is
|
||||||
|
deleted at the end.
|
||||||
|
`;
|
||||||
|
|
||||||
|
const CHROME_CANDIDATES = [
|
||||||
|
process.env.CHROME_PATH,
|
||||||
|
'google-chrome',
|
||||||
|
'google-chrome-stable',
|
||||||
|
'chromium',
|
||||||
|
'chromium-browser',
|
||||||
|
].filter(Boolean);
|
||||||
|
|
||||||
|
function fail(message) {
|
||||||
|
process.stderr.write(`film-samples: FAILED: ${message}\n`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
function log(step, message) {
|
||||||
|
process.stdout.write(`film-samples: ${step.padEnd(9)} ${message}\n`);
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseArgs(argv) {
|
||||||
|
const options = {
|
||||||
|
photo: null,
|
||||||
|
out: path.join(process.env.XDG_CACHE_HOME || path.join(os.homedir(), '.cache'), 'luminary-film-gallery'),
|
||||||
|
perCategory: 3,
|
||||||
|
quality: JPEG_QUALITY,
|
||||||
|
help: false,
|
||||||
|
};
|
||||||
|
const value = (index, flag) => {
|
||||||
|
const next = argv[index + 1];
|
||||||
|
if (!next || next.startsWith('--')) fail(`${flag} needs a value`);
|
||||||
|
return next;
|
||||||
|
};
|
||||||
|
for (let i = 0; i < argv.length; i++) {
|
||||||
|
const arg = argv[i];
|
||||||
|
if (arg === '--photo') {
|
||||||
|
options.photo = path.resolve(value(i, arg));
|
||||||
|
i += 1;
|
||||||
|
} else if (arg === '--out') {
|
||||||
|
options.out = path.resolve(value(i, arg));
|
||||||
|
i += 1;
|
||||||
|
} else if (arg === '--per-category') {
|
||||||
|
options.perCategory = Number(value(i, arg));
|
||||||
|
i += 1;
|
||||||
|
} else if (arg === '--quality') {
|
||||||
|
options.quality = Number(value(i, arg));
|
||||||
|
i += 1;
|
||||||
|
} else if (arg === '--help' || arg === '-h') {
|
||||||
|
options.help = true;
|
||||||
|
} else {
|
||||||
|
fail(`unknown option ${arg} (see --help)`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!Number.isInteger(options.perCategory) || options.perCategory < 1) {
|
||||||
|
fail('--per-category must be a positive integer');
|
||||||
|
}
|
||||||
|
if (!Number.isInteger(options.quality) || options.quality < 1 || options.quality > 100) {
|
||||||
|
fail('--quality must be 1-100');
|
||||||
|
}
|
||||||
|
if (!options.help && !options.photo) fail('--photo is required (see --help)');
|
||||||
|
if (options.photo && !existsSync(options.photo)) fail(`photo not found: ${options.photo}`);
|
||||||
|
return options;
|
||||||
|
}
|
||||||
|
|
||||||
|
function sleep(ms) {
|
||||||
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||||
|
}
|
||||||
|
|
||||||
|
function spawnSyncOk(bin) {
|
||||||
|
const probe = spawn(bin, ['--version'], { stdio: 'ignore' });
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
probe.on('error', () => resolve(false));
|
||||||
|
probe.on('exit', (code) => resolve(code === 0));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function findChrome() {
|
||||||
|
for (const candidate of CHROME_CANDIDATES) {
|
||||||
|
if (candidate.includes(path.sep)) {
|
||||||
|
if (existsSync(candidate)) return candidate;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (await spawnSyncOk(candidate)) return candidate;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const PAGE_HTML = `<!doctype html>
|
||||||
|
<meta charset="utf-8" />
|
||||||
|
<pre id="out">boot</pre>
|
||||||
|
<script type="module">
|
||||||
|
import { Renderer } from '/src/gl/renderer.ts';
|
||||||
|
import { FILM_PRESETS } from '/src/lib/presets.ts';
|
||||||
|
import { defaultEdits, normalizeEdits } from '/src/lib/edits.ts';
|
||||||
|
|
||||||
|
const pre = document.getElementById('out');
|
||||||
|
try {
|
||||||
|
const canvas = document.createElement('canvas');
|
||||||
|
const renderer = new Renderer(canvas);
|
||||||
|
const blob = await (await fetch('/.film-samples/photo.jpg')).blob();
|
||||||
|
const bitmap = await createImageBitmap(blob, { imageOrientation: 'from-image' });
|
||||||
|
renderer.setImage(bitmap, null);
|
||||||
|
const size = { width: ${RENDER_WIDTH}, height: ${RENDER_HEIGHT} };
|
||||||
|
|
||||||
|
// filter is only used by the B&W strip: it overrides the stock's own filter.
|
||||||
|
window.renderLook = async (id, filter) => {
|
||||||
|
const preset = FILM_PRESETS.find((entry) => entry.id === id);
|
||||||
|
const edits = preset
|
||||||
|
? normalizeEdits(
|
||||||
|
filter
|
||||||
|
? { ...preset.edits, bw: true, bwFilter: filter, bwFilterAmount: 100 }
|
||||||
|
: preset.edits,
|
||||||
|
)
|
||||||
|
: defaultEdits();
|
||||||
|
renderer.render(edits, size);
|
||||||
|
return canvas.toDataURL('image/jpeg', ${JPEG_QUALITY} / 100);
|
||||||
|
};
|
||||||
|
window.ready = true;
|
||||||
|
pre.textContent = 'READY';
|
||||||
|
} catch (error) {
|
||||||
|
pre.textContent = 'ERROR ' + (error && error.message ? error.message : String(error));
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
`;
|
||||||
|
|
||||||
|
async function drive(chromeBin, url, jobs, outDir, quality) {
|
||||||
|
const port = 9333;
|
||||||
|
const child = spawn(
|
||||||
|
chromeBin,
|
||||||
|
[
|
||||||
|
'--headless=new',
|
||||||
|
'--no-sandbox',
|
||||||
|
'--disable-gpu-sandbox',
|
||||||
|
'--use-gl=angle',
|
||||||
|
'--use-angle=swiftshader',
|
||||||
|
'--enable-unsafe-swiftshader',
|
||||||
|
`--remote-debugging-port=${port}`,
|
||||||
|
`--user-data-dir=${path.join(DIR, 'profile')}`,
|
||||||
|
'about:blank',
|
||||||
|
],
|
||||||
|
{ stdio: 'ignore' },
|
||||||
|
);
|
||||||
|
|
||||||
|
try {
|
||||||
|
let target = null;
|
||||||
|
for (let i = 0; i < 120 && !target; i++) {
|
||||||
|
try {
|
||||||
|
const res = await fetch(`http://127.0.0.1:${port}/json/list`);
|
||||||
|
target = (await res.json()).find((t) => t.type === 'page') ?? null;
|
||||||
|
} catch {
|
||||||
|
/* devtools not up yet */
|
||||||
|
}
|
||||||
|
if (!target) await sleep(250);
|
||||||
|
}
|
||||||
|
if (!target) throw new Error('Chrome DevTools endpoint never came up');
|
||||||
|
|
||||||
|
const ws = new WebSocket(target.webSocketDebuggerUrl);
|
||||||
|
await new Promise((resolve, reject) => {
|
||||||
|
ws.onopen = resolve;
|
||||||
|
ws.onerror = () => reject(new Error('DevTools websocket failed'));
|
||||||
|
});
|
||||||
|
let nextId = 1;
|
||||||
|
const pending = new Map();
|
||||||
|
ws.onmessage = (event) => {
|
||||||
|
const message = JSON.parse(event.data);
|
||||||
|
if (message.id && pending.has(message.id)) {
|
||||||
|
pending.get(message.id)(message);
|
||||||
|
pending.delete(message.id);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const send = (method, params = {}) => {
|
||||||
|
const id = nextId++;
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
pending.set(id, resolve);
|
||||||
|
ws.send(JSON.stringify({ id, method, params }));
|
||||||
|
});
|
||||||
|
};
|
||||||
|
const evaluate = async (expression, awaitPromise = false) => {
|
||||||
|
const response = await send('Runtime.evaluate', {
|
||||||
|
expression,
|
||||||
|
awaitPromise,
|
||||||
|
returnByValue: true,
|
||||||
|
});
|
||||||
|
if (response.result?.exceptionDetails) {
|
||||||
|
throw new Error(
|
||||||
|
response.result.exceptionDetails.exception?.description ??
|
||||||
|
response.result.exceptionDetails.text,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return response.result?.result?.value;
|
||||||
|
};
|
||||||
|
|
||||||
|
await send('Page.enable');
|
||||||
|
await send('Runtime.enable');
|
||||||
|
await send('Page.navigate', { url });
|
||||||
|
|
||||||
|
const deadline = Date.now() + 120000;
|
||||||
|
let status = '';
|
||||||
|
while (Date.now() < deadline) {
|
||||||
|
status = (await evaluate("document.getElementById('out')?.textContent ?? ''")) ?? '';
|
||||||
|
if (status.startsWith('READY') || status.startsWith('ERROR')) break;
|
||||||
|
await sleep(400);
|
||||||
|
}
|
||||||
|
if (status.startsWith('ERROR')) throw new Error(status.slice(6));
|
||||||
|
if (!status.startsWith('READY')) throw new Error('the render page never became ready');
|
||||||
|
|
||||||
|
const written = [];
|
||||||
|
for (const job of jobs) {
|
||||||
|
const dataUrl = await evaluate(
|
||||||
|
`window.renderLook(${JSON.stringify(job.id)}, ${JSON.stringify(job.filter ?? null)})`,
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
if (typeof dataUrl !== 'string' || !dataUrl.startsWith('data:image/jpeg;base64,')) {
|
||||||
|
throw new Error(`renderer returned no JPEG for ${job.file}`);
|
||||||
|
}
|
||||||
|
const buffer = Buffer.from(dataUrl.slice('data:image/jpeg;base64,'.length), 'base64');
|
||||||
|
const file = path.join(outDir, job.file);
|
||||||
|
// Re-encode so the frames carry consistent metadata and no EXIF bloat.
|
||||||
|
await sharp(buffer).jpeg({ quality, mozjpeg: true }).toFile(file);
|
||||||
|
log('render', `${job.file} (${(buffer.length / 1024).toFixed(0)} KB)`);
|
||||||
|
written.push(job.file);
|
||||||
|
}
|
||||||
|
ws.close();
|
||||||
|
return written;
|
||||||
|
} finally {
|
||||||
|
child.kill('SIGKILL');
|
||||||
|
await sleep(400);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ page ---- */
|
||||||
|
|
||||||
|
function escapeHtml(value) {
|
||||||
|
return String(value)
|
||||||
|
.replace(/&/g, '&')
|
||||||
|
.replace(/</g, '<')
|
||||||
|
.replace(/>/g, '>')
|
||||||
|
.replace(/"/g, '"');
|
||||||
|
}
|
||||||
|
|
||||||
|
function slug(category) {
|
||||||
|
return category
|
||||||
|
.toLowerCase()
|
||||||
|
.replace(/&/g, 'and')
|
||||||
|
.replace(/[^a-z0-9]+/g, '-')
|
||||||
|
.replace(/(^-|-$)/g, '');
|
||||||
|
}
|
||||||
|
|
||||||
|
function filterLabel(id) {
|
||||||
|
return BW_FILTERS.find((filter) => filter.id === id)?.label ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildFilterDemo(catalogue) {
|
||||||
|
const group = catalogue.find((entry) => entry.category === 'Black & White');
|
||||||
|
if (!group) return '';
|
||||||
|
const withFilter = group.looks.filter((look) => look.filter && look.filter !== 'none').length;
|
||||||
|
const figures = BW_FILTERS.map(
|
||||||
|
(filter) => `<figure>
|
||||||
|
<img src="assets/film/${BW_DEMO_STOCK}--${filter.id}.jpg" width="${RENDER_WIDTH}" height="${RENDER_HEIGHT}" loading="lazy" alt="${escapeHtml(
|
||||||
|
filter.label,
|
||||||
|
)} filter on ${escapeHtml(group.looks.find((look) => look.id === BW_DEMO_STOCK)?.name ?? 'a black and white film')}">
|
||||||
|
<figcaption>${escapeHtml(filter.label)}</figcaption>
|
||||||
|
<p>${escapeHtml(FILTER_HINTS[filter.id] ?? '')}</p>
|
||||||
|
</figure>`,
|
||||||
|
).join('\n ');
|
||||||
|
|
||||||
|
return ` <div class="film-filter-demo">
|
||||||
|
<h3>Colour filters, the way they were used on the lens</h3>
|
||||||
|
<p class="film-filter-lede">
|
||||||
|
Before digital, contrast in black and white came from screwing a coloured filter onto
|
||||||
|
the lens: it held back its own colour, so a red filter turned a blue sky nearly black
|
||||||
|
while leaving skin bright, and a green one lifted foliage. Each monochrome look here
|
||||||
|
records the filter it was built with, and ${withFilter} of the ${group.looks.length}
|
||||||
|
name one. The same Tri-X 400 frame through every filter:
|
||||||
|
</p>
|
||||||
|
<div class="film-filters">
|
||||||
|
${figures}
|
||||||
|
</div>
|
||||||
|
<p class="fineprint">Filter strength is adjustable in the editor, so a look can be dialled back from the full strength shown here.</p>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildPage(catalogue, framesByCategory) {
|
||||||
|
const total = catalogue.reduce((sum, group) => sum + group.looks.length, 0);
|
||||||
|
const chips = catalogue
|
||||||
|
.map(
|
||||||
|
(group) =>
|
||||||
|
`<a href="#${slug(group.category)}">${escapeHtml(group.category)} <span>${group.looks.length}</span></a>`,
|
||||||
|
)
|
||||||
|
.join('\n ');
|
||||||
|
|
||||||
|
const sections = catalogue
|
||||||
|
.map((group) => {
|
||||||
|
const frames = framesByCategory[group.category] ?? [];
|
||||||
|
const figures = frames
|
||||||
|
.map(
|
||||||
|
(frame) => `<figure class="film-set">
|
||||||
|
<img src="assets/film/${frame.id}.jpg" width="${RENDER_WIDTH}" height="${RENDER_HEIGHT}" loading="lazy" alt="${escapeHtml(frame.name)} applied to the sample photograph">
|
||||||
|
<figcaption>${escapeHtml(frame.name)}${frame.iso ? ` · ISO ${frame.iso}` : ''}${
|
||||||
|
frame.process ? ` · ${escapeHtml(frame.process)}` : ''
|
||||||
|
}</figcaption>
|
||||||
|
</figure>`,
|
||||||
|
)
|
||||||
|
.join('\n ');
|
||||||
|
|
||||||
|
const looks = group.looks
|
||||||
|
.map(
|
||||||
|
(look) => `<li>
|
||||||
|
<span class="film-name">${escapeHtml(look.name)}</span>
|
||||||
|
<span class="film-meta">${[
|
||||||
|
look.iso ? `ISO ${look.iso}` : '',
|
||||||
|
look.process ?? '',
|
||||||
|
look.filter && look.filter !== 'none' ? `${filterLabel(look.filter)} filter` : '',
|
||||||
|
]
|
||||||
|
.filter(Boolean)
|
||||||
|
.join(' · ')}</span>
|
||||||
|
${look.note ? `<span class="film-note">${escapeHtml(look.note)}</span>` : ''}
|
||||||
|
</li>`,
|
||||||
|
)
|
||||||
|
.join('\n ');
|
||||||
|
|
||||||
|
return ` <section class="section${group.index % 2 === 1 ? ' section-alt' : ''}" id="${slug(group.category)}">
|
||||||
|
<div class="wrap">
|
||||||
|
<div class="section-head">
|
||||||
|
<p class="kicker">${escapeHtml(group.category)} · ${group.looks.length} looks</p>
|
||||||
|
<h2>${escapeHtml(group.category)}</h2>
|
||||||
|
<p class="section-lede">${escapeHtml(CATEGORY_HINTS[group.category] ?? '')}</p>
|
||||||
|
</div>
|
||||||
|
${group.category === 'Black & White' ? buildFilterDemo(catalogue) : ''} <div class="film-sets">
|
||||||
|
${figures}
|
||||||
|
</div>
|
||||||
|
<ul class="film-looks">
|
||||||
|
${looks}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
</section>`;
|
||||||
|
})
|
||||||
|
.join('\n\n');
|
||||||
|
|
||||||
|
return `<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>Luminary film looks: ${total} documented film emulations</title>
|
||||||
|
<meta name="description" content="The full Luminary film pack: ${total} film looks by category, each with the stock, ISO, process and a note on the look, rendered on one frame by Luminary's own editor. Black and white looks also record their contrast filter.">
|
||||||
|
<meta name="theme-color" content="#0c0e11">
|
||||||
|
<meta property="og:title" content="Luminary film looks: ${total} documented emulations">
|
||||||
|
<meta property="og:description" content="Colour negative, slide, black and white, cinema, instant, redscale and experimental looks, with frames rendered by the editor itself and the B&W contrast filters shown side by side.">
|
||||||
|
<meta property="og:type" content="website">
|
||||||
|
<meta property="og:image" content="assets/film/film-portra-400.jpg">
|
||||||
|
<link rel="icon" href="assets/favicon.png" type="image/png">
|
||||||
|
<link rel="apple-touch-icon" href="assets/icon-256.png">
|
||||||
|
<link rel="stylesheet" href="styles.css?v=20261128g">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<a class="skip" href="#main">Skip to content</a>
|
||||||
|
|
||||||
|
<header class="site-header">
|
||||||
|
<div class="wrap header-inner">
|
||||||
|
<a class="brand" href="index.html" aria-label="Luminary home">
|
||||||
|
<span class="brand-mark"><img src="assets/icon-256.png" alt="" width="36" height="36"></span>
|
||||||
|
<span class="brand-name">Luminary</span>
|
||||||
|
</a>
|
||||||
|
<nav class="nav" aria-label="Main">
|
||||||
|
<a href="index.html#develop">Raw editing</a>
|
||||||
|
<a href="film.html">Film looks</a>
|
||||||
|
<a href="index.html#library">Organise</a>
|
||||||
|
<a href="index.html#proofing">Galleries</a>
|
||||||
|
<a href="index.html#downloads">Download</a>
|
||||||
|
</nav>
|
||||||
|
<div class="header-actions">
|
||||||
|
<details class="mobile-nav">
|
||||||
|
<summary>Menu</summary>
|
||||||
|
<nav class="mobile-menu" aria-label="Sections">
|
||||||
|
<a href="index.html#develop">Raw editing</a>
|
||||||
|
<a href="film.html">Film looks</a>
|
||||||
|
<a href="index.html#library">Organise</a>
|
||||||
|
<a href="index.html#proofing">Galleries</a>
|
||||||
|
<a href="index.html#downloads">Download</a>
|
||||||
|
<a href="index.html#install">Install</a>
|
||||||
|
</nav>
|
||||||
|
</details>
|
||||||
|
<a class="btn btn-primary btn-small" href="index.html#downloads">Download</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<main id="main">
|
||||||
|
<section class="hero film-hero" id="top">
|
||||||
|
<div class="wrap">
|
||||||
|
<p class="eyebrow"><span class="dot"></span> Film pack · ${total} looks</p>
|
||||||
|
<h1>${total} film looks.<br><em>One frame, one engine.</em></h1>
|
||||||
|
<p class="lede">
|
||||||
|
Every frame below was rendered by Luminary's own editor with the look applied to the
|
||||||
|
same photograph — no screenshots from another app, no pasted LUTs. Each entry lists
|
||||||
|
the stock it emulates, its ISO and process, and a note on what it does.
|
||||||
|
</p>
|
||||||
|
<div class="film-cats" aria-label="Categories">
|
||||||
|
${chips}
|
||||||
|
</div>
|
||||||
|
<p class="fineprint">Sample frame: a digital photograph, unedited, rendered at ${RENDER_WIDTH}×${RENDER_HEIGHT}. Grain and colour come from the look itself.</p>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="section" id="sample">
|
||||||
|
<div class="wrap">
|
||||||
|
<figure class="film-original">
|
||||||
|
<img src="assets/film/original.jpg" width="${RENDER_WIDTH}" height="${RENDER_HEIGHT}" alt="The sample photograph with no film look applied">
|
||||||
|
<figcaption>The starting frame: no look, no crop, no colour work.</figcaption>
|
||||||
|
</figure>
|
||||||
|
<p class="fineprint">
|
||||||
|
The black and white section also shows the colour-filter technique: the same stock
|
||||||
|
rendered through yellow, orange, red, green and blue filters, the way contrast was
|
||||||
|
shaped on film before digital.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
${sections}
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<footer class="site-footer">
|
||||||
|
<div class="wrap footer-inner">
|
||||||
|
<div class="footer-brand">
|
||||||
|
<span class="brand-mark small"><img src="assets/icon-256.png" alt="" width="28" height="28"></span>
|
||||||
|
<div>
|
||||||
|
<p class="footer-name">Luminary</p>
|
||||||
|
<p class="footer-note">A photo library and raw editor for people who'd rather own their photos. MIT licensed. © 2026 Brian Hursey.</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<nav class="footer-links" aria-label="Footer">
|
||||||
|
<a href="index.html">Product page</a>
|
||||||
|
<a href="index.html#downloads">Download</a>
|
||||||
|
<a href="index.html#changelog">Changelog</a>
|
||||||
|
<a href="https://git.maple-street.net/bhursey/luminary" target="_blank" rel="noopener">Source</a>
|
||||||
|
<a href="mailto:bhursey@gmail.com?subject=Luminary%20film%20looks">Feedback</a>
|
||||||
|
</nav>
|
||||||
|
</div>
|
||||||
|
</footer>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ main ---- */
|
||||||
|
|
||||||
|
function filterDemoJobs() {
|
||||||
|
return BW_FILTERS.map((filter) => ({
|
||||||
|
id: BW_DEMO_STOCK,
|
||||||
|
filter: filter.id,
|
||||||
|
file: `${BW_DEMO_STOCK}--${filter.id}.jpg`,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
const options = parseArgs(process.argv.slice(2));
|
||||||
|
if (options.help) {
|
||||||
|
process.stdout.write(HELP);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
const chromeBin = await findChrome();
|
||||||
|
if (!chromeBin) {
|
||||||
|
fail('no Chrome/Chromium found; set CHROME_PATH or install one (WebGL2 is required)');
|
||||||
|
}
|
||||||
|
|
||||||
|
const categories = CATEGORY_ORDER.filter((category) =>
|
||||||
|
FILM_PRESETS.some((preset) => preset.category === category),
|
||||||
|
);
|
||||||
|
const catalogue = categories.map((category, index) => ({
|
||||||
|
category,
|
||||||
|
index,
|
||||||
|
looks: FILM_PRESETS.filter((preset) => preset.category === category).map((preset) => ({
|
||||||
|
id: preset.id,
|
||||||
|
name: preset.name,
|
||||||
|
iso: preset.film?.speed ?? null,
|
||||||
|
process: preset.film?.process ?? null,
|
||||||
|
filter: preset.edits.bw ? preset.edits.bwFilter ?? 'none' : null,
|
||||||
|
note: preset.description ?? null,
|
||||||
|
})),
|
||||||
|
}));
|
||||||
|
|
||||||
|
const framesByCategory = {};
|
||||||
|
const jobs = [{ id: 'original', file: 'original.jpg' }];
|
||||||
|
for (const group of catalogue) {
|
||||||
|
const picks = (SAMPLE_PICKS[group.category] ?? [])
|
||||||
|
.filter((id) => group.looks.some((look) => look.id === id))
|
||||||
|
.slice(0, options.perCategory);
|
||||||
|
framesByCategory[group.category] = picks.map((id) => {
|
||||||
|
const look = group.looks.find((entry) => entry.id === id);
|
||||||
|
return { id, name: look.name, iso: look.iso, process: look.process };
|
||||||
|
});
|
||||||
|
for (const id of picks) jobs.push({ id, file: `${id}.jpg` });
|
||||||
|
}
|
||||||
|
|
||||||
|
await mkdir(options.out, { recursive: true });
|
||||||
|
await rm(DIR, { recursive: true, force: true });
|
||||||
|
await mkdir(DIR, { recursive: true });
|
||||||
|
|
||||||
|
// A 3:2 frame keeps every look comparable; the page states the source size.
|
||||||
|
await sharp(options.photo)
|
||||||
|
.rotate()
|
||||||
|
.resize(RENDER_WIDTH, RENDER_HEIGHT, { fit: 'cover', position: 'centre' })
|
||||||
|
.jpeg({ quality: 95, chromaSubsampling: '4:4:4' })
|
||||||
|
.toFile(path.join(DIR, 'photo.jpg'));
|
||||||
|
|
||||||
|
const server = await createServer({
|
||||||
|
root: ROOT,
|
||||||
|
logLevel: 'error',
|
||||||
|
server: { host: '127.0.0.1', port: PORT, strictPort: false },
|
||||||
|
});
|
||||||
|
await server.listen();
|
||||||
|
const base = (server.resolvedUrls?.local?.[0] ?? `http://127.0.0.1:${PORT}/`).replace(/\/$/, '');
|
||||||
|
// The editor's own filter list, so the page cannot drift from the app.
|
||||||
|
BW_FILTERS = (await server.ssrLoadModule('/src/lib/edits.ts')).BW_FILTERS;
|
||||||
|
jobs.push(...filterDemoJobs());
|
||||||
|
await writeFile(PAGE, PAGE_HTML);
|
||||||
|
|
||||||
|
log('photo', `${path.relative(process.cwd(), options.photo)} → ${RENDER_WIDTH}×${RENDER_HEIGHT}`);
|
||||||
|
log('render', `${jobs.length} frames through the editor's renderer`);
|
||||||
|
|
||||||
|
let written;
|
||||||
|
try {
|
||||||
|
written = await drive(chromeBin, `${base}/.film-samples/`, jobs, options.out, options.quality);
|
||||||
|
} finally {
|
||||||
|
await server.close();
|
||||||
|
await rm(DIR, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 }).catch(() => {});
|
||||||
|
}
|
||||||
|
if (written.length !== jobs.length) fail(`only ${written.length} of ${jobs.length} frames rendered`);
|
||||||
|
|
||||||
|
await writeFile(
|
||||||
|
path.join(options.out, 'film-looks.json'),
|
||||||
|
`${JSON.stringify({ total: FILM_PRESETS.length, categories: catalogue }, null, 2)}\n`,
|
||||||
|
);
|
||||||
|
await writeFile(path.join(options.out, 'film.html'), buildPage(catalogue, framesByCategory));
|
||||||
|
|
||||||
|
const bytes = (
|
||||||
|
await Promise.all(written.map((file) => readFile(path.join(options.out, file))))
|
||||||
|
).reduce((sum, buffer) => sum + buffer.length, 0);
|
||||||
|
|
||||||
|
process.stdout.write(
|
||||||
|
[
|
||||||
|
'',
|
||||||
|
'film gallery PASSED',
|
||||||
|
` frames ${written.length} JPEGs, ${(bytes / 1024 / 1024).toFixed(1)} MB`,
|
||||||
|
` looks ${FILM_PRESETS.length} across ${catalogue.length} categories`,
|
||||||
|
` filters ${BW_FILTERS.length} on ${BW_DEMO_STOCK}`,
|
||||||
|
` page ${path.join(options.out, 'film.html')}`,
|
||||||
|
` data ${path.join(options.out, 'film-looks.json')}`,
|
||||||
|
'',
|
||||||
|
'Copy the frames to assets/film/ and film.html to the site root.',
|
||||||
|
'',
|
||||||
|
].join('\n'),
|
||||||
|
);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
main().then(
|
||||||
|
(code) => {
|
||||||
|
process.exitCode = code;
|
||||||
|
},
|
||||||
|
(error) => {
|
||||||
|
fail(error instanceof Error ? error.message : String(error));
|
||||||
|
},
|
||||||
|
);
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
/**
|
||||||
|
* Pre-deploy gate: typecheck, unit suite, render check, then the production
|
||||||
|
* build -- skipped when nothing that feeds the bundle has changed since the
|
||||||
|
* last successful build, so editing only a test file does not rebuild dist.
|
||||||
|
*
|
||||||
|
* The signature is stored under node_modules/.cache: that directory is
|
||||||
|
* gitignored and excluded from the deploy rsync, so it is per-checkout state
|
||||||
|
* and never travels to the server.
|
||||||
|
*
|
||||||
|
* Exits via process.exitCode rather than process.exit(): piped stdout is async
|
||||||
|
* and exiting early truncates the failure message.
|
||||||
|
*/
|
||||||
|
import { createHash } from 'node:crypto';
|
||||||
|
import { execFileSync } from 'node:child_process';
|
||||||
|
import {
|
||||||
|
existsSync,
|
||||||
|
mkdirSync,
|
||||||
|
readFileSync,
|
||||||
|
readdirSync,
|
||||||
|
statSync,
|
||||||
|
writeFileSync,
|
||||||
|
} from 'node:fs';
|
||||||
|
import path from 'node:path';
|
||||||
|
|
||||||
|
const ROOT = process.cwd();
|
||||||
|
const CACHE = path.join(ROOT, 'node_modules', '.cache', 'luminary-predeploy.json');
|
||||||
|
|
||||||
|
/** Vite inputs: everything the bundle is built from, plus the config it reads. */
|
||||||
|
const INPUTS = [
|
||||||
|
'src',
|
||||||
|
'public',
|
||||||
|
'index.html',
|
||||||
|
'vite.config.ts',
|
||||||
|
'tsconfig.json',
|
||||||
|
'package.json',
|
||||||
|
'package-lock.json',
|
||||||
|
];
|
||||||
|
|
||||||
|
/** Test files never reach the bundle, so their edits must not force a rebuild. */
|
||||||
|
const NOT_BUNDLED = /(^|\/)(__tests__|__mocks__|__fixtures__)(\/|$)|\.(test|spec)\.[cm]?[jt]sx?$/;
|
||||||
|
|
||||||
|
class StepFailed extends Error {}
|
||||||
|
|
||||||
|
function walk(target) {
|
||||||
|
if (!existsSync(target)) return [];
|
||||||
|
if (statSync(target).isFile()) return [target];
|
||||||
|
return readdirSync(target, { withFileTypes: true }).flatMap((entry) =>
|
||||||
|
walk(path.join(target, entry.name)),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function inputSignature() {
|
||||||
|
const files = INPUTS.flatMap((entry) => walk(entry))
|
||||||
|
.map((file) => path.relative(ROOT, file).split(path.sep).join('/'))
|
||||||
|
.filter((file) => !NOT_BUNDLED.test(file))
|
||||||
|
.sort();
|
||||||
|
const hash = createHash('sha256');
|
||||||
|
for (const file of files) {
|
||||||
|
hash.update(file);
|
||||||
|
hash.update('\0');
|
||||||
|
hash.update(readFileSync(path.join(ROOT, file)));
|
||||||
|
hash.update('\0');
|
||||||
|
}
|
||||||
|
return { count: files.length, digest: hash.digest('hex') };
|
||||||
|
}
|
||||||
|
|
||||||
|
function run(name, args) {
|
||||||
|
console.log(`\npredeploy: ${name}`);
|
||||||
|
try {
|
||||||
|
execFileSync('npm', args, { cwd: ROOT, stdio: 'inherit' });
|
||||||
|
} catch {
|
||||||
|
throw new StepFailed(name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function main() {
|
||||||
|
const signature = inputSignature();
|
||||||
|
const previous = existsSync(CACHE) ? JSON.parse(readFileSync(CACHE, 'utf8')) : null;
|
||||||
|
const upToDate =
|
||||||
|
existsSync(path.join(ROOT, 'dist', 'index.html')) && previous?.digest === signature.digest;
|
||||||
|
|
||||||
|
try {
|
||||||
|
run('typecheck', ['run', 'typecheck']);
|
||||||
|
run('tests', ['run', 'test']);
|
||||||
|
run('render check', ['run', 'check:render']);
|
||||||
|
if (upToDate) {
|
||||||
|
console.log(
|
||||||
|
`\npredeploy: build skipped - the ${signature.count} bundle inputs are unchanged since the last build.`,
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
run('build', ['run', 'build']);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
if (!(err instanceof StepFailed)) throw err;
|
||||||
|
console.error(`\npredeploy FAILED at ${err.message}.`);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!upToDate) {
|
||||||
|
mkdirSync(path.dirname(CACHE), { recursive: true });
|
||||||
|
writeFileSync(
|
||||||
|
CACHE,
|
||||||
|
`${JSON.stringify({ digest: signature.digest, count: signature.count, at: new Date().toISOString() }, null, 2)}\n`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('\npredeploy PASSED.');
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
process.exitCode = main();
|
||||||
@@ -0,0 +1,740 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
/**
|
||||||
|
* Headless render check for the 16-bit proxy swap.
|
||||||
|
*
|
||||||
|
* The editor shows the JPEG proxy first and swaps in the 16-bit sidecar a few
|
||||||
|
* seconds later. Both uploads go through `Renderer.setImage`, and whether they
|
||||||
|
* agree depends on a WebGL detail that no unit test can cover: `UNPACK_FLIP_Y_WEBGL`
|
||||||
|
* is ignored for `ImageBitmap` sources (the proxy) but honoured for typed arrays
|
||||||
|
* (the sidecar). If the two disagree, the picture jumps upside down at the swap.
|
||||||
|
*
|
||||||
|
* This script builds a two-tone 16-bit PNG with the server's own encoder plus the
|
||||||
|
* matching JPEG, serves `parsePreview16` through Vite, and measures the rows that
|
||||||
|
* actually reach the GPU in headless Chrome. It fails if the top row of the proxy
|
||||||
|
* is not the top row of the sidecar.
|
||||||
|
*
|
||||||
|
* Runs outside `npm test` because it needs a WebGL2-capable Chrome:
|
||||||
|
* npm run check:render
|
||||||
|
*/
|
||||||
|
import { spawn } from 'node:child_process';
|
||||||
|
import { existsSync } from 'node:fs';
|
||||||
|
import { mkdir, rm, writeFile } from 'node:fs/promises';
|
||||||
|
import path from 'node:path';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
import sharp from 'sharp';
|
||||||
|
import { createServer } from 'vite';
|
||||||
|
import { encodePng16 } from '../server/imaging.mjs';
|
||||||
|
|
||||||
|
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||||
|
const DIR = path.join(ROOT, '.render-check');
|
||||||
|
const PAGE = path.join(DIR, 'index.html');
|
||||||
|
const W = 96;
|
||||||
|
const H = 64;
|
||||||
|
|
||||||
|
const CHROME_CANDIDATES = [
|
||||||
|
process.env.CHROME_PATH,
|
||||||
|
'google-chrome',
|
||||||
|
'google-chrome-stable',
|
||||||
|
'chromium',
|
||||||
|
'chromium-browser',
|
||||||
|
].filter(Boolean);
|
||||||
|
|
||||||
|
async function findChrome() {
|
||||||
|
for (const candidate of CHROME_CANDIDATES) {
|
||||||
|
if (candidate.includes(path.sep)) {
|
||||||
|
if (existsSync(candidate)) return candidate;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (await spawnSyncOk(candidate)) return candidate;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function spawnSyncOk(bin) {
|
||||||
|
const probe = spawn(bin, ['--version'], { stdio: 'ignore' });
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
probe.on('error', () => resolve(false));
|
||||||
|
probe.on('exit', (code) => resolve(code === 0));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Horizontal bands that exercise both ends of the range: one and two channels
|
||||||
|
* blown, one clean band, then one and two channels crushed, plus a green+blue
|
||||||
|
* crush to check the secondary colour. The same image proves the clipping
|
||||||
|
* overlay names the channels instead of painting every warning one colour.
|
||||||
|
*/
|
||||||
|
const BANDS = [
|
||||||
|
[1.0, 0.55, 0.08], // highlight: red only
|
||||||
|
[1.0, 1.0, 0.08], // highlight: red + green (yellow)
|
||||||
|
[0.24, 0.28, 0.35], // nothing clipped
|
||||||
|
[0.0, 0.3, 0.35], // shadow: red only
|
||||||
|
[0.0, 0.0, 0.35], // shadow: red + green (yellow)
|
||||||
|
[0.3, 0.0, 0.0], // shadow: green + blue (cyan)
|
||||||
|
];
|
||||||
|
|
||||||
|
function buildSource() {
|
||||||
|
const rgb16 = new Uint16Array(W * H * 3);
|
||||||
|
const rgb8 = new Uint8Array(W * H * 3);
|
||||||
|
const bands = BANDS;
|
||||||
|
for (let y = 0; y < H; y++) {
|
||||||
|
const band = bands[Math.min(bands.length - 1, Math.floor((y / H) * bands.length))];
|
||||||
|
for (let x = 0; x < W; x++) {
|
||||||
|
const i = (y * W + x) * 3;
|
||||||
|
for (let c = 0; c < 3; c++) {
|
||||||
|
rgb16[i + c] = Math.round(band[c] * 65535);
|
||||||
|
rgb8[i + c] = Math.round(band[c] * 255);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { rgb8, rgb16 };
|
||||||
|
}
|
||||||
|
|
||||||
|
const PAGE_HTML = `<!doctype html>
|
||||||
|
<meta charset="utf-8" />
|
||||||
|
<pre id="out">boot</pre>
|
||||||
|
<script type="module">
|
||||||
|
import { parsePreview16 } from '/src/lib/preview16.ts';
|
||||||
|
import { Renderer } from '/src/gl/renderer.ts';
|
||||||
|
import { defaultEdits, defaultLocalComponent, defaultLocalLayer } from '/src/lib/edits.ts';
|
||||||
|
const pre = document.getElementById('out');
|
||||||
|
const half = (bits) => {
|
||||||
|
const s = bits >> 15 ? -1 : 1;
|
||||||
|
const e = (bits >> 10) & 0x1f;
|
||||||
|
const m = bits & 0x3ff;
|
||||||
|
if (e === 0) return s * m * Math.pow(2, -24);
|
||||||
|
if (e === 31) return m ? NaN : s * Infinity;
|
||||||
|
return s * (1 + m / 1024) * Math.pow(2, e - 15);
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
const canvas = document.createElement('canvas');
|
||||||
|
const gl = canvas.getContext('webgl2', { alpha: false, antialias: false });
|
||||||
|
if (!gl) { pre.textContent = 'ERROR no WebGL2 in this Chrome'; throw new Error('no webgl2'); }
|
||||||
|
const makeTex = () => {
|
||||||
|
const t = gl.createTexture();
|
||||||
|
gl.bindTexture(gl.TEXTURE_2D, t);
|
||||||
|
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
|
||||||
|
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
|
||||||
|
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
|
||||||
|
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
|
||||||
|
return t;
|
||||||
|
};
|
||||||
|
// readPixels rows start at the framebuffer's bottom row, which is texel row 0.
|
||||||
|
const rowLuma = (tex, y, w) => {
|
||||||
|
gl.bindTexture(gl.TEXTURE_2D, tex);
|
||||||
|
const fb = gl.createFramebuffer();
|
||||||
|
gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
|
||||||
|
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
|
||||||
|
if (gl.checkFramebufferStatus(gl.FRAMEBUFFER) !== gl.FRAMEBUFFER_COMPLETE) {
|
||||||
|
throw new Error('framebuffer incomplete');
|
||||||
|
}
|
||||||
|
const buf = new Uint8Array(w * 4);
|
||||||
|
gl.readPixels(0, y, w, 1, gl.RGBA, gl.UNSIGNED_BYTE, buf);
|
||||||
|
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
|
||||||
|
gl.deleteFramebuffer(fb);
|
||||||
|
let sum = 0;
|
||||||
|
for (let i = 0; i < w; i++) {
|
||||||
|
sum += 0.2126 * buf[i * 4] + 0.7152 * buf[i * 4 + 1] + 0.0722 * buf[i * 4 + 2];
|
||||||
|
}
|
||||||
|
return sum / w / 255;
|
||||||
|
};
|
||||||
|
|
||||||
|
const blob = await (await fetch('/.render-check/proxy.jpg')).blob();
|
||||||
|
const bitmap = await createImageBitmap(blob, { imageOrientation: 'from-image' });
|
||||||
|
const w = bitmap.width;
|
||||||
|
const h = bitmap.height;
|
||||||
|
|
||||||
|
// Exactly what Renderer.setImage does for the JPEG proxy.
|
||||||
|
const texFlip = makeTex();
|
||||||
|
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
|
||||||
|
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, gl.RGBA, gl.UNSIGNED_BYTE, bitmap);
|
||||||
|
const texNoFlip = makeTex();
|
||||||
|
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
|
||||||
|
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, gl.RGBA, gl.UNSIGNED_BYTE, bitmap);
|
||||||
|
|
||||||
|
const png = await (await fetch('/.render-check/side.p16.png')).arrayBuffer();
|
||||||
|
const parsed = await parsePreview16(png);
|
||||||
|
if (!parsed) throw new Error('parsePreview16 returned null');
|
||||||
|
if (parsed.width !== w || parsed.height !== h) {
|
||||||
|
throw new Error('sidecar ' + parsed.width + 'x' + parsed.height + ' vs proxy ' + w + 'x' + h);
|
||||||
|
}
|
||||||
|
// Exactly what Renderer.setImage does for the sidecar: rows in parser order, unflipped.
|
||||||
|
const sideRow = (y) => {
|
||||||
|
const out = new Uint8Array(w * 4);
|
||||||
|
for (let x = 0; x < w; x++) {
|
||||||
|
const i = (y * w + x) * 4;
|
||||||
|
const toByte = (bits) => Math.round(Math.min(1, Math.max(0, half(bits))) * 255);
|
||||||
|
out[x * 4] = toByte(parsed.rgba[i]);
|
||||||
|
out[x * 4 + 1] = toByte(parsed.rgba[i + 1]);
|
||||||
|
out[x * 4 + 2] = toByte(parsed.rgba[i + 2]);
|
||||||
|
out[x * 4 + 3] = 255;
|
||||||
|
}
|
||||||
|
const tex = makeTex();
|
||||||
|
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
|
||||||
|
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, w, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, out);
|
||||||
|
return tex;
|
||||||
|
};
|
||||||
|
const sideTopTex = sideRow(0);
|
||||||
|
const sideBottomTex = sideRow(h - 1);
|
||||||
|
|
||||||
|
const proxyTop = rowLuma(texFlip, 0, w);
|
||||||
|
const proxyBottom = rowLuma(texFlip, h - 1, w);
|
||||||
|
const proxyNoFlipTop = rowLuma(texNoFlip, 0, w);
|
||||||
|
const sideTop = rowLuma(sideTopTex, 0, w);
|
||||||
|
const sideBottom = rowLuma(sideBottomTex, 0, w);
|
||||||
|
const same = (a, b) => Math.abs(a - b) < 0.02;
|
||||||
|
|
||||||
|
// Clipping overlay: red for one clipped channel, yellow for two. This renders
|
||||||
|
// through the real Renderer, so a shader that collapses the warning to white
|
||||||
|
// (or loses the shadow/highlight bit) fails here.
|
||||||
|
const view = document.createElement('canvas');
|
||||||
|
const renderer = new Renderer(view);
|
||||||
|
renderer.setImage(bitmap, parsed);
|
||||||
|
renderer.render(defaultEdits(), { width: w, height: h, clipPreview: true });
|
||||||
|
const viewGl = view.getContext('webgl2');
|
||||||
|
const sampleBand = (index) => {
|
||||||
|
// readPixels rows start at the bottom, so flip the band centre.
|
||||||
|
const py = h - 1 - Math.floor((h * (index + 0.5)) / ${BANDS.length});
|
||||||
|
const px = new Uint8Array(4);
|
||||||
|
viewGl.readPixels(Math.floor(w / 2), py, 1, 1, viewGl.RGBA, viewGl.UNSIGNED_BYTE, px);
|
||||||
|
return [px[0], px[1], px[2]];
|
||||||
|
};
|
||||||
|
const clipPixels = [0, 1, 2].map(sampleBand);
|
||||||
|
const near = (pixel, target) =>
|
||||||
|
Math.abs(pixel[0] - target[0]) < 14 &&
|
||||||
|
Math.abs(pixel[1] - target[1]) < 14 &&
|
||||||
|
Math.abs(pixel[2] - target[2]) < 14;
|
||||||
|
const RED_MARK = [255, 31, 31];
|
||||||
|
const YELLOW_MARK = [255, 230, 26];
|
||||||
|
// The preview has to follow the sliders it is shown for: +6 EV blows every
|
||||||
|
// channel of the unclipped band, so it must turn white, not stay clear.
|
||||||
|
const brightEdits = defaultEdits();
|
||||||
|
brightEdits.exposure = 6;
|
||||||
|
renderer.render(brightEdits, { width: w, height: h, clipPreview: true });
|
||||||
|
const brightPixel = sampleBand(2);
|
||||||
|
|
||||||
|
// Shadow clipping: same palette at the other end of the histogram.
|
||||||
|
renderer.render(defaultEdits(), { width: w, height: h, clipping: 'shadows' });
|
||||||
|
const shadowPixels = [2, 3, 4, 5].map(sampleBand);
|
||||||
|
|
||||||
|
// And it has to move with the sliders, not just exist: -9 EV drives every
|
||||||
|
// channel of the clean band to black, so that band must turn white in shadow
|
||||||
|
// mode, just as it turns white at +6 EV in highlight mode.
|
||||||
|
const shadowEdits = defaultEdits();
|
||||||
|
shadowEdits.exposure = -9;
|
||||||
|
renderer.render(shadowEdits, { width: w, height: h, clipping: 'shadows' });
|
||||||
|
const shadowDarkPixel = sampleBand(2);
|
||||||
|
|
||||||
|
// Per-mask curve: a radial covering the whole frame, first with an identity
|
||||||
|
// curve and then with one that halves the output. The mask must leave the
|
||||||
|
// frame alone with the identity curve and darken it with the real one.
|
||||||
|
const maskLayer = defaultLocalLayer('radial', 0);
|
||||||
|
const maskShape = maskLayer.components[0];
|
||||||
|
maskShape.feather = 0;
|
||||||
|
maskShape.radial = { cx: 0.5, cy: 0.5, rx: 1.2, ry: 1.2 };
|
||||||
|
const darkCurve = [
|
||||||
|
{ x: 0, y: 0 },
|
||||||
|
{ x: 1, y: 0.4 },
|
||||||
|
];
|
||||||
|
const maskedEdits = defaultEdits();
|
||||||
|
maskedEdits.local = [{ ...maskLayer, curve: [{ x: 0, y: 0 }, { x: 1, y: 1 }] }];
|
||||||
|
renderer.render(maskedEdits, { width: w, height: h });
|
||||||
|
const maskIdentityPixel = sampleBand(2);
|
||||||
|
maskedEdits.local = [{ ...maskLayer, curve: darkCurve }];
|
||||||
|
renderer.render(maskedEdits, { width: w, height: h });
|
||||||
|
const maskCurvePixel = sampleBand(2);
|
||||||
|
|
||||||
|
// Mask groups: a second shape has to composite into the layer's own mask.
|
||||||
|
// Subtracting a frame-wide shape from an equally wide add shape clears the
|
||||||
|
// group, so the darkened curve must stop touching the frame; intersecting
|
||||||
|
// with the same shape keeps full coverage, so it must still darken.
|
||||||
|
const groupShape = defaultLocalComponent('radial');
|
||||||
|
groupShape.feather = 0;
|
||||||
|
groupShape.radial = { cx: 0.5, cy: 0.5, rx: 1.2, ry: 1.2 };
|
||||||
|
const groupEdits = defaultEdits();
|
||||||
|
groupEdits.local = [
|
||||||
|
{
|
||||||
|
...maskLayer,
|
||||||
|
curve: darkCurve,
|
||||||
|
components: [maskShape, { ...groupShape, mode: 'subtract' }],
|
||||||
|
},
|
||||||
|
];
|
||||||
|
renderer.render(groupEdits, { width: w, height: h });
|
||||||
|
const maskGroupSubtractPixel = sampleBand(2);
|
||||||
|
groupEdits.local = [
|
||||||
|
{
|
||||||
|
...maskLayer,
|
||||||
|
curve: darkCurve,
|
||||||
|
components: [maskShape, { ...groupShape, mode: 'intersect' }],
|
||||||
|
},
|
||||||
|
];
|
||||||
|
renderer.render(groupEdits, { width: w, height: h });
|
||||||
|
const maskGroupIntersectPixel = sampleBand(2);
|
||||||
|
|
||||||
|
// Brush masks are source-space and feather softens the rim inside the brush
|
||||||
|
// circle. The dab below has a radius of 0.08 of the frame width, so it spans
|
||||||
|
// 0.12 of the frame height; nothing outside that may be touched, even at a
|
||||||
|
// high feather, and the rim itself must be a gradient rather than a step.
|
||||||
|
const pixelAt = (fx, fy) => {
|
||||||
|
const px = new Uint8Array(4);
|
||||||
|
const py = h - 1 - Math.min(h - 1, Math.floor(fy * h));
|
||||||
|
viewGl.readPixels(Math.min(w - 1, Math.floor(fx * w)), py, 1, 1, viewGl.RGBA, viewGl.UNSIGNED_BYTE, px);
|
||||||
|
return [px[0], px[1], px[2]];
|
||||||
|
};
|
||||||
|
const dabRadiusY = 0.08 * (w / h);
|
||||||
|
const brushEdits = (feather) => {
|
||||||
|
const layer = defaultLocalLayer('brush', 0);
|
||||||
|
const shape = layer.components[0];
|
||||||
|
shape.feather = feather;
|
||||||
|
shape.brush.strokes = [{ points: [{ x: 0.25, y: 0.2 }], size: 0.08, erase: false }];
|
||||||
|
return { ...defaultEdits(), local: [{ ...layer, curve: darkCurve }] };
|
||||||
|
};
|
||||||
|
renderer.render(brushEdits(0), { width: w, height: h });
|
||||||
|
const dabHard = pixelAt(0.25, 0.2);
|
||||||
|
const dabOutsideHard = pixelAt(0.25, 0.2 + dabRadiusY * 1.15);
|
||||||
|
renderer.render(brushEdits(80), { width: w, height: h });
|
||||||
|
const dabSoft = pixelAt(0.25, 0.2);
|
||||||
|
const dabRimSoft = pixelAt(0.25, 0.2 + dabRadiusY * 0.75);
|
||||||
|
const dabOutsideSoft = pixelAt(0.25, 0.2 + dabRadiusY * 1.15);
|
||||||
|
// The develop view tints the baked mask instead of redrawing the stroke, so
|
||||||
|
// the overlay has to follow the same coverage: strong in the core, a real
|
||||||
|
// gradient at the rim, and nothing at all outside the brush circle.
|
||||||
|
renderer.render(brushEdits(80), { width: w, height: h, maskView: 0 });
|
||||||
|
const tintCore = pixelAt(0.25, 0.2);
|
||||||
|
const tintRim = pixelAt(0.25, 0.2 + dabRadiusY * 0.75);
|
||||||
|
const tintOutside = pixelAt(0.25, 0.2 + dabRadiusY * 1.15);
|
||||||
|
|
||||||
|
// Source-space alignment. Masks are baked over the whole source, so a crop
|
||||||
|
// that keeps a dab in frame but moves it on screen must move its tint and
|
||||||
|
// its local detail with it: source (0.6, 0.4) inside a quarter-frame crop
|
||||||
|
// lands at screen (0.4, 0.6), and nothing may be tinted at (0.6, 0.4).
|
||||||
|
const cropRect = {
|
||||||
|
x: 0.5,
|
||||||
|
y: 0.25,
|
||||||
|
w: 0.25,
|
||||||
|
h: 0.25,
|
||||||
|
angle: 0,
|
||||||
|
quarter: 0,
|
||||||
|
aspect: 'original',
|
||||||
|
flipH: false,
|
||||||
|
flipV: false,
|
||||||
|
};
|
||||||
|
const dabEdits = (at, size, adjust) => {
|
||||||
|
const layer = defaultLocalLayer('brush', 0);
|
||||||
|
const shape = layer.components[0];
|
||||||
|
shape.feather = 0;
|
||||||
|
shape.brush.strokes = [{ points: [at], size, erase: false }];
|
||||||
|
return {
|
||||||
|
...defaultEdits(),
|
||||||
|
local: [{ ...layer, adjust: { ...layer.adjust, ...(adjust || {}) } }],
|
||||||
|
};
|
||||||
|
};
|
||||||
|
const cropped = { ...defaultEdits(), crop: cropRect };
|
||||||
|
renderer.render(cropped, { width: w, height: h });
|
||||||
|
const cropRef = pixelAt(0.4, 0.6);
|
||||||
|
const cropRefOff = pixelAt(0.6, 0.4);
|
||||||
|
const cropDab = dabEdits({ x: 0.6, y: 0.4 }, 0.02);
|
||||||
|
cropDab.crop = cropRect;
|
||||||
|
renderer.render(cropDab, { width: w, height: h, maskView: 0 });
|
||||||
|
const cropTintOn = pixelAt(0.4, 0.6);
|
||||||
|
const cropTintOff = pixelAt(0.6, 0.4);
|
||||||
|
// Same crop and dab, but as a local detail amount instead of a tint: the
|
||||||
|
// finish pass has to read the mask through the same source coordinate.
|
||||||
|
const cropDetail = dabEdits({ x: 0.6, y: 0.4 }, 0.02, { dehaze: 100 });
|
||||||
|
cropDetail.crop = cropRect;
|
||||||
|
renderer.render(cropDetail, { width: w, height: h });
|
||||||
|
const cropDetailOn = pixelAt(0.4, 0.6);
|
||||||
|
const cropDetailOff = pixelAt(0.6, 0.4);
|
||||||
|
|
||||||
|
// Tint strength and toggle: full strength must read stronger than the default
|
||||||
|
// half, and no maskView at all must leave the photo untouched.
|
||||||
|
renderer.render(brushEdits(80), { width: w, height: h, maskView: 0, maskStrength: 1 });
|
||||||
|
const tintFull = pixelAt(0.25, 0.2);
|
||||||
|
renderer.render(brushEdits(80), { width: w, height: h });
|
||||||
|
const tintOffPixel = pixelAt(0.25, 0.2);
|
||||||
|
|
||||||
|
// Lens warp: a geometry map that magnifies the centre by 1.6 puts the dab at
|
||||||
|
// source (0.7, 0.45) at screen (0.625, 0.469); its source uv must be clear.
|
||||||
|
const lensN = 33;
|
||||||
|
const lensData = new Float32Array(lensN * lensN * 4);
|
||||||
|
for (let ly = 0; ly < lensN; ly++) {
|
||||||
|
for (let lx = 0; lx < lensN; lx++) {
|
||||||
|
const i = (ly * lensN + lx) * 4;
|
||||||
|
lensData[i] = 0.5 + ((lx + 0.5) / lensN - 0.5) * 1.6;
|
||||||
|
lensData[i + 1] = 0.5 + ((ly + 0.5) / lensN - 0.5) * 1.6;
|
||||||
|
lensData[i + 2] = 0;
|
||||||
|
lensData[i + 3] = 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const lensWarp = {
|
||||||
|
key: 'render-check-warp',
|
||||||
|
scale: 1,
|
||||||
|
geometry: { data: lensData, width: lensN, height: lensN },
|
||||||
|
};
|
||||||
|
renderer.render(defaultEdits(), { width: w, height: h, lens: lensWarp });
|
||||||
|
const lensRef = pixelAt(0.625, 0.469);
|
||||||
|
const lensRefOff = pixelAt(0.7, 0.469);
|
||||||
|
const lensDab = dabEdits({ x: 0.7, y: 0.45 }, 0.04);
|
||||||
|
renderer.render(lensDab, { width: w, height: h, lens: lensWarp, maskView: 0 });
|
||||||
|
const lensTintOn = pixelAt(0.625, 0.469);
|
||||||
|
const lensTintOff = pixelAt(0.7, 0.469);
|
||||||
|
|
||||||
|
pre.textContent = 'RESULT ' + JSON.stringify({
|
||||||
|
clipPixels,
|
||||||
|
clipRed: near(clipPixels[0], RED_MARK),
|
||||||
|
clipYellow: near(clipPixels[1], YELLOW_MARK),
|
||||||
|
clipClear:
|
||||||
|
!near(clipPixels[2], RED_MARK) &&
|
||||||
|
!near(clipPixels[2], YELLOW_MARK) &&
|
||||||
|
!near(clipPixels[2], [255, 255, 255]),
|
||||||
|
clipFollowsExposure: near(brightPixel, [255, 255, 255]),
|
||||||
|
brightPixel,
|
||||||
|
shadowPixels,
|
||||||
|
shadowClear:
|
||||||
|
!near(shadowPixels[0], RED_MARK) && !near(shadowPixels[0], YELLOW_MARK),
|
||||||
|
shadowRed: near(shadowPixels[1], RED_MARK),
|
||||||
|
shadowYellow: near(shadowPixels[2], YELLOW_MARK),
|
||||||
|
shadowCyan: near(shadowPixels[3], [26, 217, 255]),
|
||||||
|
shadowFollowsExposure: near(shadowDarkPixel, [255, 255, 255]),
|
||||||
|
shadowDarkPixel,
|
||||||
|
maskIdentityPixel,
|
||||||
|
maskCurvePixel,
|
||||||
|
maskIdentityFlat: near(maskIdentityPixel, [61, 71, 89]),
|
||||||
|
maskCurveDarkens: maskCurvePixel[0] < maskIdentityPixel[0] * 0.75,
|
||||||
|
maskGroupSubtractPixel,
|
||||||
|
maskGroupSubtractCleared: near(maskGroupSubtractPixel, maskIdentityPixel),
|
||||||
|
maskGroupIntersectPixel,
|
||||||
|
maskGroupIntersectDarkens: maskGroupIntersectPixel[0] < maskIdentityPixel[0] * 0.75,
|
||||||
|
dabHard,
|
||||||
|
dabOutsideHard,
|
||||||
|
dabSoft,
|
||||||
|
dabRimSoft,
|
||||||
|
dabOutsideSoft,
|
||||||
|
tintCore,
|
||||||
|
tintRim,
|
||||||
|
tintOutside,
|
||||||
|
// Orange tint: blue is the channel the overlay pushes up, so it ranks the
|
||||||
|
// coverage without depending on how dark the adjustment left the pixels.
|
||||||
|
tintFollowsMask: tintCore[2] > tintRim[2] && tintRim[2] > tintOutside[2] + 5,
|
||||||
|
tintBounded: Math.abs(tintOutside[2] - dabOutsideSoft[2]) <= 1,
|
||||||
|
cropRef,
|
||||||
|
cropRefOff,
|
||||||
|
cropTintOn,
|
||||||
|
cropTintOff,
|
||||||
|
cropDetailOn,
|
||||||
|
cropDetailOff,
|
||||||
|
lensRef,
|
||||||
|
lensRefOff,
|
||||||
|
lensTintOn,
|
||||||
|
lensTintOff,
|
||||||
|
tintFull,
|
||||||
|
tintOffPixel,
|
||||||
|
// The tint pushes red up hard on the dark mid band, so red ranks coverage.
|
||||||
|
cropTintAligned: cropTintOn[0] > cropRef[0] + 40,
|
||||||
|
cropTintBounded: Math.abs(cropTintOff[0] - cropRefOff[0]) <= 2,
|
||||||
|
// Local dehaze lifts the blue of that band, so blue marks where it landed.
|
||||||
|
cropDetailAligned: cropDetailOn[2] > cropDetailOff[2] + 10,
|
||||||
|
cropDetailBounded: Math.abs(cropDetailOff[2] - cropRefOff[2]) <= 3,
|
||||||
|
lensTintAligned: lensTintOn[0] > lensRef[0] + 40,
|
||||||
|
lensTintBounded: Math.abs(lensTintOff[0] - lensRefOff[0]) <= 2,
|
||||||
|
tintStrengthWorks: tintFull[2] > tintCore[2] + 8,
|
||||||
|
tintOffMatches: Math.abs(tintOffPixel[2] - dabSoft[2]) <= 1,
|
||||||
|
// A hard dab covers the core, and even an 80 % feather stops at the rim.
|
||||||
|
dabCoreDarkened: dabHard[0] < 140,
|
||||||
|
dabSoftCoreDarkened: dabSoft[0] < 140,
|
||||||
|
dabRimSmooth: dabRimSoft[0] > 140 && dabRimSoft[0] < 240,
|
||||||
|
dabBoundedHard: dabOutsideHard[0] > 240,
|
||||||
|
dabBoundedSoft: dabOutsideSoft[0] > 240,
|
||||||
|
flagHonouredForBitmap: !same(proxyTop, proxyNoFlipTop),
|
||||||
|
proxyTop: +proxyTop.toFixed(4),
|
||||||
|
sidecarTop: +sideTop.toFixed(4),
|
||||||
|
proxyBottom: +proxyBottom.toFixed(4),
|
||||||
|
sidecarBottom: +sideBottom.toFixed(4),
|
||||||
|
matchTop: same(proxyTop, sideTop),
|
||||||
|
matchBottom: same(proxyBottom, sideBottom),
|
||||||
|
reversed: same(proxyTop, sideBottom) && same(proxyBottom, sideTop),
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
if (!String(pre.textContent).startsWith('ERROR')) {
|
||||||
|
pre.textContent = 'ERROR ' + (err && err.message ? err.message : String(err));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>`;
|
||||||
|
|
||||||
|
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||||
|
|
||||||
|
async function drive(chromeBin, url) {
|
||||||
|
const port = 9333 + Math.floor(Math.random() * 200);
|
||||||
|
const child = spawn(
|
||||||
|
chromeBin,
|
||||||
|
[
|
||||||
|
'--headless=new',
|
||||||
|
'--no-sandbox',
|
||||||
|
'--disable-gpu-sandbox',
|
||||||
|
'--use-gl=angle',
|
||||||
|
'--use-angle=swiftshader',
|
||||||
|
'--enable-unsafe-swiftshader',
|
||||||
|
`--remote-debugging-port=${port}`,
|
||||||
|
`--user-data-dir=${path.join(DIR, 'profile')}`,
|
||||||
|
'about:blank',
|
||||||
|
],
|
||||||
|
{ stdio: 'ignore' },
|
||||||
|
);
|
||||||
|
|
||||||
|
try {
|
||||||
|
let target = null;
|
||||||
|
for (let i = 0; i < 120 && !target; i++) {
|
||||||
|
try {
|
||||||
|
const res = await fetch(`http://127.0.0.1:${port}/json/list`);
|
||||||
|
target = (await res.json()).find((t) => t.type === 'page') ?? null;
|
||||||
|
} catch {
|
||||||
|
/* devtools not up yet */
|
||||||
|
}
|
||||||
|
if (!target) await sleep(250);
|
||||||
|
}
|
||||||
|
if (!target) throw new Error('Chrome DevTools endpoint never came up');
|
||||||
|
|
||||||
|
const ws = new WebSocket(target.webSocketDebuggerUrl);
|
||||||
|
await new Promise((resolve, reject) => {
|
||||||
|
ws.onopen = resolve;
|
||||||
|
ws.onerror = () => reject(new Error('DevTools websocket failed'));
|
||||||
|
});
|
||||||
|
let nextId = 1;
|
||||||
|
const pending = new Map();
|
||||||
|
ws.onmessage = (event) => {
|
||||||
|
const message = JSON.parse(event.data);
|
||||||
|
if (message.id && pending.has(message.id)) {
|
||||||
|
pending.get(message.id)(message);
|
||||||
|
pending.delete(message.id);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const send = (method, params = {}) => {
|
||||||
|
const id = nextId++;
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
pending.set(id, resolve);
|
||||||
|
ws.send(JSON.stringify({ id, method, params }));
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
await send('Page.enable');
|
||||||
|
await send('Runtime.enable');
|
||||||
|
await send('Page.navigate', { url });
|
||||||
|
|
||||||
|
let text = '';
|
||||||
|
const deadline = Date.now() + 90000;
|
||||||
|
while (Date.now() < deadline) {
|
||||||
|
const res = await send('Runtime.evaluate', {
|
||||||
|
expression: "document.getElementById('out')?.textContent ?? ''",
|
||||||
|
returnByValue: true,
|
||||||
|
});
|
||||||
|
text = res.result?.result?.value ?? '';
|
||||||
|
if (text.includes('RESULT') || text.startsWith('ERROR')) break;
|
||||||
|
await sleep(500);
|
||||||
|
}
|
||||||
|
ws.close();
|
||||||
|
return text;
|
||||||
|
} finally {
|
||||||
|
child.kill('SIGKILL');
|
||||||
|
// Chrome writes its profile until the process is gone; give it a moment so
|
||||||
|
// the cleanup below does not race the file handles it still holds.
|
||||||
|
await sleep(500);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
const chromeBin = await findChrome();
|
||||||
|
const { rgb8, rgb16 } = buildSource();
|
||||||
|
await mkdir(DIR, { recursive: true });
|
||||||
|
await writeFile(path.join(DIR, 'proxy.jpg'), await sharp(rgb8, { raw: { width: W, height: H, channels: 3 } })
|
||||||
|
.jpeg({ quality: 96, chromaSubsampling: '4:4:4' })
|
||||||
|
.toBuffer());
|
||||||
|
await writeFile(path.join(DIR, 'side.p16.png'), encodePng16(rgb16, W, H));
|
||||||
|
await writeFile(PAGE, PAGE_HTML);
|
||||||
|
|
||||||
|
const server = await createServer({
|
||||||
|
root: ROOT,
|
||||||
|
logLevel: 'error',
|
||||||
|
server: { host: '127.0.0.1', port: 5199, strictPort: false },
|
||||||
|
});
|
||||||
|
await server.listen();
|
||||||
|
const base = server.resolvedUrls?.local?.[0] ?? 'http://127.0.0.1:5199/';
|
||||||
|
|
||||||
|
let text = '';
|
||||||
|
try {
|
||||||
|
if (!chromeBin) {
|
||||||
|
console.log('render check SKIPPED: no Chrome/Chromium found (set CHROME_PATH to run it).');
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
text = await drive(chromeBin, `${base.replace(/\/$/, '')}/.render-check/`);
|
||||||
|
} finally {
|
||||||
|
await server.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (text.startsWith('ERROR')) {
|
||||||
|
console.error(`render check FAILED: ${text.slice(6)}`);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
const marker = text.indexOf('RESULT');
|
||||||
|
if (marker < 0) {
|
||||||
|
console.error('render check FAILED: the probe never reported a result.');
|
||||||
|
console.error(text.slice(0, 500));
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
const result = JSON.parse(text.slice(marker + 7));
|
||||||
|
console.log(
|
||||||
|
`render check: proxy top=${result.proxyTop} bottom=${result.proxyBottom}` +
|
||||||
|
` | sidecar top=${result.sidecarTop} bottom=${result.sidecarBottom}` +
|
||||||
|
` | flip flag honoured for ImageBitmap=${result.flagHonouredForBitmap}`,
|
||||||
|
);
|
||||||
|
console.log(
|
||||||
|
`render check: clipping overlay red=${JSON.stringify(result.clipPixels[0])}` +
|
||||||
|
` yellow=${JSON.stringify(result.clipPixels[1])}` +
|
||||||
|
` clear=${JSON.stringify(result.clipPixels[2])}` +
|
||||||
|
` | at +6EV the clear band is ${JSON.stringify(result.brightPixel)}`,
|
||||||
|
);
|
||||||
|
console.log(
|
||||||
|
`render check: shadow overlay clear=${JSON.stringify(result.shadowPixels[0])}` +
|
||||||
|
` red=${JSON.stringify(result.shadowPixels[1])}` +
|
||||||
|
` yellow=${JSON.stringify(result.shadowPixels[2])}` +
|
||||||
|
` cyan=${JSON.stringify(result.shadowPixels[3])}` +
|
||||||
|
` | at -9EV the clean band is ${JSON.stringify(result.shadowDarkPixel)}`,
|
||||||
|
);
|
||||||
|
console.log(
|
||||||
|
`render check: mask curve identity=${JSON.stringify(result.maskIdentityPixel)}` +
|
||||||
|
` darkened=${JSON.stringify(result.maskCurvePixel)}`,
|
||||||
|
);
|
||||||
|
console.log(
|
||||||
|
`render check: mask group subtract=${JSON.stringify(result.maskGroupSubtractPixel)}` +
|
||||||
|
` intersect=${JSON.stringify(result.maskGroupIntersectPixel)}`,
|
||||||
|
);
|
||||||
|
if (!result.matchTop || !result.matchBottom) {
|
||||||
|
console.error(
|
||||||
|
result.reversed
|
||||||
|
? 'render check FAILED: the sidecar lands upside down against the proxy.'
|
||||||
|
: 'render check FAILED: proxy and sidecar rows do not line up.',
|
||||||
|
);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
if (!result.clipRed || !result.clipYellow || !result.clipClear) {
|
||||||
|
console.error(
|
||||||
|
'render check FAILED: the clipping overlay lost its channel colours ' +
|
||||||
|
`(red=${result.clipRed}, yellow=${result.clipYellow}, clear=${result.clipClear}).`,
|
||||||
|
);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
if (!result.shadowClear || !result.shadowRed || !result.shadowYellow || !result.shadowCyan) {
|
||||||
|
console.error(
|
||||||
|
'render check FAILED: the shadow clipping overlay lost its channel colours ' +
|
||||||
|
`(clear=${result.shadowClear}, red=${result.shadowRed}, ` +
|
||||||
|
`yellow=${result.shadowYellow}, cyan=${result.shadowCyan}).`,
|
||||||
|
);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
if (!result.maskIdentityFlat || !result.maskCurveDarkens) {
|
||||||
|
console.error(
|
||||||
|
'render check FAILED: the per-mask curve is not reaching the grade ' +
|
||||||
|
`(identity=${JSON.stringify(result.maskIdentityPixel)}, ` +
|
||||||
|
`curve=${JSON.stringify(result.maskCurvePixel)}).`,
|
||||||
|
);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
if (!result.maskGroupSubtractCleared || !result.maskGroupIntersectDarkens) {
|
||||||
|
console.error(
|
||||||
|
'render check FAILED: mask group shapes are not compositing ' +
|
||||||
|
`(subtract=${JSON.stringify(result.maskGroupSubtractPixel)}, ` +
|
||||||
|
`intersect=${JSON.stringify(result.maskGroupIntersectPixel)}).`,
|
||||||
|
);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
if (!result.shadowFollowsExposure) {
|
||||||
|
console.error(
|
||||||
|
'render check FAILED: the shadow clipping overlay does not follow Exposure; ' +
|
||||||
|
`at -9EV the clean band stayed ${JSON.stringify(result.shadowDarkPixel)}.`,
|
||||||
|
);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
if (!result.clipFollowsExposure) {
|
||||||
|
console.error(
|
||||||
|
'render check FAILED: the clipping overlay does not follow Exposure; ' +
|
||||||
|
`the unclipped band stayed ${JSON.stringify(result.brightPixel)} at +6 EV.`,
|
||||||
|
);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
console.log(
|
||||||
|
`render check: brush dab hard=${JSON.stringify(result.dabHard)}` +
|
||||||
|
` outsideHard=${JSON.stringify(result.dabOutsideHard)} soft=${JSON.stringify(result.dabSoft)}` +
|
||||||
|
` rimSoft=${JSON.stringify(result.dabRimSoft)} outsideSoft=${JSON.stringify(result.dabOutsideSoft)}`,
|
||||||
|
);
|
||||||
|
console.log(
|
||||||
|
`render check: mask overlay core=${JSON.stringify(result.tintCore)}` +
|
||||||
|
` rim=${JSON.stringify(result.tintRim)} outside=${JSON.stringify(result.tintOutside)}`,
|
||||||
|
);
|
||||||
|
console.log(
|
||||||
|
`render check: crop mask tint on=${JSON.stringify(result.cropTintOn)}` +
|
||||||
|
` off=${JSON.stringify(result.cropTintOff)} ref=${JSON.stringify(result.cropRef)}` +
|
||||||
|
` | local detail on=${JSON.stringify(result.cropDetailOn)}` +
|
||||||
|
` off=${JSON.stringify(result.cropDetailOff)}`,
|
||||||
|
);
|
||||||
|
console.log(
|
||||||
|
`render check: lens mask tint on=${JSON.stringify(result.lensTintOn)}` +
|
||||||
|
` off=${JSON.stringify(result.lensTintOff)} ref=${JSON.stringify(result.lensRef)}` +
|
||||||
|
` | tint strength full=${JSON.stringify(result.tintFull)}` +
|
||||||
|
` half=${JSON.stringify(result.tintCore)}`,
|
||||||
|
);
|
||||||
|
if (
|
||||||
|
!result.cropTintAligned ||
|
||||||
|
!result.cropTintBounded ||
|
||||||
|
!result.cropDetailAligned ||
|
||||||
|
!result.cropDetailBounded ||
|
||||||
|
!result.lensTintAligned ||
|
||||||
|
!result.lensTintBounded ||
|
||||||
|
!result.tintStrengthWorks ||
|
||||||
|
!result.tintOffMatches
|
||||||
|
) {
|
||||||
|
console.error(
|
||||||
|
'render check FAILED: the local mask does not stay on its source pixels ' +
|
||||||
|
'through a crop or a lens warp ' +
|
||||||
|
`(crop tint ${JSON.stringify(result.cropTintOn)}/${JSON.stringify(result.cropTintOff)}` +
|
||||||
|
` vs ${JSON.stringify(result.cropRef)}, detail ` +
|
||||||
|
`${JSON.stringify(result.cropDetailOn)}/${JSON.stringify(result.cropDetailOff)}` +
|
||||||
|
`, lens tint ${JSON.stringify(result.lensTintOn)}/${JSON.stringify(result.lensTintOff)}` +
|
||||||
|
` vs ${JSON.stringify(result.lensRef)}).`,
|
||||||
|
);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
!result.dabCoreDarkened ||
|
||||||
|
!result.dabSoftCoreDarkened ||
|
||||||
|
!result.dabRimSmooth ||
|
||||||
|
!result.dabBoundedHard ||
|
||||||
|
!result.dabBoundedSoft ||
|
||||||
|
!result.tintFollowsMask ||
|
||||||
|
!result.tintBounded
|
||||||
|
) {
|
||||||
|
console.error(
|
||||||
|
'render check FAILED: the brush mask does not follow the brush circle ' +
|
||||||
|
`(hard=${JSON.stringify(result.dabHard)}, rim=${JSON.stringify(result.dabRimSoft)}, ` +
|
||||||
|
`outsideHard=${JSON.stringify(result.dabOutsideHard)}, ` +
|
||||||
|
`outsideSoft=${JSON.stringify(result.dabOutsideSoft)}, ` +
|
||||||
|
`tint=${JSON.stringify(result.tintCore)}/${JSON.stringify(result.tintRim)}/` +
|
||||||
|
`${JSON.stringify(result.tintOutside)}).`,
|
||||||
|
);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
console.log(
|
||||||
|
'render check PASSED: proxy and sidecar share a row order and the clipping overlay names the channels.',
|
||||||
|
);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
let code = 1;
|
||||||
|
try {
|
||||||
|
code = await main();
|
||||||
|
} catch (err) {
|
||||||
|
console.error(`render check FAILED: ${err instanceof Error ? err.message : String(err)}`);
|
||||||
|
} finally {
|
||||||
|
await rm(DIR, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 }).catch(() => {
|
||||||
|
/* a stray Chrome profile is not worth failing the check over */
|
||||||
|
});
|
||||||
|
}
|
||||||
|
process.exit(code);
|
||||||
@@ -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;
|
||||||
|
|||||||
@@ -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,
|
||||||
|
|||||||
@@ -0,0 +1,144 @@
|
|||||||
|
/**
|
||||||
|
* Camera-native colour conversion for the raw pipeline.
|
||||||
|
*
|
||||||
|
* LibRaw can hand back the demosaiced frame before it applies any output
|
||||||
|
* colourspace (`outputColor: 0`). Those samples are the camera's own RGB,
|
||||||
|
* white-balanced and gamma encoded, which is what a camera profile needs: the
|
||||||
|
* camera-to-sRGB step becomes a matrix the editor can swap out without
|
||||||
|
* decoding the raw again.
|
||||||
|
*
|
||||||
|
* One white point is chosen for the whole frame from the *converted* pixels, so
|
||||||
|
* the JPEG proxy and the 16-bit sidecar share an exposure. LibRaw's own
|
||||||
|
* auto-bright is deliberately off: it measures each output path separately,
|
||||||
|
* which leaves the two outputs a third of a stop apart.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export function srgbToLinear(value) {
|
||||||
|
const v = value <= 0 ? 0 : value >= 1 ? 1 : value;
|
||||||
|
return v <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function linearToSrgb(value) {
|
||||||
|
const v = value <= 0 ? 0 : value >= 1 ? 1 : value;
|
||||||
|
return v <= 0.0031308 ? v * 12.92 : 1.055 * v ** (1 / 2.4) - 0.055;
|
||||||
|
}
|
||||||
|
|
||||||
|
let decodeTable = null;
|
||||||
|
let encodeTable = null;
|
||||||
|
|
||||||
|
/** 16-bit sample -> linear light, for the camera's own gamma encoding. */
|
||||||
|
function linearTable() {
|
||||||
|
if (!decodeTable) {
|
||||||
|
decodeTable = new Float32Array(65536);
|
||||||
|
for (let i = 0; i < 65536; i++) decodeTable[i] = srgbToLinear(i / 65535);
|
||||||
|
}
|
||||||
|
return decodeTable;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Linear light (indexed as a 16-bit fraction) -> 8-bit sRGB. */
|
||||||
|
function encodedTable() {
|
||||||
|
if (!encodeTable) {
|
||||||
|
encodeTable = new Uint8Array(65536);
|
||||||
|
for (let i = 0; i < 65536; i++) {
|
||||||
|
encodeTable[i] = Math.round(linearToSrgb(i / 65535) * 255);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return encodeTable;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Flattens the metadata's 4x4 `rgb_cam` into the 3x3 camera -> sRGB matrix. */
|
||||||
|
export function readRgbCam(meta) {
|
||||||
|
const raw = meta?.color_data?.rgb_cam;
|
||||||
|
if (!Array.isArray(raw) || raw.length < 3) return null;
|
||||||
|
const matrix = [];
|
||||||
|
for (let row = 0; row < 3; row++) {
|
||||||
|
const values = raw[row];
|
||||||
|
if (!Array.isArray(values) || values.length < 3) return null;
|
||||||
|
for (let col = 0; col < 3; col++) {
|
||||||
|
const value = Number(values[col]);
|
||||||
|
if (!Number.isFinite(value)) return null;
|
||||||
|
matrix.push(value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// A zero matrix would render the whole frame black; that is a metadata
|
||||||
|
// failure, not a look, so fall back to LibRaw's own conversion.
|
||||||
|
if (matrix.every((value) => Math.abs(value) < 1e-6)) return null;
|
||||||
|
return matrix;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Converts a camera-native 16-bit frame into the two buffers the editor needs,
|
||||||
|
* in place:
|
||||||
|
*
|
||||||
|
* - `rgb8` the sRGB proxy the JPEG is encoded from
|
||||||
|
* - `rgb16` the camera samples, white-point scaled, still camera native
|
||||||
|
*
|
||||||
|
* Returns the white point gain that was applied. The gain is baked into both
|
||||||
|
* buffers, so the client only has to apply the camera matrix; keeping it out of
|
||||||
|
* the sidecar would mean shipping a second 16-bit table for no benefit.
|
||||||
|
*/
|
||||||
|
export function cameraToProxy(rgb16, rgb8, matrix) {
|
||||||
|
const linear = linearTable();
|
||||||
|
const encode = encodedTable();
|
||||||
|
const count = Math.floor(rgb16.length / 3);
|
||||||
|
const m = matrix ?? [1, 0, 0, 0, 1, 0, 0, 0, 1];
|
||||||
|
|
||||||
|
// Pass 1: where does the fastest channel sit? Choosing the white point after
|
||||||
|
// the matrix keeps highlight clipping at about the same 1% LibRaw targets,
|
||||||
|
// instead of clipping whatever the matrix pushes past 1 on top of that.
|
||||||
|
const hist = new Uint32Array(65536);
|
||||||
|
for (let i = 0; i < count; i++) {
|
||||||
|
const s = i * 3;
|
||||||
|
const r = linear[rgb16[s]];
|
||||||
|
const g = linear[rgb16[s + 1]];
|
||||||
|
const b = linear[rgb16[s + 2]];
|
||||||
|
const max = Math.max(
|
||||||
|
m[0] * r + m[1] * g + m[2] * b,
|
||||||
|
m[3] * r + m[4] * g + m[5] * b,
|
||||||
|
m[6] * r + m[7] * g + m[8] * b,
|
||||||
|
);
|
||||||
|
const bin = max <= 0 ? 0 : max >= 1 ? 65535 : Math.round(max * 65535);
|
||||||
|
hist[bin]++;
|
||||||
|
}
|
||||||
|
let seen = 0;
|
||||||
|
let p99 = 65535;
|
||||||
|
const target = count * 0.99;
|
||||||
|
for (let i = 0; i < 65536; i++) {
|
||||||
|
seen += hist[i];
|
||||||
|
if (seen >= target) {
|
||||||
|
p99 = i;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Cap the gain: a nearly black frame is a real photograph, not a reason to
|
||||||
|
// multiply read noise by fifty.
|
||||||
|
const gain = Math.min(48, Math.max(0.25, 65535 / Math.max(1, p99)));
|
||||||
|
|
||||||
|
// Camera samples stay gamma encoded, so a shadow lift still has 16 bits of
|
||||||
|
// encoded detail to work from rather than 16 bits of linear light.
|
||||||
|
const camera = new Uint16Array(65536);
|
||||||
|
for (let i = 0; i < 65536; i++) {
|
||||||
|
camera[i] = Math.round(linearToSrgb(linear[i] * gain) * 65535);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pass 2: write both buffers.
|
||||||
|
for (let i = 0; i < count; i++) {
|
||||||
|
const s = i * 3;
|
||||||
|
const r = linear[rgb16[s]] * gain;
|
||||||
|
const g = linear[rgb16[s + 1]] * gain;
|
||||||
|
const b = linear[rgb16[s + 2]] * gain;
|
||||||
|
rgb8[s] = encode[clampIndex(m[0] * r + m[1] * g + m[2] * b)];
|
||||||
|
rgb8[s + 1] = encode[clampIndex(m[3] * r + m[4] * g + m[5] * b)];
|
||||||
|
rgb8[s + 2] = encode[clampIndex(m[6] * r + m[7] * g + m[8] * b)];
|
||||||
|
rgb16[s] = camera[rgb16[s]];
|
||||||
|
rgb16[s + 1] = camera[rgb16[s + 1]];
|
||||||
|
rgb16[s + 2] = camera[rgb16[s + 2]];
|
||||||
|
}
|
||||||
|
return gain;
|
||||||
|
}
|
||||||
|
|
||||||
|
function clampIndex(value) {
|
||||||
|
if (!(value > 0)) return 0;
|
||||||
|
if (value >= 1) return 65535;
|
||||||
|
return Math.round(value * 65535);
|
||||||
|
}
|
||||||
@@ -27,12 +27,29 @@ export const HOST = process.env.HOST || '0.0.0.0';
|
|||||||
/** Shared invite code required to register after the first account exists. */
|
/** Shared invite code required to register after the first account exists. */
|
||||||
export const INVITE = setting('INVITE');
|
export const INVITE = setting('INVITE');
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Single-user desktop mode, set by the Windows launcher (LUMINARY_LOCAL=1).
|
||||||
|
* The server creates one admin account and treats an unauthenticated request as
|
||||||
|
* that account, so a personal install never shows a signup or sign-in screen.
|
||||||
|
* Only safe on loopback, which is where the launcher binds; the server warns if
|
||||||
|
* it is enabled with a reachable HOST.
|
||||||
|
*/
|
||||||
|
export const LOCAL_MODE = setting('LOCAL') === '1';
|
||||||
|
export const LOCAL_EMAIL = setting('LOCAL_EMAIL', 'local@luminary');
|
||||||
|
|
||||||
/** Base URL of the dashboard this editor is bridged to, e.g. http://hub:3000. */
|
/** Base URL of the dashboard this editor is bridged to, e.g. http://hub:3000. */
|
||||||
export const GLENLOCH_URL = (process.env.GLENLOCH_URL || '').replace(/\/+$/, '');
|
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'));
|
||||||
|
|
||||||
@@ -68,6 +85,13 @@ export const SMTP_FROM = setting('SMTP_FROM', SMTP_USER);
|
|||||||
/** Long edge used for the editable proxy of raw files. */
|
/** Long edge used for the editable proxy of raw files. */
|
||||||
export const RAW_PREVIEW_EDGE = Number(setting('RAW_EDGE', '6000'));
|
export const RAW_PREVIEW_EDGE = Number(setting('RAW_EDGE', '6000'));
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Also store the 16-bit samples LibRaw decoded as a sidecar next to the JPEG
|
||||||
|
* proxy. It costs roughly 25x the JPEG in disk and download, but it is the only
|
||||||
|
* way the editor can grade from more than 256 levels per channel.
|
||||||
|
*/
|
||||||
|
export const RAW_16BIT = setting('16BIT', '1') !== '0';
|
||||||
|
|
||||||
export const SESSION_DAYS = 30;
|
export const SESSION_DAYS = 30;
|
||||||
|
|
||||||
/** How many raws decode at once. One core is left for the HTTP server. */
|
/** How many raws decode at once. One core is left for the HTTP server. */
|
||||||
|
|||||||
@@ -89,6 +89,18 @@ db.exec(`
|
|||||||
|
|
||||||
CREATE INDEX IF NOT EXISTS gallery_reviews_token ON gallery_reviews(token);
|
CREATE INDEX IF NOT EXISTS gallery_reviews_token ON gallery_reviews(token);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS gallery_settings (
|
||||||
|
token TEXT PRIMARY KEY,
|
||||||
|
password_hash TEXT NOT NULL DEFAULT '',
|
||||||
|
password_salt TEXT NOT NULL DEFAULT '',
|
||||||
|
expires_at INTEGER,
|
||||||
|
watermark TEXT NOT NULL DEFAULT '',
|
||||||
|
allow_downloads INTEGER NOT NULL DEFAULT 1,
|
||||||
|
download_cap INTEGER NOT NULL DEFAULT 0,
|
||||||
|
download_count INTEGER NOT NULL DEFAULT 0,
|
||||||
|
updated_at INTEGER NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS invites (
|
CREATE TABLE IF NOT EXISTS invites (
|
||||||
token TEXT PRIMARY KEY,
|
token TEXT PRIMARY KEY,
|
||||||
email TEXT NOT NULL DEFAULT '',
|
email TEXT NOT NULL DEFAULT '',
|
||||||
@@ -114,6 +126,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),
|
||||||
@@ -122,6 +204,25 @@ db.exec(`
|
|||||||
prune_notified_at INTEGER,
|
prune_notified_at INTEGER,
|
||||||
last_quota_email_at INTEGER
|
last_quota_email_at INTEGER
|
||||||
);
|
);
|
||||||
|
|
||||||
|
/* Lens calibrations measured by the team, alongside the bundled database. */
|
||||||
|
CREATE TABLE IF NOT EXISTS lens_profiles (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
maker TEXT NOT NULL,
|
||||||
|
model TEXT NOT NULL,
|
||||||
|
mount TEXT NOT NULL DEFAULT '',
|
||||||
|
crop REAL NOT NULL DEFAULT 1,
|
||||||
|
aspect REAL NOT NULL DEFAULT 0,
|
||||||
|
center_x REAL NOT NULL DEFAULT 0,
|
||||||
|
center_y REAL NOT NULL DEFAULT 0,
|
||||||
|
notes TEXT NOT NULL DEFAULT '',
|
||||||
|
data TEXT NOT NULL,
|
||||||
|
created_by TEXT NOT NULL DEFAULT '',
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
updated_at INTEGER NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS lens_profiles_updated ON lens_profiles(updated_at);
|
||||||
`);
|
`);
|
||||||
|
|
||||||
/* Databases created before account disabling existed get the column in place. */
|
/* Databases created before account disabling existed get the column in place. */
|
||||||
@@ -162,6 +263,74 @@ 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'");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Applying a lens profile used to enable its vignetting correction, and that
|
||||||
|
* flat-field gain over-exposed the edges. The correction is opt-in now, so the
|
||||||
|
* flag older edits stored is cleared once, here, before anything reads the
|
||||||
|
* catalogue. Matching on the JSON text keeps the scan to the few rows that ever
|
||||||
|
* carried it, and the rows it rewrites no longer match, so it is idempotent.
|
||||||
|
*/
|
||||||
|
const legacyVignetting = db
|
||||||
|
.prepare(`SELECT id, data FROM photos WHERE instr(data, '"vignetting":true') > 0`)
|
||||||
|
.all();
|
||||||
|
if (legacyVignetting.length) {
|
||||||
|
const updateData = db.prepare('UPDATE photos SET data = ?, updated_at = ? WHERE id = ?');
|
||||||
|
const clear = (edits) => {
|
||||||
|
const lens = edits && edits.lens;
|
||||||
|
if (!lens || !lens.corrections || lens.corrections.vignetting !== true) return edits;
|
||||||
|
return { ...edits, lens: { ...lens, corrections: { ...lens.corrections, vignetting: false } } };
|
||||||
|
};
|
||||||
|
let cleared = 0;
|
||||||
|
for (const row of legacyVignetting) {
|
||||||
|
let record;
|
||||||
|
try {
|
||||||
|
record = JSON.parse(row.data);
|
||||||
|
} catch {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!record || typeof record !== 'object') continue;
|
||||||
|
let changed = false;
|
||||||
|
const strip = (edits) => {
|
||||||
|
const next = clear(edits);
|
||||||
|
if (next !== edits) changed = true;
|
||||||
|
return next;
|
||||||
|
};
|
||||||
|
record.edits = strip(record.edits);
|
||||||
|
if (Array.isArray(record.snapshots)) {
|
||||||
|
record.snapshots = record.snapshots.map((snap) =>
|
||||||
|
snap && snap.edits ? { ...snap, edits: strip(snap.edits) } : snap,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (Array.isArray(record.history)) {
|
||||||
|
record.history = record.history.map((entry) =>
|
||||||
|
entry && entry.edits ? { ...entry, edits: strip(entry.edits) } : entry,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (!changed) continue;
|
||||||
|
updateData.run(JSON.stringify(record), Date.now(), row.id);
|
||||||
|
cleared += 1;
|
||||||
|
}
|
||||||
|
if (cleared) console.log(`lens vignetting: cleared the stored corner gain on ${cleared} photo(s)`);
|
||||||
|
}
|
||||||
|
|
||||||
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 +424,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 (?, ?, ?, ?, ?, ?)',
|
||||||
@@ -335,6 +613,28 @@ const q = {
|
|||||||
kvSet: db.prepare(
|
kvSet: db.prepare(
|
||||||
'INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value',
|
'INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value',
|
||||||
),
|
),
|
||||||
|
|
||||||
|
allLensProfiles: db.prepare(
|
||||||
|
'SELECT * FROM lens_profiles ORDER BY maker COLLATE NOCASE ASC, model COLLATE NOCASE ASC',
|
||||||
|
),
|
||||||
|
lensProfile: db.prepare('SELECT * FROM lens_profiles WHERE id = ?'),
|
||||||
|
upsertLensProfile: db.prepare(`
|
||||||
|
INSERT INTO lens_profiles
|
||||||
|
(id, maker, model, mount, crop, aspect, center_x, center_y, notes, data, created_by, created_at, updated_at)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
ON CONFLICT(id) DO UPDATE SET
|
||||||
|
maker = excluded.maker,
|
||||||
|
model = excluded.model,
|
||||||
|
mount = excluded.mount,
|
||||||
|
crop = excluded.crop,
|
||||||
|
aspect = excluded.aspect,
|
||||||
|
center_x = excluded.center_x,
|
||||||
|
center_y = excluded.center_y,
|
||||||
|
notes = excluded.notes,
|
||||||
|
data = excluded.data,
|
||||||
|
updated_at = excluded.updated_at
|
||||||
|
`),
|
||||||
|
deleteLensProfile: db.prepare('DELETE FROM lens_profiles WHERE id = ?'),
|
||||||
};
|
};
|
||||||
|
|
||||||
function parse(json) {
|
function parse(json) {
|
||||||
@@ -361,6 +661,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) {
|
||||||
@@ -408,6 +710,71 @@ export function picksByOwner(ownerId) {
|
|||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const gallerySettingsStmt = db.prepare('SELECT * FROM gallery_settings WHERE token = ?');
|
||||||
|
const upsertGallerySettings = db.prepare(`
|
||||||
|
INSERT INTO gallery_settings
|
||||||
|
(token, password_hash, password_salt, expires_at, watermark, allow_downloads, download_cap, download_count, updated_at)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
ON CONFLICT(token) DO UPDATE SET
|
||||||
|
password_hash = excluded.password_hash,
|
||||||
|
password_salt = excluded.password_salt,
|
||||||
|
expires_at = excluded.expires_at,
|
||||||
|
watermark = excluded.watermark,
|
||||||
|
allow_downloads = excluded.allow_downloads,
|
||||||
|
download_cap = excluded.download_cap,
|
||||||
|
updated_at = excluded.updated_at
|
||||||
|
`);
|
||||||
|
const deleteGallerySettings = db.prepare('DELETE FROM gallery_settings WHERE token = ?');
|
||||||
|
const bumpGalleryDownload = db.prepare(
|
||||||
|
'UPDATE gallery_settings SET download_count = download_count + 1 WHERE token = ?',
|
||||||
|
);
|
||||||
|
const readGalleryDownloads = db.prepare(
|
||||||
|
'SELECT download_count FROM gallery_settings WHERE token = ?',
|
||||||
|
);
|
||||||
|
|
||||||
|
/** Access rules for a public proofing link; defaults when none were saved. */
|
||||||
|
export function gallerySettingsFor(token) {
|
||||||
|
const row = gallerySettingsStmt.get(token);
|
||||||
|
return {
|
||||||
|
passwordHash: row?.password_hash ?? '',
|
||||||
|
passwordSalt: row?.password_salt ?? '',
|
||||||
|
expiresAt: row?.expires_at ?? null,
|
||||||
|
watermark: row?.watermark ?? '',
|
||||||
|
allowDownloads: row ? Boolean(row.allow_downloads) : true,
|
||||||
|
downloadCap: row?.download_cap ?? 0,
|
||||||
|
downloadCount: row?.download_count ?? 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The download counter is deliberately preserved across settings edits: an
|
||||||
|
* owner tightening or loosening a cap must not hand out a fresh allowance.
|
||||||
|
*/
|
||||||
|
export function saveGallerySettings(token, settings) {
|
||||||
|
upsertGallerySettings.run(
|
||||||
|
token,
|
||||||
|
settings.passwordHash ?? '',
|
||||||
|
settings.passwordSalt ?? '',
|
||||||
|
settings.expiresAt ?? null,
|
||||||
|
settings.watermark ?? '',
|
||||||
|
settings.allowDownloads === false ? 0 : 1,
|
||||||
|
Math.max(0, Math.round(settings.downloadCap ?? 0)),
|
||||||
|
0,
|
||||||
|
Date.now(),
|
||||||
|
);
|
||||||
|
return gallerySettingsFor(token);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function clearGallerySettings(token) {
|
||||||
|
deleteGallerySettings.run(token);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Counts a gallery download and reports the new total, or 0 when uncapped. */
|
||||||
|
export function noteGalleryDownload(token) {
|
||||||
|
bumpGalleryDownload.run(token);
|
||||||
|
return readGalleryDownloads.get(token)?.download_count ?? 0;
|
||||||
|
}
|
||||||
|
|
||||||
export function galleryPick(token, photoId, clientId, clientName, picked) {
|
export function galleryPick(token, photoId, clientId, clientName, picked) {
|
||||||
if (!picked) {
|
if (!picked) {
|
||||||
q.deletePick.run(token, photoId, clientId);
|
q.deletePick.run(token, photoId, clientId);
|
||||||
@@ -479,6 +846,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 +1112,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() {
|
||||||
@@ -590,3 +1204,52 @@ export const kv = {
|
|||||||
},
|
},
|
||||||
set: (key, value) => q.kvSet.run(key, JSON.stringify(value)),
|
set: (key, value) => q.kvSet.run(key, JSON.stringify(value)),
|
||||||
};
|
};
|
||||||
|
|
||||||
|
function lensProfileFromRow(row) {
|
||||||
|
const data = parse(row.data) ?? {};
|
||||||
|
return {
|
||||||
|
id: row.id,
|
||||||
|
maker: row.maker,
|
||||||
|
model: row.model,
|
||||||
|
mount: row.mount,
|
||||||
|
crop: Number(row.crop),
|
||||||
|
aspect: Number(row.aspect),
|
||||||
|
centerX: Number(row.center_x),
|
||||||
|
centerY: Number(row.center_y),
|
||||||
|
notes: row.notes,
|
||||||
|
d: Array.isArray(data.d) ? data.d : [],
|
||||||
|
t: Array.isArray(data.t) ? data.t : [],
|
||||||
|
v: Array.isArray(data.v) ? data.v : [],
|
||||||
|
createdBy: row.created_by,
|
||||||
|
createdAt: row.created_at,
|
||||||
|
updatedAt: row.updated_at,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Team-measured calibrations, shared by every signed-in member. */
|
||||||
|
export const lensProfiles = {
|
||||||
|
list: () => q.allLensProfiles.all().map(lensProfileFromRow),
|
||||||
|
get: (id) => {
|
||||||
|
const row = q.lensProfile.get(String(id));
|
||||||
|
return row ? lensProfileFromRow(row) : null;
|
||||||
|
},
|
||||||
|
save: (record) => {
|
||||||
|
q.upsertLensProfile.run(
|
||||||
|
record.id,
|
||||||
|
record.maker,
|
||||||
|
record.model,
|
||||||
|
record.mount ?? '',
|
||||||
|
Number(record.crop ?? 1),
|
||||||
|
Number(record.aspect ?? 0),
|
||||||
|
Number(record.centerX ?? 0),
|
||||||
|
Number(record.centerY ?? 0),
|
||||||
|
record.notes ?? '',
|
||||||
|
JSON.stringify({ d: record.d ?? [], t: record.t ?? [], v: record.v ?? [] }),
|
||||||
|
record.createdBy ?? '',
|
||||||
|
record.createdAt ?? Date.now(),
|
||||||
|
record.updatedAt ?? Date.now(),
|
||||||
|
);
|
||||||
|
return lensProfiles.get(record.id);
|
||||||
|
},
|
||||||
|
remove: (id) => q.deleteLensProfile.run(String(id)).changes > 0,
|
||||||
|
};
|
||||||
|
|||||||
@@ -68,7 +68,156 @@ export function encodePng(rgb, width, height) {
|
|||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Encode an interleaved RGB byte buffer as JPEG (sharp) or PNG (fallback). */
|
/**
|
||||||
|
* Box-average a 16-bit RGB image down to the proxy size. sharp's raw pipeline
|
||||||
|
* does not round-trip 16-bit samples faithfully, and this keeps the sidecar
|
||||||
|
* pixel-aligned with the JPEG that was encoded by a different library.
|
||||||
|
*/
|
||||||
|
export function resizeRgb16(rgb16, width, height, tw, th) {
|
||||||
|
if (width === tw && height === th) return rgb16;
|
||||||
|
const out = new Uint16Array(tw * th * 3);
|
||||||
|
const fx = width / tw;
|
||||||
|
const fy = height / th;
|
||||||
|
for (let y = 0; y < th; y++) {
|
||||||
|
const y0 = Math.floor(y * fy);
|
||||||
|
const y1 = Math.min(height, Math.max(y0 + 1, Math.ceil((y + 1) * fy)));
|
||||||
|
for (let x = 0; x < tw; x++) {
|
||||||
|
const x0 = Math.floor(x * fx);
|
||||||
|
const x1 = Math.min(width, Math.max(x0 + 1, Math.ceil((x + 1) * fx)));
|
||||||
|
let r = 0;
|
||||||
|
let g = 0;
|
||||||
|
let b = 0;
|
||||||
|
let n = 0;
|
||||||
|
for (let sy = y0; sy < y1; sy++) {
|
||||||
|
let at = (sy * width + x0) * 3;
|
||||||
|
for (let sx = x0; sx < x1; sx++) {
|
||||||
|
r += rgb16[at];
|
||||||
|
g += rgb16[at + 1];
|
||||||
|
b += rgb16[at + 2];
|
||||||
|
at += 3;
|
||||||
|
n += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const d = (y * tw + x) * 3;
|
||||||
|
out[d] = Math.round(r / n);
|
||||||
|
out[d + 1] = Math.round(g / n);
|
||||||
|
out[d + 2] = Math.round(b / n);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 16-bit RGB PNG (colour type 2, no interlacing, Sub-filtered rows). The editor
|
||||||
|
* inflates this in the browser and uploads it as a half-float texture, so it has
|
||||||
|
* to be a standard PNG rather than a private container. Sub filtering subtracts
|
||||||
|
* each byte from the pixel six bytes to its left, which compresses photographic
|
||||||
|
* rows far better than storing the samples raw.
|
||||||
|
*
|
||||||
|
* `matrix` is the camera-to-sRGB matrix (9 numbers, row major). It is written to
|
||||||
|
* a tEXt chunk because the sidecar holds camera-native samples: without it the
|
||||||
|
* client would have to guess the conversion, and a self-describing sidecar also
|
||||||
|
* keeps working for imports that predate a catalogue migration.
|
||||||
|
*/
|
||||||
|
export function encodePng16(rgb16, width, height, matrix = null) {
|
||||||
|
const stride = width * 6;
|
||||||
|
const raw = Buffer.alloc((stride + 1) * height);
|
||||||
|
const row = Buffer.alloc(stride);
|
||||||
|
for (let y = 0; y < height; y++) {
|
||||||
|
let at = y * width * 3;
|
||||||
|
for (let i = 0; i < stride; i += 2) {
|
||||||
|
row.writeUInt16BE(rgb16[at++] & 0xffff, i);
|
||||||
|
}
|
||||||
|
const base = y * (stride + 1);
|
||||||
|
raw[base] = 1;
|
||||||
|
for (let i = 0; i < stride; i++) {
|
||||||
|
raw[base + 1 + i] = (row[i] - (i >= 6 ? row[i - 6] : 0)) & 0xff;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const idat = zlib.deflateSync(raw, { level: 6 });
|
||||||
|
const ihdr = Buffer.alloc(13);
|
||||||
|
ihdr.writeUInt32BE(width, 0);
|
||||||
|
ihdr.writeUInt32BE(height, 4);
|
||||||
|
ihdr[8] = 16;
|
||||||
|
ihdr[9] = 2;
|
||||||
|
ihdr[10] = 0;
|
||||||
|
ihdr[11] = 0;
|
||||||
|
ihdr[12] = 0;
|
||||||
|
return Buffer.concat([
|
||||||
|
Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
|
||||||
|
chunk('IHDR', ihdr),
|
||||||
|
...(matrix && matrix.length === 9
|
||||||
|
? [
|
||||||
|
chunk(
|
||||||
|
'tEXt',
|
||||||
|
Buffer.from(
|
||||||
|
`rgbCam\0${matrix.map((value) => Number(value).toFixed(8)).join(',')}`,
|
||||||
|
'latin1',
|
||||||
|
),
|
||||||
|
),
|
||||||
|
]
|
||||||
|
: []),
|
||||||
|
chunk('IDAT', idat),
|
||||||
|
chunk('IEND', Buffer.alloc(0)),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
/** The camera matrix carried in a 16-bit sidecar's `rgbCam` tEXt chunk. */
|
||||||
|
export function png16Matrix(png) {
|
||||||
|
const needle = Buffer.from('rgbCam\0', 'latin1');
|
||||||
|
const at = png.indexOf(needle);
|
||||||
|
if (at < 0) return null;
|
||||||
|
const start = at + needle.length;
|
||||||
|
// The text runs to the end of the tEXt chunk, and the chunk's CRC is binary
|
||||||
|
// and may contain a NUL. Stop at the first byte that cannot be part of the
|
||||||
|
// comma-separated number list instead of searching for a terminator.
|
||||||
|
let end = start;
|
||||||
|
while (end < png.length) {
|
||||||
|
const code = png[end];
|
||||||
|
const numeric =
|
||||||
|
(code >= 0x30 && code <= 0x39) || // 0-9
|
||||||
|
code === 0x2e || // .
|
||||||
|
code === 0x2c || // ,
|
||||||
|
code === 0x2d || // -
|
||||||
|
code === 0x2b || // +
|
||||||
|
code === 0x65 || // e
|
||||||
|
code === 0x45; // E
|
||||||
|
if (!numeric) break;
|
||||||
|
end++;
|
||||||
|
}
|
||||||
|
const values = png.toString('latin1', start, end).split(',').map(Number);
|
||||||
|
return values.length === 9 && values.every(Number.isFinite) ? values : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A camera-native grid thumbnail, resized from the 16-bit sidecar with sharp's
|
||||||
|
* 16-bit path. The grid normally renders the sRGB JPEG, whose body matrix is
|
||||||
|
* already baked in; this gives the client camera samples small enough to fetch
|
||||||
|
* per tile, so a per-photo DCP profile shows everywhere the photo does. The
|
||||||
|
* `rgbCam` tag is rewritten so the client still knows how to convert them.
|
||||||
|
*/
|
||||||
|
export async function cameraThumb16(png16, width, height, matrix = null) {
|
||||||
|
const sharp = await loadSharp();
|
||||||
|
if (!sharp || width < 1 || height < 1) return null;
|
||||||
|
try {
|
||||||
|
const { data, info } = await sharp(png16)
|
||||||
|
.resize({ width, height, fit: 'fill' })
|
||||||
|
.raw({ depth: 'ushort' })
|
||||||
|
.toBuffer({ resolveWithObject: true });
|
||||||
|
if (info.channels !== 3 || info.depth !== 'ushort') return null;
|
||||||
|
// Copy through a fresh buffer: a raw output offset is not guaranteed to be
|
||||||
|
// 16-bit aligned, and Uint16Array refuses an odd byteOffset.
|
||||||
|
const samples = data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength);
|
||||||
|
return encodePng16(
|
||||||
|
new Uint16Array(samples),
|
||||||
|
info.width,
|
||||||
|
info.height,
|
||||||
|
matrix ?? png16Matrix(png16),
|
||||||
|
);
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export async function encodeRgb(rgb, width, height, quality = 92, maxEdge = 0) {
|
export async function encodeRgb(rgb, width, height, quality = 92, maxEdge = 0) {
|
||||||
const sharp = await loadSharp();
|
const sharp = await loadSharp();
|
||||||
if (!sharp) {
|
if (!sharp) {
|
||||||
|
|||||||
@@ -0,0 +1,95 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import { cameraThumb16, encodePng16, png16Matrix, resizeRgb16 } from './imaging.mjs';
|
||||||
|
|
||||||
|
/** A sample camera-to-sRGB matrix, in the shape a DCP derivation produces. */
|
||||||
|
const MATRIX = [
|
||||||
|
1.66943598, -0.4847292, -0.18470675, -0.00096075, 1.25268972, -0.25172901, 0.04713935,
|
||||||
|
-0.30006605, 1.25292671,
|
||||||
|
];
|
||||||
|
|
||||||
|
/** Flat 16-bit RGB samples, row major. */
|
||||||
|
function flat16(width, height, rgb) {
|
||||||
|
const out = new Uint16Array(width * height * 3);
|
||||||
|
for (let i = 0; i < out.length; i += 3) {
|
||||||
|
out[i] = rgb[0];
|
||||||
|
out[i + 1] = rgb[1];
|
||||||
|
out[i + 2] = rgb[2];
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('png16Matrix', () => {
|
||||||
|
it('reads the nine numbers back out of the tEXt chunk', () => {
|
||||||
|
const png = encodePng16(flat16(2, 1, [1000, 2000, 3000]), 2, 1, MATRIX);
|
||||||
|
const parsed = png16Matrix(png);
|
||||||
|
expect(parsed).not.toBeNull();
|
||||||
|
expect(parsed).toHaveLength(9);
|
||||||
|
parsed.forEach((value, index) => expect(value).toBeCloseTo(MATRIX[index], 8));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns null when the tag is absent or short', () => {
|
||||||
|
expect(png16Matrix(encodePng16(flat16(1, 1, [0, 0, 0]), 1, 1))).toBeNull();
|
||||||
|
const short = Buffer.concat([Buffer.from('rgbCam\0', 'latin1'), Buffer.from('1,2,3,4')]);
|
||||||
|
expect(png16Matrix(short)).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('stops at the end of the tag instead of reading the chunk CRC', () => {
|
||||||
|
// The first parser scanned for the next NUL, so a CRC with no zero byte ran
|
||||||
|
// into the following chunk header and every matrix came back as NaN.
|
||||||
|
const text = `rgbCam\0${MATRIX.map((value) => value.toFixed(8)).join(',')}`;
|
||||||
|
const png = Buffer.concat([
|
||||||
|
Buffer.from(text, 'latin1'),
|
||||||
|
Buffer.from([0x31, 0x32, 0x00, 0x33]),
|
||||||
|
]);
|
||||||
|
const parsed = png16Matrix(png);
|
||||||
|
expect(parsed).toHaveLength(9);
|
||||||
|
parsed.forEach((value, index) => expect(value).toBeCloseTo(MATRIX[index], 8));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('resizeRgb16', () => {
|
||||||
|
it('box-averages samples when shrinking', () => {
|
||||||
|
const source = new Uint16Array([
|
||||||
|
1000, 1000, 1000, 1000, 1000, 1000, 3000, 3000, 3000, 3000, 3000, 3000,
|
||||||
|
]);
|
||||||
|
expect(Array.from(resizeRgb16(source, 4, 1, 2, 1))).toEqual([
|
||||||
|
1000, 1000, 1000, 3000, 3000, 3000,
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('leaves an already-sized image untouched', () => {
|
||||||
|
const source = new Uint16Array([1, 2, 3, 4, 5, 6]);
|
||||||
|
expect(resizeRgb16(source, 2, 1, 2, 1)).toBe(source);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('cameraThumb16', () => {
|
||||||
|
it('writes a 16-bit RGB thumbnail at the requested grid size', async () => {
|
||||||
|
const source = encodePng16(flat16(4, 2, [2000, 4000, 6000]), 4, 2, MATRIX);
|
||||||
|
const out = await cameraThumb16(source, 3, 2);
|
||||||
|
expect(out).not.toBeNull();
|
||||||
|
// PNG signature, then IHDR: length at 8, type at 12, data from 16.
|
||||||
|
expect(out.readUInt32BE(16)).toBe(3);
|
||||||
|
expect(out.readUInt32BE(20)).toBe(2);
|
||||||
|
expect(out[24]).toBe(16); // bit depth
|
||||||
|
expect(out[25]).toBe(2); // colour type RGB
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps the camera matrix so the client can convert the samples', async () => {
|
||||||
|
const source = encodePng16(flat16(4, 2, [1000, 2000, 3000]), 4, 2, MATRIX);
|
||||||
|
const out = await cameraThumb16(source, 2, 1);
|
||||||
|
const parsed = png16Matrix(out);
|
||||||
|
expect(parsed).toHaveLength(9);
|
||||||
|
parsed.forEach((value, index) => expect(value).toBeCloseTo(MATRIX[index], 8));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('falls back to the matrix stored in the source sidecar', async () => {
|
||||||
|
const source = encodePng16(flat16(2, 2, [500, 600, 700]), 2, 2, MATRIX);
|
||||||
|
const out = await cameraThumb16(source, 1, 1);
|
||||||
|
expect(png16Matrix(out)).toHaveLength(9);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('declines input sharp cannot decode', async () => {
|
||||||
|
expect(await cameraThumb16(Buffer.alloc(64), 2, 2)).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
/**
|
||||||
|
* Validation for team-measured lens calibrations.
|
||||||
|
*
|
||||||
|
* A profile carries the same sample rows the bundled Lensfun database uses, so
|
||||||
|
* the correction engine can read both without a second code path:
|
||||||
|
*
|
||||||
|
* d: [focal, model, a, b, c, realFocal] distortion
|
||||||
|
* t: [focal, model, br, cr, vr, bb, cb, vb] lateral chromatic aberration
|
||||||
|
* v: [focal, aperture, distance, k1, k2, k3] vignetting
|
||||||
|
*
|
||||||
|
* Coefficients are entered as measured: the engine rescales them by focal and
|
||||||
|
* sensor size exactly as it does for the bundled data.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const MAX_DISTORTION = 60;
|
||||||
|
const MAX_TCA = 60;
|
||||||
|
const MAX_VIGNETTING = 120;
|
||||||
|
const MAX_COEFFICIENT = 100;
|
||||||
|
|
||||||
|
const DISTORTION_MODELS = [0, 1, 2]; // poly3, poly5, ptlens
|
||||||
|
const TCA_MODELS = [0, 1]; // poly3, linear
|
||||||
|
|
||||||
|
const finite = (value) => typeof value === 'number' && Number.isFinite(value);
|
||||||
|
const clampText = (value, max) =>
|
||||||
|
typeof value === 'string' ? value.trim().replace(/\s+/g, ' ').slice(0, max) : '';
|
||||||
|
|
||||||
|
function row(values, count) {
|
||||||
|
if (!Array.isArray(values) || values.length !== count) return null;
|
||||||
|
const numbers = values.map((value) => (typeof value === 'number' ? value : Number(value)));
|
||||||
|
return numbers.every(finite) ? numbers : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function distortionRows(input) {
|
||||||
|
if (input === undefined) return { rows: [] };
|
||||||
|
if (!Array.isArray(input)) return { error: 'Distortion samples must be a list' };
|
||||||
|
if (input.length > MAX_DISTORTION) return { error: `At most ${MAX_DISTORTION} distortion samples` };
|
||||||
|
const rows = [];
|
||||||
|
for (const entry of input) {
|
||||||
|
const values = row(entry, 6);
|
||||||
|
if (!values) return { error: 'Each distortion sample needs 6 numbers' };
|
||||||
|
const [focal, model, a, b, c, realFocal] = values;
|
||||||
|
if (!(focal > 0)) return { error: 'Distortion samples need a focal length above zero' };
|
||||||
|
if (!DISTORTION_MODELS.includes(model)) return { error: 'Unknown distortion model' };
|
||||||
|
if ([a, b, c].some((value) => Math.abs(value) > MAX_COEFFICIENT)) {
|
||||||
|
return { error: 'Distortion coefficients look out of range' };
|
||||||
|
}
|
||||||
|
if (realFocal < 0 || realFocal > 2000) return { error: 'Real focal length looks out of range' };
|
||||||
|
rows.push([focal, model, a, b, c, realFocal]);
|
||||||
|
}
|
||||||
|
return { rows };
|
||||||
|
}
|
||||||
|
|
||||||
|
function tcaRows(input) {
|
||||||
|
if (input === undefined) return { rows: [] };
|
||||||
|
if (!Array.isArray(input)) return { error: 'Chromatic aberration samples must be a list' };
|
||||||
|
if (input.length > MAX_TCA) return { error: `At most ${MAX_TCA} chromatic aberration samples` };
|
||||||
|
const rows = [];
|
||||||
|
for (const entry of input) {
|
||||||
|
const values = row(entry, 8);
|
||||||
|
if (!values) return { error: 'Each chromatic aberration sample needs 8 numbers' };
|
||||||
|
const [focal, model] = values;
|
||||||
|
if (!(focal > 0)) return { error: 'Chromatic aberration samples need a focal length above zero' };
|
||||||
|
if (!TCA_MODELS.includes(model)) return { error: 'Unknown chromatic aberration model' };
|
||||||
|
if (values.some((value) => Math.abs(value) > MAX_COEFFICIENT)) {
|
||||||
|
return { error: 'Chromatic aberration coefficients look out of range' };
|
||||||
|
}
|
||||||
|
rows.push(values);
|
||||||
|
}
|
||||||
|
return { rows };
|
||||||
|
}
|
||||||
|
|
||||||
|
function vignettingRows(input) {
|
||||||
|
if (input === undefined) return { rows: [] };
|
||||||
|
if (!Array.isArray(input)) return { error: 'Vignetting samples must be a list' };
|
||||||
|
if (input.length > MAX_VIGNETTING) return { error: `At most ${MAX_VIGNETTING} vignetting samples` };
|
||||||
|
const rows = [];
|
||||||
|
for (const entry of input) {
|
||||||
|
const values = row(entry, 6);
|
||||||
|
if (!values) return { error: 'Each vignetting sample needs 6 numbers' };
|
||||||
|
const [focal, aperture, distance, k1, k2, k3] = values;
|
||||||
|
if (!(focal > 0)) return { error: 'Vignetting samples need a focal length above zero' };
|
||||||
|
if (!(aperture > 0)) return { error: 'Vignetting samples need an aperture above zero' };
|
||||||
|
if (!(distance > 0)) return { error: 'Vignetting samples need a focus distance above zero' };
|
||||||
|
if ([k1, k2, k3].some((value) => Math.abs(value) > MAX_COEFFICIENT)) {
|
||||||
|
return { error: 'Vignetting coefficients look out of range' };
|
||||||
|
}
|
||||||
|
rows.push(values);
|
||||||
|
}
|
||||||
|
return { rows };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Returns `{ value }` for a valid body, or `{ error }` describing the first problem. */
|
||||||
|
export function parseCalibration(body) {
|
||||||
|
if (!body || typeof body !== 'object') return { error: 'Expected a lens profile' };
|
||||||
|
const maker = clampText(body.maker, 80);
|
||||||
|
const model = clampText(body.model, 120);
|
||||||
|
if (!maker) return { error: 'Lens maker is required' };
|
||||||
|
if (!model) return { error: 'Lens model is required' };
|
||||||
|
|
||||||
|
const crop = Number(body.crop);
|
||||||
|
if (!(crop >= 0.5 && crop <= 3)) return { error: 'Crop factor must be between 0.5 and 3' };
|
||||||
|
|
||||||
|
const aspect = body.aspect === undefined || body.aspect === '' ? 0 : Number(body.aspect);
|
||||||
|
if (!(aspect >= 0 && aspect <= 4)) return { error: 'Aspect ratio must be between 0 and 4' };
|
||||||
|
|
||||||
|
const centerX = body.centerX === undefined || body.centerX === '' ? 0 : Number(body.centerX);
|
||||||
|
const centerY = body.centerY === undefined || body.centerY === '' ? 0 : Number(body.centerY);
|
||||||
|
if (Math.abs(centerX) > 0.5 || Math.abs(centerY) > 0.5) {
|
||||||
|
return { error: 'Lens centre offset must be between -0.5 and 0.5' };
|
||||||
|
}
|
||||||
|
|
||||||
|
const distortion = distortionRows(body.d);
|
||||||
|
if (distortion.error) return { error: distortion.error };
|
||||||
|
const tca = tcaRows(body.t);
|
||||||
|
if (tca.error) return { error: tca.error };
|
||||||
|
const vignetting = vignettingRows(body.v);
|
||||||
|
if (vignetting.error) return { error: vignetting.error };
|
||||||
|
|
||||||
|
if (!distortion.rows.length && !tca.rows.length && !vignetting.rows.length) {
|
||||||
|
return { error: 'Add at least one distortion, chromatic aberration or vignetting sample' };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
value: {
|
||||||
|
maker,
|
||||||
|
model,
|
||||||
|
mount: clampText(body.mount, 40),
|
||||||
|
crop,
|
||||||
|
aspect,
|
||||||
|
centerX,
|
||||||
|
centerY,
|
||||||
|
notes: clampText(body.notes, 500),
|
||||||
|
d: distortion.rows,
|
||||||
|
t: tca.rows,
|
||||||
|
v: vignetting.rows,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import { parseCalibration } from './lensCalibration.mjs';
|
||||||
|
|
||||||
|
const base = {
|
||||||
|
maker: 'Tamron',
|
||||||
|
model: 'SP 24-70mm f/2.8 Di VC USD',
|
||||||
|
mount: 'Canon EF',
|
||||||
|
crop: 1,
|
||||||
|
d: [[24, 2, 0.01, -0.02, 0.03, 0]],
|
||||||
|
};
|
||||||
|
|
||||||
|
describe('team lens calibration validation', () => {
|
||||||
|
it('accepts a measured profile and normalises its text', () => {
|
||||||
|
const result = parseCalibration({ ...base, maker: ' Tamron ', notes: ' shot on a 5D ' });
|
||||||
|
expect(result.error).toBeUndefined();
|
||||||
|
expect(result.value).toMatchObject({
|
||||||
|
maker: 'Tamron',
|
||||||
|
model: 'SP 24-70mm f/2.8 Di VC USD',
|
||||||
|
mount: 'Canon EF',
|
||||||
|
crop: 1,
|
||||||
|
notes: 'shot on a 5D',
|
||||||
|
aspect: 0,
|
||||||
|
centerX: 0,
|
||||||
|
centerY: 0,
|
||||||
|
});
|
||||||
|
expect(result.value.d).toEqual([[24, 2, 0.01, -0.02, 0.03, 0]]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('requires a maker and a model', () => {
|
||||||
|
expect(parseCalibration({ ...base, maker: ' ' }).error).toMatch(/maker/i);
|
||||||
|
expect(parseCalibration({ ...base, model: '' }).error).toMatch(/model/i);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects unknown models and impossible focals', () => {
|
||||||
|
expect(parseCalibration({ ...base, d: [[24, 7, 0.01, 0, 0, 0]] }).error).toMatch(/model/i);
|
||||||
|
expect(parseCalibration({ ...base, d: [[0, 2, 0.01, 0, 0, 0]] }).error).toMatch(/focal/i);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects a row with the wrong number of values', () => {
|
||||||
|
expect(parseCalibration({ ...base, d: [[24, 2, 0.01]] }).error).toMatch(/6 numbers/);
|
||||||
|
expect(parseCalibration({ ...base, t: [[24, 0, 0, 0]] }).error).toMatch(/8 numbers/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects a crop factor no lens has', () => {
|
||||||
|
expect(parseCalibration({ ...base, crop: 0 }).error).toMatch(/crop/i);
|
||||||
|
expect(parseCalibration({ ...base, crop: 9 }).error).toMatch(/crop/i);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('needs at least one sample of any kind', () => {
|
||||||
|
expect(parseCalibration({ ...base, d: [] }).error).toMatch(/at least one/i);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps vignetting samples that a measurement pass produced', () => {
|
||||||
|
const result = parseCalibration({
|
||||||
|
...base,
|
||||||
|
d: [],
|
||||||
|
v: [
|
||||||
|
[24, 2.8, 1000, 0.31, -0.12, 0.02],
|
||||||
|
[70, 2.8, 1000, 0.42, -0.2, 0.05],
|
||||||
|
],
|
||||||
|
});
|
||||||
|
expect(result.error).toBeUndefined();
|
||||||
|
expect(result.value.v).toHaveLength(2);
|
||||||
|
expect(result.value.d).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects vignetting without an aperture', () => {
|
||||||
|
expect(parseCalibration({ ...base, d: [], v: [[24, 0, 1000, 0.3, 0, 0]] }).error).toMatch(/aperture/i);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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,54 @@
|
|||||||
|
/**
|
||||||
|
* Rebuilds stored raw proxies from their originals.
|
||||||
|
*
|
||||||
|
* A decode is CPU bound and holds a LibRaw worker for seconds, so the work runs
|
||||||
|
* one photo at a time behind a snapshot: a request that blocked for an hour
|
||||||
|
* would time out, and decoding in parallel would starve the editor. The job
|
||||||
|
* itself keeps progress in memory; `onProgress` lets the caller persist it so a
|
||||||
|
* restart can pick the run up where it stopped.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/** Photos that have a proxy worth regenerating: camera raws that still exist. */
|
||||||
|
export function previewRebuildTargets(photos) {
|
||||||
|
return photos.filter((photo) => photo && photo.raw === true && !photo.deletedAt);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Runs `regenerate(photo)` for every target and reports progress.
|
||||||
|
*
|
||||||
|
* A photo that fails is counted and recorded, and the run continues: one
|
||||||
|
* unreadable original must not strand the rest of the library.
|
||||||
|
*/
|
||||||
|
export function startPreviewRebuild({ targets, regenerate, now = Date.now, onProgress }) {
|
||||||
|
const job = {
|
||||||
|
state: 'running',
|
||||||
|
total: targets.length,
|
||||||
|
done: 0,
|
||||||
|
failed: 0,
|
||||||
|
sidecars: 0,
|
||||||
|
startedAt: now(),
|
||||||
|
finishedAt: null,
|
||||||
|
errors: [],
|
||||||
|
};
|
||||||
|
|
||||||
|
const finished = (async () => {
|
||||||
|
for (const [index, photo] of targets.entries()) {
|
||||||
|
try {
|
||||||
|
const result = await regenerate(photo);
|
||||||
|
if (result?.sidecar) job.sidecars += 1;
|
||||||
|
} catch (err) {
|
||||||
|
job.failed += 1;
|
||||||
|
if (job.errors.length < 5) {
|
||||||
|
const label = photo?.name || photo?.id || 'photo';
|
||||||
|
job.errors.push(`${label}: ${err instanceof Error ? err.message : String(err)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
job.done += 1;
|
||||||
|
onProgress?.({ ...job, errors: [...job.errors] }, targets.slice(index + 1));
|
||||||
|
}
|
||||||
|
job.state = 'done';
|
||||||
|
job.finishedAt = now();
|
||||||
|
})();
|
||||||
|
|
||||||
|
return { snapshot: () => ({ ...job, errors: [...job.errors] }), finished };
|
||||||
|
}
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import { previewRebuildTargets, startPreviewRebuild } from './previewRebuild.mjs';
|
||||||
|
|
||||||
|
describe('preview rebuild targets', () => {
|
||||||
|
it('takes live camera raws and nothing else', () => {
|
||||||
|
const photos = [
|
||||||
|
{ id: 'raw', raw: true },
|
||||||
|
{ id: 'jpeg', raw: false },
|
||||||
|
{ id: 'trashed', raw: true, deletedAt: 1 },
|
||||||
|
{ id: 'unknown' },
|
||||||
|
];
|
||||||
|
expect(previewRebuildTargets(photos).map((photo) => photo.id)).toEqual(['raw']);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('preview rebuild job', () => {
|
||||||
|
it('walks every target in order and counts the 16-bit sidecars', async () => {
|
||||||
|
const seen = [];
|
||||||
|
const job = startPreviewRebuild({
|
||||||
|
targets: [{ id: 'a' }, { id: 'b' }],
|
||||||
|
regenerate: async (photo) => {
|
||||||
|
seen.push(photo.id);
|
||||||
|
return { sidecar: photo.id === 'a' };
|
||||||
|
},
|
||||||
|
now: () => 7,
|
||||||
|
});
|
||||||
|
expect(job.snapshot()).toMatchObject({ state: 'running', total: 2, done: 0 });
|
||||||
|
await job.finished;
|
||||||
|
expect(seen).toEqual(['a', 'b']);
|
||||||
|
expect(job.snapshot()).toMatchObject({
|
||||||
|
state: 'done',
|
||||||
|
done: 2,
|
||||||
|
failed: 0,
|
||||||
|
sidecars: 1,
|
||||||
|
startedAt: 7,
|
||||||
|
finishedAt: 7,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps going after a photo that cannot be decoded', async () => {
|
||||||
|
const job = startPreviewRebuild({
|
||||||
|
targets: [{ id: 'a', name: 'A.CR2' }, { id: 'b', name: 'B.CR2' }],
|
||||||
|
regenerate: async (photo) => {
|
||||||
|
if (photo.id === 'a') throw new Error('the original is missing');
|
||||||
|
return { sidecar: false };
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await job.finished;
|
||||||
|
const snapshot = job.snapshot();
|
||||||
|
expect(snapshot).toMatchObject({ state: 'done', done: 2, failed: 1, sidecars: 0 });
|
||||||
|
expect(snapshot.errors[0]).toContain('A.CR2');
|
||||||
|
expect(snapshot.errors[0]).toContain('the original is missing');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('hands out copies, so a caller cannot edit the live progress', async () => {
|
||||||
|
const job = startPreviewRebuild({
|
||||||
|
targets: [{ id: 'a' }],
|
||||||
|
regenerate: async () => ({ sidecar: false }),
|
||||||
|
});
|
||||||
|
const snapshot = job.snapshot();
|
||||||
|
snapshot.errors.push('tampered');
|
||||||
|
await job.finished;
|
||||||
|
expect(job.snapshot().errors).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('reports progress and what is still pending after each photo', async () => {
|
||||||
|
const steps = [];
|
||||||
|
const job = startPreviewRebuild({
|
||||||
|
targets: [{ id: 'a' }, { id: 'b' }, { id: 'c' }],
|
||||||
|
regenerate: async () => ({ sidecar: false }),
|
||||||
|
onProgress: (snapshot, pending) =>
|
||||||
|
steps.push({ done: snapshot.done, pending: pending.map((photo) => photo.id) }),
|
||||||
|
});
|
||||||
|
await job.finished;
|
||||||
|
expect(steps).toEqual([
|
||||||
|
{ done: 1, pending: ['b', 'c'] },
|
||||||
|
{ done: 2, pending: ['c'] },
|
||||||
|
{ done: 3, pending: [] },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('finishes immediately when there is nothing to rebuild', async () => {
|
||||||
|
const job = startPreviewRebuild({ targets: [], regenerate: async () => ({ sidecar: false }) });
|
||||||
|
await job.finished;
|
||||||
|
expect(job.snapshot()).toMatchObject({ state: 'done', total: 0, done: 0, failed: 0 });
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
import { RAW_PREVIEW_EDGE } from './config.mjs';
|
import { RAW_16BIT, RAW_PREVIEW_EDGE } from './config.mjs';
|
||||||
import { encodeRgb, jpegInfo, loadSharp, toJpegProxy } from './imaging.mjs';
|
import { cameraToProxy, readRgbCam } from './color.mjs';
|
||||||
|
import { encodePng16, encodeRgb, jpegInfo, loadSharp, resizeRgb16, toJpegProxy } from './imaging.mjs';
|
||||||
import { loadLibRaw, rawPool } from './libraw-pool.mjs';
|
import { loadLibRaw, rawPool } from './libraw-pool.mjs';
|
||||||
|
|
||||||
/** Every raw container the pipeline will attempt, grouped by vendor family. */
|
/** Every raw container the pipeline will attempt, grouped by vendor family. */
|
||||||
@@ -27,6 +28,26 @@ export function isRawName(name = '') {
|
|||||||
return RAW_EXTENSIONS.has(ext);
|
return RAW_EXTENSIONS.has(ext);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Standard images that browsers cannot decode. TIFF takes the raw upload path
|
||||||
|
* (store the original, serve a JPEG proxy) but is decoded by sharp, not LibRaw.
|
||||||
|
*/
|
||||||
|
export const SERVER_IMAGE_EXTENSIONS = new Set(['tif', 'tiff']);
|
||||||
|
|
||||||
|
export function isStillName(name = '') {
|
||||||
|
const ext = name.split('.').pop()?.toLowerCase() ?? '';
|
||||||
|
return SERVER_IMAGE_EXTENSIONS.has(ext);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Rejects instead of waiting forever when a decoder wedges on one file. */
|
||||||
|
function withTimeout(promise, ms, message) {
|
||||||
|
let timer;
|
||||||
|
const guard = new Promise((_, reject) => {
|
||||||
|
timer = setTimeout(() => reject(new Error(message)), ms);
|
||||||
|
});
|
||||||
|
return Promise.race([promise, guard]).finally(() => clearTimeout(timer));
|
||||||
|
}
|
||||||
|
|
||||||
/** True when the buffer starts with a container signature LibRaw can open. */
|
/** True when the buffer starts with a container signature LibRaw can open. */
|
||||||
export function looksLikeRaw(buffer) {
|
export function looksLikeRaw(buffer) {
|
||||||
if (!buffer || buffer.length < 64) return false;
|
if (!buffer || buffer.length < 64) return false;
|
||||||
@@ -44,6 +65,19 @@ export function looksLikeRaw(buffer) {
|
|||||||
|
|
||||||
let engineState = 'unloaded';
|
let engineState = 'unloaded';
|
||||||
|
|
||||||
|
export async function decodeStill(buffer) {
|
||||||
|
const proxy = await toJpegProxy(buffer, RAW_PREVIEW_EDGE);
|
||||||
|
if (!proxy) throw new Error('Could not decode this image');
|
||||||
|
const size = await jpegInfo(proxy.data);
|
||||||
|
return {
|
||||||
|
jpeg: proxy.data,
|
||||||
|
width: size?.width || proxy.width,
|
||||||
|
height: size?.height || proxy.height,
|
||||||
|
engine: 'sharp',
|
||||||
|
ext: proxy.ext,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
export async function rawEngine() {
|
export async function rawEngine() {
|
||||||
if (engineState === 'unloaded') {
|
if (engineState === 'unloaded') {
|
||||||
try {
|
try {
|
||||||
@@ -57,12 +91,25 @@ export async function rawEngine() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const DECODE_SETTINGS = {
|
const DECODE_SETTINGS = {
|
||||||
outputBps: 8,
|
// Decode at 16 bits and let LibRaw blend reconstructed highlights instead of
|
||||||
|
// clipping them; the 8-bit proxy is downsampled after the rolloff, so a
|
||||||
|
// recovered sky keeps gradation instead of a flat white patch.
|
||||||
|
outputBps: 16,
|
||||||
useCameraWb: true,
|
useCameraWb: true,
|
||||||
outputColor: 1, // sRGB
|
// Camera-native, not sRGB: the camera-to-output matrix is applied here in JS
|
||||||
|
// (see color.mjs) and again by the editor on the 16-bit sidecar. That makes
|
||||||
|
// the conversion one swappable matrix instead of a fixed choice inside
|
||||||
|
// LibRaw, which is what a camera profile needs.
|
||||||
|
outputColor: 0,
|
||||||
userQual: 3,
|
userQual: 3,
|
||||||
highlight: 0,
|
highlight: 2,
|
||||||
noAutoBright: false,
|
// One white point for the frame, chosen after the matrix. LibRaw's per-path
|
||||||
|
// auto-bright measures each output colourspace separately, so the JPEG and
|
||||||
|
// the camera-native sidecar would disagree by up to half a stop.
|
||||||
|
noAutoBright: true,
|
||||||
|
// Always use the camera's own colour matrix. The default only does so when
|
||||||
|
// white balance is applied, which leaves some bodies on the generic matrix.
|
||||||
|
useCameraMatrix: 3,
|
||||||
// Use the orientation stored in the raw container: phone and DSLR files often
|
// Use the orientation stored in the raw container: phone and DSLR files often
|
||||||
// record the shot rotated (EXIF 6/8), and demosaicing without it produces a
|
// record the shot rotated (EXIF 6/8), and demosaicing without it produces a
|
||||||
// sideways proxy that no later step can fix without losing the original axes.
|
// sideways proxy that no later step can fix without losing the original axes.
|
||||||
@@ -70,7 +117,13 @@ const DECODE_SETTINGS = {
|
|||||||
useFujiRotate: -1,
|
useFujiRotate: -1,
|
||||||
};
|
};
|
||||||
|
|
||||||
/** Turns one LibRaw `imageData()` result into an interleaved RGB buffer. */
|
/**
|
||||||
|
* Turns one LibRaw `imageData()` result into an interleaved RGB buffer.
|
||||||
|
*
|
||||||
|
* The 8-bit copy is what the JPEG proxy is encoded from. The 16-bit copy keeps
|
||||||
|
* every sample LibRaw produced so the editor can upload a half-float source
|
||||||
|
* texture; without it, a heavy shadow lift is applied to 256 levels per channel.
|
||||||
|
*/
|
||||||
function toRgb(img) {
|
function toRgb(img) {
|
||||||
if (!img || !img.width || !img.height || !img.data) throw new Error('LibRaw returned no pixels');
|
if (!img || !img.width || !img.height || !img.data) throw new Error('LibRaw returned no pixels');
|
||||||
const width = Number(img.width);
|
const width = Number(img.width);
|
||||||
@@ -79,19 +132,36 @@ function toRgb(img) {
|
|||||||
const bits = Number(img.bits ?? 8);
|
const bits = Number(img.bits ?? 8);
|
||||||
const src = img.data;
|
const src = img.data;
|
||||||
const pixelCount = width * height;
|
const pixelCount = width * height;
|
||||||
const needed = pixelCount * colors * (bits > 8 ? 2 : 1);
|
const needed = pixelCount * colors;
|
||||||
if (src.length < needed) {
|
// libraw-wasm hands back samples, not bytes: with outputBps 16 the buffer is a
|
||||||
throw new Error(`LibRaw buffer too small (${src.length} bytes for ${width}×${height}×${colors})`);
|
// Uint16Array already. Older builds returned the raw 16-bit bytes, so accept
|
||||||
|
// both shapes instead of assuming one and rejecting every 16-bit decode.
|
||||||
|
const wide =
|
||||||
|
bits > 8 && !(src instanceof Uint16Array)
|
||||||
|
? new Uint16Array(src.buffer, src.byteOffset, Math.floor(src.byteLength / 2))
|
||||||
|
: src;
|
||||||
|
if (wide.length < needed) {
|
||||||
|
throw new Error(
|
||||||
|
`LibRaw buffer too small (${wide.length} samples for ${width}×${height}×${colors})`,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const rgb = Buffer.alloc(pixelCount * 3);
|
const rgb = Buffer.alloc(pixelCount * 3);
|
||||||
|
let rgb16 = null;
|
||||||
if (bits > 8) {
|
if (bits > 8) {
|
||||||
const view = new Uint16Array(src.buffer, src.byteOffset, Math.floor(src.byteLength / 2));
|
const view = wide instanceof Uint16Array ? wide : src;
|
||||||
|
rgb16 = new Uint16Array(pixelCount * 3);
|
||||||
for (let i = 0; i < pixelCount; i++) {
|
for (let i = 0; i < pixelCount; i++) {
|
||||||
const s = i * colors;
|
const s = i * colors;
|
||||||
rgb[i * 3] = view[s] >> 8;
|
const r = view[s];
|
||||||
rgb[i * 3 + 1] = view[s + 1] >> 8;
|
const g = view[s + 1];
|
||||||
rgb[i * 3 + 2] = view[s + 2] >> 8;
|
const b = view[s + 2];
|
||||||
|
rgb[i * 3] = r >> 8;
|
||||||
|
rgb[i * 3 + 1] = g >> 8;
|
||||||
|
rgb[i * 3 + 2] = b >> 8;
|
||||||
|
rgb16[i * 3] = r;
|
||||||
|
rgb16[i * 3 + 1] = g;
|
||||||
|
rgb16[i * 3 + 2] = b;
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
for (let i = 0; i < pixelCount; i++) {
|
for (let i = 0; i < pixelCount; i++) {
|
||||||
@@ -101,20 +171,29 @@ function toRgb(img) {
|
|||||||
rgb[i * 3 + 2] = src[s + 2];
|
rgb[i * 3 + 2] = src[s + 2];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return { rgb, width, height };
|
return { rgb, rgb16, width, height };
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Full demosaic through a pooled LibRaw worker. `open()` only unpacks the file;
|
* Full demosaic through a pooled LibRaw worker. `open()` only unpacks the file;
|
||||||
* the pixels come from `imageData()`, which rejects when the camera is unsupported.
|
* the pixels come from `imageData()`, which rejects when the camera is unsupported.
|
||||||
|
*
|
||||||
|
* `cameraNative` asks for the frame before LibRaw's output matrix, plus the
|
||||||
|
* matrix metadata. A body LibRaw has no matrix for falls back to the plain sRGB
|
||||||
|
* decode, which is the same result the pipeline produced before.
|
||||||
*/
|
*/
|
||||||
async function demosaic(buffer) {
|
async function demosaic(buffer, cameraNative = true) {
|
||||||
if ((await rawEngine()) !== 'ready') throw new Error('LibRaw is not installed');
|
if ((await rawEngine()) !== 'ready') throw new Error('LibRaw is not installed');
|
||||||
return rawPool.use(async (lib) => {
|
return rawPool.use(async (lib) => {
|
||||||
// LibRaw transfers the buffer to its worker, which detaches it here. Hand it
|
// LibRaw transfers the buffer to its worker, which detaches it here. Hand it
|
||||||
// a copy so the caller's bytes survive for the embedded-preview fallback.
|
// a copy so the caller's bytes survive for the embedded-preview fallback.
|
||||||
await lib.open(Buffer.from(buffer), DECODE_SETTINGS);
|
await lib.open(
|
||||||
return toRgb(await lib.imageData());
|
Buffer.from(buffer),
|
||||||
|
cameraNative ? DECODE_SETTINGS : { ...DECODE_SETTINGS, outputColor: 1, noAutoBright: false },
|
||||||
|
);
|
||||||
|
const image = toRgb(await lib.imageData());
|
||||||
|
const rgbCam = cameraNative ? readRgbCam(await lib.metadata(true)) : null;
|
||||||
|
return { ...image, rgbCam };
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -141,10 +220,14 @@ export function extractEmbeddedJpeg(buffer) {
|
|||||||
async function embeddedPreview(buffer) {
|
async function embeddedPreview(buffer) {
|
||||||
if ((await rawEngine()) === 'ready') {
|
if ((await rawEngine()) === 'ready') {
|
||||||
try {
|
try {
|
||||||
const thumb = await rawPool.use(async (lib) => {
|
const thumb = await withTimeout(
|
||||||
await lib.open(Buffer.from(buffer), { useCameraWb: true });
|
rawPool.use(async (lib) => {
|
||||||
return lib.thumbnailData();
|
await lib.open(Buffer.from(buffer), { useCameraWb: true });
|
||||||
});
|
return lib.thumbnailData();
|
||||||
|
}),
|
||||||
|
12000,
|
||||||
|
'LibRaw preview timed out',
|
||||||
|
);
|
||||||
if (thumb?.data && thumb.format === 'jpeg' && thumb.data.length > 4096) {
|
if (thumb?.data && thumb.format === 'jpeg' && thumb.data.length > 4096) {
|
||||||
return Buffer.from(thumb.data);
|
return Buffer.from(thumb.data);
|
||||||
}
|
}
|
||||||
@@ -163,10 +246,38 @@ export async function decodeRaw(buffer) {
|
|||||||
let librawError = null;
|
let librawError = null;
|
||||||
if (looksLikeRaw(buffer)) {
|
if (looksLikeRaw(buffer)) {
|
||||||
try {
|
try {
|
||||||
const { rgb, width, height } = await demosaic(buffer);
|
let frame = await withTimeout(demosaic(buffer, true), 45000, 'LibRaw timed out on this file');
|
||||||
|
// No usable matrix (an odd body or older engine): decode the familiar sRGB
|
||||||
|
// way instead of shipping camera samples nobody can convert.
|
||||||
|
if (!frame.rgbCam || !frame.rgb16) frame = await withTimeout(demosaic(buffer, false), 45000, 'LibRaw timed out on this file');
|
||||||
|
const { width, height, rgbCam } = frame;
|
||||||
|
// Both buffers are rewritten in place: `rgb` becomes the sRGB proxy and
|
||||||
|
// `rgb16` the camera-native sidecar, sharing one white point.
|
||||||
|
if (rgbCam && frame.rgb16) cameraToProxy(frame.rgb16, frame.rgb, rgbCam);
|
||||||
|
const { rgb } = frame;
|
||||||
const encoded = await encodeRgb(rgb, width, height, 92, RAW_PREVIEW_EDGE);
|
const encoded = await encodeRgb(rgb, width, height, 92, RAW_PREVIEW_EDGE);
|
||||||
|
// The sidecar must match the JPEG pixel for pixel: the editor swaps the
|
||||||
|
// two textures at the same uv, so a size disagreement would misalign the
|
||||||
|
// whole grade. It is optional -- encoding failures leave the JPEG path.
|
||||||
|
let preview16 = null;
|
||||||
|
if (frame.rgb16 && RAW_16BIT) {
|
||||||
|
try {
|
||||||
|
const scaled = resizeRgb16(frame.rgb16, width, height, encoded.width, encoded.height);
|
||||||
|
preview16 = {
|
||||||
|
// The matrix travels with the samples so the editor knows how to
|
||||||
|
// turn camera RGB into sRGB without a second metadata fetch.
|
||||||
|
data: encodePng16(scaled, encoded.width, encoded.height, rgbCam),
|
||||||
|
width: encoded.width,
|
||||||
|
height: encoded.height,
|
||||||
|
rgbCam,
|
||||||
|
};
|
||||||
|
} catch {
|
||||||
|
preview16 = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
return {
|
return {
|
||||||
jpeg: encoded.data,
|
jpeg: encoded.data,
|
||||||
|
preview16,
|
||||||
width: encoded.width,
|
width: encoded.width,
|
||||||
height: encoded.height,
|
height: encoded.height,
|
||||||
engine: 'libraw',
|
engine: 'libraw',
|
||||||
|
|||||||
@@ -0,0 +1,108 @@
|
|||||||
|
import { readFileSync, existsSync } from 'node:fs';
|
||||||
|
import path from 'node:path';
|
||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import {
|
||||||
|
RAW_EXTENSIONS,
|
||||||
|
decodeRaw,
|
||||||
|
decodeStill,
|
||||||
|
isRawName,
|
||||||
|
isStillName,
|
||||||
|
looksLikeRaw,
|
||||||
|
rawEngine,
|
||||||
|
} from './raw.mjs';
|
||||||
|
|
||||||
|
/** TIFF-family containers: CR2, NEF and DNG all start with the same header. */
|
||||||
|
function tiffHeader() {
|
||||||
|
const buffer = Buffer.alloc(64);
|
||||||
|
Buffer.from('49492a00', 'hex').copy(buffer, 0);
|
||||||
|
return buffer;
|
||||||
|
}
|
||||||
|
|
||||||
|
function withAscii(bytes) {
|
||||||
|
const buffer = Buffer.alloc(64);
|
||||||
|
buffer.write(bytes, 0, 'latin1');
|
||||||
|
return buffer;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('raw format coverage', () => {
|
||||||
|
it.each(['cr2', 'nef', 'cr3', 'dng'])('routes .%s to the raw decoder', (ext) => {
|
||||||
|
expect(RAW_EXTENSIONS.has(ext)).toBe(true);
|
||||||
|
expect(isRawName(`IMG_0001.${ext}`)).toBe(true);
|
||||||
|
expect(isRawName(`IMG_0001.${ext.toUpperCase()}`)).toBe(true);
|
||||||
|
expect(isStillName(`IMG_0001.${ext}`)).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each(['tif', 'tiff'])('routes .%s to the still decoder', (ext) => {
|
||||||
|
expect(isStillName(`scan.${ext}`)).toBe(true);
|
||||||
|
expect(isStillName(`scan.${ext.toUpperCase()}`)).toBe(true);
|
||||||
|
expect(isRawName(`scan.${ext}`)).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('recognises the container signatures of the main families', () => {
|
||||||
|
expect(looksLikeRaw(tiffHeader())).toBe(true); // CR2, NEF, DNG
|
||||||
|
const cr3 = Buffer.alloc(64);
|
||||||
|
cr3.write('ftyp', 4, 'latin1');
|
||||||
|
expect(looksLikeRaw(cr3)).toBe(true);
|
||||||
|
expect(looksLikeRaw(withAscii('IIRO'))).toBe(true); // ORF
|
||||||
|
expect(looksLikeRaw(withAscii('IIU\0'))).toBe(true); // RW2
|
||||||
|
expect(looksLikeRaw(withAscii('FUJIFILMCCD-RAW'))).toBe(true); // RAF
|
||||||
|
expect(looksLikeRaw(withAscii('FOVb'))).toBe(true); // X3F
|
||||||
|
expect(looksLikeRaw(Buffer.alloc(64))).toBe(false);
|
||||||
|
expect(looksLikeRaw(Buffer.alloc(8))).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('TIFF decoding', () => {
|
||||||
|
it('turns a TIFF into a JPEG proxy', async () => {
|
||||||
|
const { default: sharp } = await import('sharp');
|
||||||
|
const tiff = await sharp({
|
||||||
|
create: {
|
||||||
|
width: 48,
|
||||||
|
height: 32,
|
||||||
|
channels: 3,
|
||||||
|
background: { r: 20, g: 120, b: 210 },
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.tiff()
|
||||||
|
.toBuffer();
|
||||||
|
const decoded = await decodeStill(tiff);
|
||||||
|
expect(decoded.engine).toBe('sharp');
|
||||||
|
expect(decoded.ext).toBe('jpg');
|
||||||
|
expect(decoded.width).toBe(48);
|
||||||
|
expect(decoded.height).toBe(32);
|
||||||
|
expect(decoded.jpeg.subarray(0, 2)).toEqual(Buffer.from([0xff, 0xd8]));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects a file that is not an image', async () => {
|
||||||
|
await expect(decodeStill(Buffer.from('not a tiff at all'))).rejects.toThrow(
|
||||||
|
/could not decode/i,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Real containers are optional: point LUMINARY_RAW_FIXTURES at a directory
|
||||||
|
* holding sample.cr2, sample.nef, sample.cr3 and sample.dng. The samples are
|
||||||
|
* deliberately not committed (they are 10-40 MB each and camera-specific), but
|
||||||
|
* when they are present this exercises the same libraw path an import takes.
|
||||||
|
*/
|
||||||
|
const FIXTURES = process.env.LUMINARY_RAW_FIXTURES;
|
||||||
|
const fixture = (ext) => (FIXTURES ? path.join(FIXTURES, `sample.${ext}`) : '');
|
||||||
|
const available = (ext) => Boolean(FIXTURES) && existsSync(fixture(ext));
|
||||||
|
const rawFormats = ['cr2', 'nef', 'cr3', 'dng'];
|
||||||
|
|
||||||
|
describe.skipIf(!FIXTURES)('real raw containers', () => {
|
||||||
|
it('has libraw available', async () => {
|
||||||
|
expect(await rawEngine()).toBe('ready');
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const ext of rawFormats) {
|
||||||
|
it.skipIf(!available(ext))(`decodes sample.${ext}`, async () => {
|
||||||
|
const decoded = await decodeRaw(readFileSync(fixture(ext)));
|
||||||
|
expect(decoded.jpeg.length).toBeGreaterThan(4096);
|
||||||
|
expect(['libraw', 'embedded']).toContain(decoded.engine);
|
||||||
|
expect(decoded.width).toBeGreaterThan(0);
|
||||||
|
expect(decoded.height).toBeGreaterThan(0);
|
||||||
|
}, 120000);
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -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;
|
||||||
@@ -112,6 +117,54 @@ export function findPreview(id) {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The 16-bit sidecar for a raw proxy: the samples LibRaw decoded, before the
|
||||||
|
* JPEG quantised them. Its name keeps a second extension so `findPreview` keeps
|
||||||
|
* returning the JPEG for browsers and for photos imported before this existed.
|
||||||
|
*/
|
||||||
|
export async function writePreview16(id, data) {
|
||||||
|
ensureDirs();
|
||||||
|
const target = path.join(storageRoot(), 'previews', `${safeId(id)}.p16.png`);
|
||||||
|
await fsp.writeFile(target, data);
|
||||||
|
return target;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function findPreview16(id) {
|
||||||
|
const safe = lookupId(id);
|
||||||
|
if (!safe) return null;
|
||||||
|
const p = path.join(dirs().previews, `${safe}.p16.png`);
|
||||||
|
return fs.existsSync(p) ? p : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function removePreview16(id) {
|
||||||
|
const found = findPreview16(id);
|
||||||
|
if (found) await fsp.rm(found, { force: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Camera-native grid thumbnail: the sidecar's samples at the JPEG thumbnail's
|
||||||
|
* size, so the grid can honour a per-photo camera profile without downloading
|
||||||
|
* the full sidecar. Lives beside the sidecar and is regenerated on demand.
|
||||||
|
*/
|
||||||
|
export async function writeThumb16(id, data) {
|
||||||
|
ensureDirs();
|
||||||
|
const target = path.join(storageRoot(), 'previews', `${safeId(id)}.t16.png`);
|
||||||
|
await fsp.writeFile(target, data);
|
||||||
|
return target;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function findThumb16(id) {
|
||||||
|
const safe = lookupId(id);
|
||||||
|
if (!safe) return null;
|
||||||
|
const p = path.join(dirs().previews, `${safe}.t16.png`);
|
||||||
|
return fs.existsSync(p) ? p : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function removeThumb16(id) {
|
||||||
|
const found = findThumb16(id);
|
||||||
|
if (found) await fsp.rm(found, { force: true });
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Denoised proxies, keyed by the hash of the parameters that produced them, so
|
* Denoised proxies, keyed by the hash of the parameters that produced them, so
|
||||||
* switching Amount back to a previous value reuses the file instead of spending
|
* switching Amount back to a previous value reuses the file instead of spending
|
||||||
@@ -204,6 +257,8 @@ export async function removeAsset(id) {
|
|||||||
const files = [
|
const files = [
|
||||||
findOriginal(id),
|
findOriginal(id),
|
||||||
findPreview(id),
|
findPreview(id),
|
||||||
|
findPreview16(id),
|
||||||
|
findThumb16(id),
|
||||||
findThumb(id),
|
findThumb(id),
|
||||||
findProof(id),
|
findProof(id),
|
||||||
findProofThumb(id),
|
findProofThumb(id),
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||||
|
import AboutModal from './components/AboutModal';
|
||||||
import AdminPanel from './components/AdminPanel';
|
import AdminPanel from './components/AdminPanel';
|
||||||
import CloudPanel from './components/CloudPanel';
|
import CloudPanel from './components/CloudPanel';
|
||||||
import CommandPalette from './components/CommandPalette';
|
import CommandPalette from './components/CommandPalette';
|
||||||
@@ -9,11 +10,18 @@ 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';
|
||||||
import PrintModal from './components/PrintModal';
|
import PrintModal from './components/PrintModal';
|
||||||
import ShareModal from './components/ShareModal';
|
import ShareModal from './components/ShareModal';
|
||||||
|
import RawReprocessModal, {
|
||||||
|
type RawReprocessFailure,
|
||||||
|
type RawReprocessJob,
|
||||||
|
} from './components/RawReprocessModal';
|
||||||
|
import CullAssistModal from './components/CullAssistModal';
|
||||||
|
import TetherPanel from './components/TetherPanel';
|
||||||
import Shortcuts from './components/Shortcuts';
|
import Shortcuts from './components/Shortcuts';
|
||||||
import Stars, { ColorSwatches, FlagButtons } from './components/Stars';
|
import Stars, { ColorSwatches, FlagButtons } from './components/Stars';
|
||||||
import TopBar from './components/TopBar';
|
import TopBar from './components/TopBar';
|
||||||
@@ -22,18 +30,24 @@ 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,
|
||||||
|
reprocessRawPhoto,
|
||||||
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,
|
||||||
@@ -52,8 +66,9 @@ import { COLOR_LABELS, defaultEdits, isEdited, normalizePhoto } from './lib/edit
|
|||||||
import { applyEditSections, type EditSectionId } from './lib/editSections';
|
import { applyEditSections, type EditSectionId } from './lib/editSections';
|
||||||
import type { MergeResult } from './lib/merge';
|
import type { MergeResult } from './lib/merge';
|
||||||
import { evictBitmap } from './lib/images';
|
import { evictBitmap } from './lib/images';
|
||||||
import { uid } from './lib/import';
|
import { importFiles, uid } from './lib/import';
|
||||||
import { PRESETS } from './lib/presets';
|
import { PRESETS } from './lib/presets';
|
||||||
|
import { downloadXmp, readXmpFile, xmpToEdits } from './lib/xmp';
|
||||||
import type {
|
import type {
|
||||||
Edits,
|
Edits,
|
||||||
EventRecord,
|
EventRecord,
|
||||||
@@ -124,6 +139,7 @@ export default function App() {
|
|||||||
const [undoAction, setUndoAction] = useState<{ message: string; run: () => void } | null>(null);
|
const [undoAction, setUndoAction] = useState<{ message: string; run: () => void } | null>(null);
|
||||||
const [menu, setMenu] = useState<{ x: number; y: number; ids: string[] } | null>(null);
|
const [menu, setMenu] = useState<{ x: number; y: number; ids: string[] } | null>(null);
|
||||||
const [helpOpen, setHelpOpen] = useState(false);
|
const [helpOpen, setHelpOpen] = useState(false);
|
||||||
|
const [aboutOpen, setAboutOpen] = useState(false);
|
||||||
const [searchOpen, setSearchOpen] = useState(false);
|
const [searchOpen, setSearchOpen] = useState(false);
|
||||||
const [shareEventId, setShareEventId] = useState<string | null>(null);
|
const [shareEventId, setShareEventId] = useState<string | null>(null);
|
||||||
/** Client proofing picks, keyed to the photos they chose. */
|
/** Client proofing picks, keyed to the photos they chose. */
|
||||||
@@ -136,6 +152,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);
|
||||||
@@ -144,6 +195,12 @@ export default function App() {
|
|||||||
const [exportOptions, setExportOptions] = useState<ExportOptions>(DEFAULT_EXPORT);
|
const [exportOptions, setExportOptions] = useState<ExportOptions>(DEFAULT_EXPORT);
|
||||||
const [exportRecipes, setExportRecipes] = useState<ExportRecipe[]>([]);
|
const [exportRecipes, setExportRecipes] = useState<ExportRecipe[]>([]);
|
||||||
const [mergeOpen, setMergeOpen] = useState(false);
|
const [mergeOpen, setMergeOpen] = useState(false);
|
||||||
|
const [rawJob, setRawJob] = useState<RawReprocessJob | null>(null);
|
||||||
|
const [cullOpen, setCullOpen] = useState(false);
|
||||||
|
const [tetherEventId, setTetherEventId] = useState<string | null>(null);
|
||||||
|
const rawBusyRef = useRef(false);
|
||||||
|
const rawCancelRef = useRef(false);
|
||||||
|
const rawBusy = Boolean(rawJob?.running);
|
||||||
const [printOpen, setPrintOpen] = useState(false);
|
const [printOpen, setPrintOpen] = useState(false);
|
||||||
|
|
||||||
const saveTimers = useRef(new Map<string, ReturnType<typeof setTimeout>>());
|
const saveTimers = useRef(new Map<string, ReturnType<typeof setTimeout>>());
|
||||||
@@ -322,6 +379,151 @@ export default function App() {
|
|||||||
[queueSave],
|
[queueSave],
|
||||||
);
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Re-decode selected RAW files on the server, then refresh the cached proxy so
|
||||||
|
* the grid and Develop pick up the new pixels without a reload. Existing edits
|
||||||
|
* are kept; only width, height and the decode engine change on the record.
|
||||||
|
*/
|
||||||
|
const reprocessRawPhotos = useCallback(
|
||||||
|
async (ids: string[], options: { eventName?: string } = {}) => {
|
||||||
|
if (rawBusyRef.current) {
|
||||||
|
setToast('A RAW reprocess is already running');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const targets = photosRef.current.filter(
|
||||||
|
(photo) => ids.includes(photo.id) && photo.raw && !photo.deletedAt,
|
||||||
|
);
|
||||||
|
if (!targets.length) {
|
||||||
|
setToast('Select RAW photos to reprocess');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!userRef.current) {
|
||||||
|
setToast('Sign in to the server to reprocess RAW files');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
rawBusyRef.current = true;
|
||||||
|
rawCancelRef.current = false;
|
||||||
|
const failures: RawReprocessFailure[] = [];
|
||||||
|
let attempts = 0;
|
||||||
|
setRawJob({
|
||||||
|
running: true,
|
||||||
|
done: 0,
|
||||||
|
total: targets.length,
|
||||||
|
current: targets[0].name,
|
||||||
|
eventName: options.eventName,
|
||||||
|
failures: [],
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
for (let index = 0; index < targets.length; index += 1) {
|
||||||
|
if (rawCancelRef.current) break;
|
||||||
|
const photo = targets[index];
|
||||||
|
setRawJob((prev) =>
|
||||||
|
prev ? { ...prev, done: index, current: photo.name, failures: failures.slice() } : prev,
|
||||||
|
);
|
||||||
|
try {
|
||||||
|
const result = await reprocessRawPhoto(photo.id);
|
||||||
|
const res = await fetch(
|
||||||
|
`/api/photos/${encodeURIComponent(photo.id)}/preview?v=${Date.now()}`,
|
||||||
|
{ credentials: 'same-origin' },
|
||||||
|
);
|
||||||
|
if (!res.ok) throw new Error('The new preview could not be read');
|
||||||
|
const blob = await res.blob();
|
||||||
|
// Replace the cached proxy, then drop the decoded bitmap so the next
|
||||||
|
// render fetches the new pixels instead of the old ones.
|
||||||
|
await putAsset(photo.id, blob);
|
||||||
|
evictBitmap(photo.id);
|
||||||
|
const version = result.previewVersion ?? Date.now();
|
||||||
|
updatePhoto(photo.id, {
|
||||||
|
width: result.width || photo.width,
|
||||||
|
height: result.height || photo.height,
|
||||||
|
decode: result.engine ?? photo.decode,
|
||||||
|
previewVersion: version,
|
||||||
|
// The stored files keep their names; the query is only a cache buster.
|
||||||
|
previewUrl:
|
||||||
|
result.previewUrl ??
|
||||||
|
`/api/photos/${encodeURIComponent(photo.id)}/preview?v=${version}`,
|
||||||
|
thumbUrl:
|
||||||
|
result.thumbUrl ??
|
||||||
|
`/api/photos/${encodeURIComponent(photo.id)}/thumb?v=${version}`,
|
||||||
|
});
|
||||||
|
attempts += 1;
|
||||||
|
} catch (err) {
|
||||||
|
failures.push({
|
||||||
|
name: photo.name,
|
||||||
|
error: err instanceof Error ? err.message : 'could not be reprocessed',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
setRawJob((prev) =>
|
||||||
|
prev
|
||||||
|
? { ...prev, done: index + 1, failures: failures.slice() }
|
||||||
|
: prev,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
rawBusyRef.current = false;
|
||||||
|
setRawJob((prev) =>
|
||||||
|
prev
|
||||||
|
? {
|
||||||
|
...prev,
|
||||||
|
running: false,
|
||||||
|
done: attempts,
|
||||||
|
failures: failures.slice(),
|
||||||
|
cancelled: rawCancelRef.current,
|
||||||
|
}
|
||||||
|
: prev,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const succeeded = attempts - failures.length;
|
||||||
|
const parts = [
|
||||||
|
`Reprocessed ${succeeded} of ${targets.length} RAW${targets.length === 1 ? '' : 's'}`,
|
||||||
|
];
|
||||||
|
if (failures.length) parts.push(`${failures.length} failed`);
|
||||||
|
if (rawCancelRef.current) parts.push('cancelled');
|
||||||
|
setToast(parts.join(' · '));
|
||||||
|
},
|
||||||
|
[updatePhoto],
|
||||||
|
);
|
||||||
|
|
||||||
|
/** Reprocess every RAW file in one event, with a confirmation that names it. */
|
||||||
|
const reprocessEventRaws = useCallback(
|
||||||
|
(id: string) => {
|
||||||
|
const event = eventsRef.current.find((item) => item.id === id);
|
||||||
|
if (!event) return;
|
||||||
|
const raws = photosRef.current.filter(
|
||||||
|
(photo) => photo.eventId === id && photo.raw && !photo.deletedAt,
|
||||||
|
);
|
||||||
|
if (!raws.length) {
|
||||||
|
setToast('This event has no RAW photos');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!userRef.current) {
|
||||||
|
setToast('Sign in to the server to reprocess RAW files');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (rawBusyRef.current) {
|
||||||
|
setToast('A RAW reprocess is already running');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const ok = window.confirm(
|
||||||
|
`Re-decode ${raws.length} RAW file${raws.length === 1 ? '' : 's'} in “${event.name}”? ` +
|
||||||
|
'Existing edits and crops are kept.',
|
||||||
|
);
|
||||||
|
if (!ok) return;
|
||||||
|
void reprocessRawPhotos(raws.map((photo) => photo.id), { eventName: event.name });
|
||||||
|
},
|
||||||
|
[reprocessRawPhotos],
|
||||||
|
);
|
||||||
|
|
||||||
|
/** Auto-sync in Develop: merge the same patch into every selected photo. */
|
||||||
|
const updatePhotoEdits = useCallback(
|
||||||
|
(ids: string[], patch: Partial<Edits>, historyLabel?: string) => {
|
||||||
|
for (const id of ids) {
|
||||||
|
updatePhoto(id, (p) => ({ edits: { ...p.edits, ...patch } }), historyLabel);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[updatePhoto],
|
||||||
|
);
|
||||||
|
|
||||||
const bulkUpdate = useCallback(
|
const bulkUpdate = useCallback(
|
||||||
(ids: string[], patch: Partial<PhotoRecord>) => {
|
(ids: string[], patch: Partial<PhotoRecord>) => {
|
||||||
if (!ids.length) return;
|
if (!ids.length) return;
|
||||||
@@ -337,6 +539,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 +687,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) => {
|
||||||
@@ -780,7 +1029,9 @@ export default function App() {
|
|||||||
|
|
||||||
const savePreset = useCallback(
|
const savePreset = useCallback(
|
||||||
(name: string, edits: Edits) => {
|
(name: string, edits: Edits) => {
|
||||||
const { crop: _crop, ...withoutCrop } = edits;
|
// Crop and the camera profile are properties of this photo, not a look:
|
||||||
|
// copying either onto another body would be wrong.
|
||||||
|
const { crop: _crop, cameraProfile: _cameraProfile, ...withoutCrop } = edits;
|
||||||
const preset: Preset = {
|
const preset: Preset = {
|
||||||
id: uid(),
|
id: uid(),
|
||||||
name,
|
name,
|
||||||
@@ -799,6 +1050,19 @@ export default function App() {
|
|||||||
[customPresets],
|
[customPresets],
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const deletePreset = useCallback(
|
||||||
|
(id: string) => {
|
||||||
|
const next = customPresets.filter((preset) => preset.id !== id);
|
||||||
|
setCustomPresets(next);
|
||||||
|
setKV('customPresets', next).catch((err) => console.error(err));
|
||||||
|
if (userRef.current) {
|
||||||
|
import('./lib/api').then(({ pushPresets }) => pushPresets(next).catch(() => undefined));
|
||||||
|
}
|
||||||
|
setToast('Preset deleted');
|
||||||
|
},
|
||||||
|
[customPresets],
|
||||||
|
);
|
||||||
|
|
||||||
/* ------------------------------------------------------------- reordering */
|
/* ------------------------------------------------------------- reordering */
|
||||||
|
|
||||||
const reorderPhotos = useCallback(
|
const reorderPhotos = useCallback(
|
||||||
@@ -1236,6 +1500,203 @@ 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);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Manual publish for an event that has no Immich gallery yet: create the
|
||||||
|
* album, link it to the event, then push originals and current edits.
|
||||||
|
*/
|
||||||
|
const publishEventToImmich = useCallback(
|
||||||
|
async (targetEventId: string) => {
|
||||||
|
const event = eventsRef.current.find((item) => item.id === targetEventId);
|
||||||
|
if (!event) return;
|
||||||
|
if (!immichStatusRef.current?.enabled) {
|
||||||
|
setToast('Turn on Immich in the Immich sync panel first');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (event.immich) {
|
||||||
|
await syncEventGallery(targetEventId);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await createImmichGalleryForEvent(targetEventId);
|
||||||
|
} catch (err) {
|
||||||
|
setToast(err instanceof Error ? err.message : 'Could not create the Immich gallery');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const count = photosRef.current.filter(
|
||||||
|
(photo) => photo.eventId === targetEventId && !photo.deletedAt,
|
||||||
|
).length;
|
||||||
|
if (!count) {
|
||||||
|
setToast(`Immich gallery created for ${event.name} — import photos to fill it`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await syncEventGallery(targetEventId);
|
||||||
|
},
|
||||||
|
[createImmichGalleryForEvent, syncEventGallery],
|
||||||
|
);
|
||||||
|
|
||||||
|
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);
|
||||||
@@ -1439,6 +1900,7 @@ export default function App() {
|
|||||||
mod &&
|
mod &&
|
||||||
k === 'k' &&
|
k === 'k' &&
|
||||||
!helpOpen &&
|
!helpOpen &&
|
||||||
|
!aboutOpen &&
|
||||||
!importOpen &&
|
!importOpen &&
|
||||||
!exportOpen &&
|
!exportOpen &&
|
||||||
!cloudOpen &&
|
!cloudOpen &&
|
||||||
@@ -1457,7 +1919,7 @@ export default function App() {
|
|||||||
setHelpOpen((v) => !v);
|
setHelpOpen((v) => !v);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (helpOpen || importOpen || exportOpen || cloudOpen || adminOpen || compareOpen) return;
|
if (helpOpen || aboutOpen || importOpen || exportOpen || cloudOpen || adminOpen || compareOpen) return;
|
||||||
|
|
||||||
if (mod && k === 'i') {
|
if (mod && k === 'i') {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
@@ -1603,7 +2065,94 @@ export default function App() {
|
|||||||
? 'Unsorted'
|
? 'Unsorted'
|
||||||
: events.find((e) => e.id === eventId)?.name ?? 'All photos';
|
: events.find((e) => e.id === eventId)?.name ?? 'All photos';
|
||||||
|
|
||||||
|
const tetherImport = useCallback(
|
||||||
|
async (files: File[]) => {
|
||||||
|
if (!tetherEventId) return 0;
|
||||||
|
const result = await importFiles(
|
||||||
|
files,
|
||||||
|
tetherEventId,
|
||||||
|
[],
|
||||||
|
undefined,
|
||||||
|
cloudUser ? { uploadOriginal, push: pushPhoto } : null,
|
||||||
|
);
|
||||||
|
if (result.photos.length) {
|
||||||
|
const tagged = result.photos.map((photo) =>
|
||||||
|
cloudUser ? { ...photo, workspace: cloudUser.id } : photo,
|
||||||
|
);
|
||||||
|
setPhotos((prev) => [...tagged, ...prev]);
|
||||||
|
}
|
||||||
|
return result.photos.length;
|
||||||
|
},
|
||||||
|
[cloudUser, tetherEventId],
|
||||||
|
);
|
||||||
|
|
||||||
|
const importSidecar = useCallback(async () => {
|
||||||
|
if (selected.length !== 1) {
|
||||||
|
setToast('Select exactly one photo to import a sidecar into');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const target = photos.find((photo) => photo.id === selected[0]);
|
||||||
|
if (!target) return;
|
||||||
|
try {
|
||||||
|
const xml = await readXmpFile();
|
||||||
|
if (!xml) return;
|
||||||
|
const result = xmpToEdits(xml, target.edits);
|
||||||
|
updatePhoto(target.id, { edits: result.edits }, 'Import XMP sidecar');
|
||||||
|
setToast(
|
||||||
|
result.source === 'luminary'
|
||||||
|
? 'Imported Luminary settings from the sidecar'
|
||||||
|
: `Imported ${result.applied.length} Lightroom setting${result.applied.length === 1 ? '' : 's'}`,
|
||||||
|
);
|
||||||
|
} catch (err) {
|
||||||
|
setToast(err instanceof Error ? err.message : 'Could not import the sidecar');
|
||||||
|
}
|
||||||
|
}, [photos, selected, updatePhoto]);
|
||||||
|
|
||||||
const paletteActions = [
|
const paletteActions = [
|
||||||
|
{
|
||||||
|
id: 'xmp-export',
|
||||||
|
label: 'Export XMP sidecar for the selection',
|
||||||
|
hint: 'Sidecar',
|
||||||
|
run: () => {
|
||||||
|
const chosen = photos.filter((photo) => selected.includes(photo.id));
|
||||||
|
if (!chosen.length) {
|
||||||
|
setToast('Select photos to export sidecars for');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (const photo of chosen) downloadXmp(photo);
|
||||||
|
setToast(`Exported ${chosen.length} sidecar${chosen.length === 1 ? '' : 's'}`);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'xmp-import',
|
||||||
|
label: 'Import XMP sidecar into the selected photo',
|
||||||
|
hint: 'Sidecar',
|
||||||
|
run: () => void importSidecar(),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'tether',
|
||||||
|
label: 'Tether this event from a watch folder',
|
||||||
|
hint: 'Capture',
|
||||||
|
run: () => {
|
||||||
|
if (eventId === 'all' || eventId === 'unsorted') {
|
||||||
|
setToast('Open an event to tether into it');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setTetherEventId(eventId);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'cull-assist',
|
||||||
|
label: 'Cull assist for the selection',
|
||||||
|
hint: 'Focus',
|
||||||
|
run: () => {
|
||||||
|
if (!selected.length) {
|
||||||
|
setToast('Select photos to cull');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setCullOpen(true);
|
||||||
|
},
|
||||||
|
},
|
||||||
{
|
{
|
||||||
id: 'import',
|
id: 'import',
|
||||||
label: 'Import photos',
|
label: 'Import photos',
|
||||||
@@ -1638,6 +2187,29 @@ export default function App() {
|
|||||||
run: () => setFilters(EMPTY_FILTERS),
|
run: () => setFilters(EMPTY_FILTERS),
|
||||||
},
|
},
|
||||||
{ id: 'shortcuts', label: 'Show keyboard shortcuts', hint: '?', run: () => setHelpOpen(true) },
|
{ id: 'shortcuts', label: 'Show keyboard shortcuts', hint: '?', run: () => setHelpOpen(true) },
|
||||||
|
...(cloudUser &&
|
||||||
|
eventId !== 'all' &&
|
||||||
|
eventId !== 'unsorted' &&
|
||||||
|
photos.some((photo) => photo.eventId === eventId && photo.raw && !photo.deletedAt)
|
||||||
|
? [
|
||||||
|
{
|
||||||
|
id: 'reprocess-event-raws',
|
||||||
|
label: 'Reprocess all RAW photos in this event',
|
||||||
|
hint: 'RAW',
|
||||||
|
run: () => reprocessEventRaws(eventId),
|
||||||
|
},
|
||||||
|
]
|
||||||
|
: []),
|
||||||
|
...(cloudUser && immichStatus?.enabled && eventId !== 'all' && eventId !== 'unsorted'
|
||||||
|
? [
|
||||||
|
{
|
||||||
|
id: 'immich-publish',
|
||||||
|
label: 'Publish this event to Immich',
|
||||||
|
hint: 'Immich',
|
||||||
|
run: () => void publishEventToImmich(eventId),
|
||||||
|
},
|
||||||
|
]
|
||||||
|
: []),
|
||||||
...(cloudUser && eventId !== 'all' && eventId !== 'unsorted'
|
...(cloudUser && eventId !== 'all' && eventId !== 'unsorted'
|
||||||
? [{ id: 'share', label: 'Open client proofing', hint: 'Share', run: () => setShareEventId(eventId) }]
|
? [{ id: 'share', label: 'Open client proofing', hint: 'Share', run: () => setShareEventId(eventId) }]
|
||||||
: []),
|
: []),
|
||||||
@@ -1652,6 +2224,11 @@ export default function App() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The Windows desktop bundle runs as one local admin (LUMINARY_LOCAL=1).
|
||||||
|
// Accounts and team administration have nothing to manage there, so both
|
||||||
|
// panels and the entry point to them stay out of the UI.
|
||||||
|
const localMode = cloudHealth?.local === true;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="app">
|
<div className="app">
|
||||||
<TopBar
|
<TopBar
|
||||||
@@ -1661,6 +2238,7 @@ export default function App() {
|
|||||||
selectedCount={selected.length}
|
selectedCount={selected.length}
|
||||||
cloudLabel={cloudUser ? cloudUser.name || cloudUser.email : cloudHealth ? 'Sign in' : 'Local only'}
|
cloudLabel={cloudUser ? cloudUser.name || cloudUser.email : cloudHealth ? 'Sign in' : 'Local only'}
|
||||||
cloudOn={!!cloudUser}
|
cloudOn={!!cloudUser}
|
||||||
|
localMode={localMode}
|
||||||
onViewChange={(v) => {
|
onViewChange={(v) => {
|
||||||
setCatalogOpen(false);
|
setCatalogOpen(false);
|
||||||
if (v === 'develop' && !activePhoto) {
|
if (v === 'develop' && !activePhoto) {
|
||||||
@@ -1679,6 +2257,7 @@ export default function App() {
|
|||||||
setCloudOpen(true);
|
setCloudOpen(true);
|
||||||
}}
|
}}
|
||||||
onHelp={() => setHelpOpen(true)}
|
onHelp={() => setHelpOpen(true)}
|
||||||
|
onAbout={() => setAboutOpen(true)}
|
||||||
onSearch={() => setSearchOpen(true)}
|
onSearch={() => setSearchOpen(true)}
|
||||||
onCatalog={() => {
|
onCatalog={() => {
|
||||||
setView('grid');
|
setView('grid');
|
||||||
@@ -1754,9 +2333,14 @@ 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}
|
||||||
|
onPublishGallery={publishEventToImmich}
|
||||||
|
canReprocessRaw={Boolean(cloudUser)}
|
||||||
|
onReprocessEvent={reprocessEventRaws}
|
||||||
onRename={renameEvent}
|
onRename={renameEvent}
|
||||||
onDelete={removeEvent}
|
onDelete={removeEvent}
|
||||||
onReorderEvents={reorderEvents}
|
onReorderEvents={reorderEvents}
|
||||||
@@ -1855,6 +2439,21 @@ 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)}
|
||||||
|
onReprocessRaw={
|
||||||
|
cloudUser && selected.some((id) => photos.find((photo) => photo.id === id)?.raw)
|
||||||
|
? () => void reprocessRawPhotos(selected)
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
|
reprocessBusy={rawBusy}
|
||||||
onDelete={() => (trashOpen ? void removePhotos(selected) : trashPhotos(selected))}
|
onDelete={() => (trashOpen ? void removePhotos(selected) : trashPhotos(selected))}
|
||||||
onExport={openExport}
|
onExport={openExport}
|
||||||
onCompare={() => setCompareOpen(true)}
|
onCompare={() => setCompareOpen(true)}
|
||||||
@@ -1892,15 +2491,24 @@ export default function App() {
|
|||||||
onSelect={setActiveId}
|
onSelect={setActiveId}
|
||||||
onExit={() => setView('grid')}
|
onExit={() => setView('grid')}
|
||||||
onUpdate={updatePhoto}
|
onUpdate={updatePhoto}
|
||||||
|
onUpdateEdits={updatePhotoEdits}
|
||||||
clipboard={clipboard}
|
clipboard={clipboard}
|
||||||
onCopy={copySettings}
|
onCopy={copySettings}
|
||||||
onPaste={() => openPaste([activePhoto.id])}
|
onCopyOf={copySettingsOf}
|
||||||
|
onPaste={(ids) => openPaste(ids?.length ? ids : [activePhoto.id])}
|
||||||
|
onResetSelection={resetEdits}
|
||||||
localClipboard={localClipboard}
|
localClipboard={localClipboard}
|
||||||
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}
|
||||||
|
onDeletePreset={deletePreset}
|
||||||
onDelete={() => trashPhotos([activePhoto.id])}
|
onDelete={() => trashPhotos([activePhoto.id])}
|
||||||
onVirtualCopy={() => void createVirtualCopy(activePhoto.id, true)}
|
onVirtualCopy={() => void createVirtualCopy(activePhoto.id, true)}
|
||||||
metadataPresets={metadataPresets}
|
metadataPresets={metadataPresets}
|
||||||
@@ -1949,6 +2557,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}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
@@ -2005,6 +2615,7 @@ export default function App() {
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{helpOpen && <Shortcuts onClose={() => setHelpOpen(false)} />}
|
{helpOpen && <Shortcuts onClose={() => setHelpOpen(false)} />}
|
||||||
|
{aboutOpen && <AboutModal onClose={() => setAboutOpen(false)} />}
|
||||||
|
|
||||||
{searchOpen && (
|
{searchOpen && (
|
||||||
<CommandPalette
|
<CommandPalette
|
||||||
@@ -2046,7 +2657,7 @@ export default function App() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{cloudOpen && (
|
{cloudOpen && !localMode && (
|
||||||
<CloudPanel
|
<CloudPanel
|
||||||
health={cloudHealth}
|
health={cloudHealth}
|
||||||
user={cloudUser}
|
user={cloudUser}
|
||||||
@@ -2061,21 +2672,37 @@ export default function App() {
|
|||||||
setCloudOpen(false);
|
setCloudOpen(false);
|
||||||
setAdminOpen(true);
|
setAdminOpen(true);
|
||||||
}}
|
}}
|
||||||
|
onImmich={() => {
|
||||||
|
setCloudOpen(false);
|
||||||
|
setImmichOpen(true);
|
||||||
|
}}
|
||||||
onClose={() => setCloudOpen(false)}
|
onClose={() => setCloudOpen(false)}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{adminOpen && cloudUser && (
|
{adminOpen && cloudUser && !localMode && (
|
||||||
<AdminPanel
|
<AdminPanel
|
||||||
user={cloudUser}
|
user={cloudUser}
|
||||||
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 +2760,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 +2810,55 @@ 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>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{tetherEventId && (
|
||||||
|
<TetherPanel
|
||||||
|
event={{
|
||||||
|
id: tetherEventId,
|
||||||
|
name: events.find((e) => e.id === tetherEventId)?.name ?? 'this event',
|
||||||
|
}}
|
||||||
|
onImport={tetherImport}
|
||||||
|
onClose={() => setTetherEventId(null)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{cullOpen && (
|
||||||
|
<CullAssistModal
|
||||||
|
photos={photos.filter((photo) => selected.includes(photo.id))}
|
||||||
|
onReject={(ids) => bulkUpdate(ids, { flag: 'reject' })}
|
||||||
|
onClose={() => setCullOpen(false)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{rawJob && (
|
||||||
|
<RawReprocessModal
|
||||||
|
job={rawJob}
|
||||||
|
onCancel={() => {
|
||||||
|
rawCancelRef.current = true;
|
||||||
|
setRawJob((prev) => (prev ? { ...prev, cancelled: true } : prev));
|
||||||
|
}}
|
||||||
|
onClose={() => setRawJob(null)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
{toast && (
|
{toast && (
|
||||||
<div className="toast">
|
<div className="toast">
|
||||||
<span>{toast}</span>
|
<span>{toast}</span>
|
||||||
|
|||||||
@@ -0,0 +1,68 @@
|
|||||||
|
import { useEffect } from 'react';
|
||||||
|
import { APP_VERSION, GUIDE_UPDATED, GUIDE_VERSION } from '../lib/about';
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
onClose: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function AboutModal({ onClose }: Props) {
|
||||||
|
useEffect(() => {
|
||||||
|
const onKey = (e: KeyboardEvent) => {
|
||||||
|
if (e.key === 'Escape') onClose();
|
||||||
|
};
|
||||||
|
window.addEventListener('keydown', onKey);
|
||||||
|
return () => window.removeEventListener('keydown', onKey);
|
||||||
|
}, [onClose]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className="modal-backdrop"
|
||||||
|
onPointerDown={(e) => e.target === e.currentTarget && onClose()}
|
||||||
|
>
|
||||||
|
<div className="modal about-modal" role="dialog" aria-label="About Luminary">
|
||||||
|
<header className="modal-head">
|
||||||
|
<h2>About Luminary</h2>
|
||||||
|
<button className="icon-btn" onClick={onClose} aria-label="Close">
|
||||||
|
✕
|
||||||
|
</button>
|
||||||
|
</header>
|
||||||
|
<div className="modal-body">
|
||||||
|
<div className="about-brand">
|
||||||
|
<img src="/logo.png" alt="" height={28} />
|
||||||
|
<div>
|
||||||
|
<strong>Luminary</strong>
|
||||||
|
<div className="muted small">Version {APP_VERSION} · Beta</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<dl className="cloud-stats about-facts">
|
||||||
|
<div>
|
||||||
|
<dt>User guide</dt>
|
||||||
|
<dd>Version {GUIDE_VERSION}</dd>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<dt>Guide updated</dt>
|
||||||
|
<dd>{GUIDE_UPDATED}</dd>
|
||||||
|
</div>
|
||||||
|
</dl>
|
||||||
|
<p className="muted small">
|
||||||
|
The guide covers every screen, panel and setting, with server, Docker and
|
||||||
|
Windows install instructions. Its screenshots are taken from a live catalog.
|
||||||
|
</p>
|
||||||
|
<div className="btn-row">
|
||||||
|
<a
|
||||||
|
className="btn primary"
|
||||||
|
href="/luminary-user-guide.pdf"
|
||||||
|
target="_blank"
|
||||||
|
rel="noreferrer"
|
||||||
|
>
|
||||||
|
Open user guide (PDF)
|
||||||
|
</a>
|
||||||
|
<button className="btn ghost" onClick={onClose}>
|
||||||
|
Close
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -6,6 +6,7 @@ import type {
|
|||||||
AdminUser,
|
AdminUser,
|
||||||
CatalogBackup,
|
CatalogBackup,
|
||||||
MailStatus,
|
MailStatus,
|
||||||
|
PreviewRebuildStatus,
|
||||||
SessionUser,
|
SessionUser,
|
||||||
StorageChange,
|
StorageChange,
|
||||||
} from '../lib/api';
|
} from '../lib/api';
|
||||||
@@ -15,14 +16,19 @@ import {
|
|||||||
adminCreateUser,
|
adminCreateUser,
|
||||||
adminDeleteEvent,
|
adminDeleteEvent,
|
||||||
adminDeleteUser,
|
adminDeleteUser,
|
||||||
|
adminDisconnectImmich,
|
||||||
adminRestoreCatalog,
|
adminRestoreCatalog,
|
||||||
adminRevokeInvite,
|
adminRevokeInvite,
|
||||||
adminOverview,
|
adminOverview,
|
||||||
|
adminPreviewRebuildStatus,
|
||||||
|
adminRebuildPreviews,
|
||||||
adminRenameEvent,
|
adminRenameEvent,
|
||||||
|
adminSaveImmich,
|
||||||
adminSaveMail,
|
adminSaveMail,
|
||||||
adminSchedulePrune,
|
adminSchedulePrune,
|
||||||
adminSetQuota,
|
adminSetQuota,
|
||||||
adminSetStorage,
|
adminSetStorage,
|
||||||
|
adminTestImmich,
|
||||||
adminTestMail,
|
adminTestMail,
|
||||||
adminUpdateUser,
|
adminUpdateUser,
|
||||||
adminWarnUser,
|
adminWarnUser,
|
||||||
@@ -68,7 +74,19 @@ 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';
|
||||||
|
|
||||||
|
/** No rebuild has run in this process yet. */
|
||||||
|
const idleRebuild: PreviewRebuildStatus = {
|
||||||
|
state: 'idle',
|
||||||
|
total: 0,
|
||||||
|
done: 0,
|
||||||
|
failed: 0,
|
||||||
|
sidecars: 0,
|
||||||
|
startedAt: null,
|
||||||
|
finishedAt: null,
|
||||||
|
errors: [],
|
||||||
|
};
|
||||||
|
|
||||||
const inviteUrl = (token: string) => `${window.location.origin}/join/${token}`;
|
const inviteUrl = (token: string) => `${window.location.origin}/join/${token}`;
|
||||||
|
|
||||||
@@ -106,12 +124,61 @@ export default function AdminPanel({ user, onClose, onChanged, onRestored }: Pro
|
|||||||
|
|
||||||
const [rootInput, setRootInput] = useState('');
|
const [rootInput, setRootInput] = useState('');
|
||||||
const [change, setChange] = useState<StorageChange | null>(null);
|
const [change, setChange] = useState<StorageChange | null>(null);
|
||||||
|
const [rebuild, setRebuild] = useState<PreviewRebuildStatus>(idleRebuild);
|
||||||
|
const [rebuildBusy, setRebuildBusy] = useState(false);
|
||||||
const restoreInput = useRef<HTMLInputElement>(null);
|
const restoreInput = useRef<HTMLInputElement>(null);
|
||||||
const [restoreNote, setRestoreNote] = useState<string | null>(null);
|
const [restoreNote, setRestoreNote] = useState<string | null>(null);
|
||||||
|
|
||||||
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 });
|
||||||
|
|
||||||
|
// The rebuild runs inside the server, so the panel reads its progress instead
|
||||||
|
// of holding the work: closing the modal does not stop it, and reopening the
|
||||||
|
// tab picks up a run that is already in flight.
|
||||||
|
useEffect(() => {
|
||||||
|
if (tab !== 'storage') return;
|
||||||
|
let alive = true;
|
||||||
|
adminPreviewRebuildStatus()
|
||||||
|
.then((next) => {
|
||||||
|
if (alive) setRebuild(next);
|
||||||
|
})
|
||||||
|
.catch(() => undefined);
|
||||||
|
return () => {
|
||||||
|
alive = false;
|
||||||
|
};
|
||||||
|
}, [tab]);
|
||||||
|
|
||||||
|
const rebuildRunning = rebuild.state === 'running';
|
||||||
|
useEffect(() => {
|
||||||
|
if (tab !== 'storage' || !rebuildRunning) return;
|
||||||
|
const timer = setInterval(() => {
|
||||||
|
adminPreviewRebuildStatus()
|
||||||
|
.then(setRebuild)
|
||||||
|
.catch(() => undefined);
|
||||||
|
}, 2000);
|
||||||
|
return () => clearInterval(timer);
|
||||||
|
}, [tab, rebuildRunning]);
|
||||||
|
|
||||||
|
const rebuildPreviews = async () => {
|
||||||
|
setRebuildBusy(true);
|
||||||
|
setError(null);
|
||||||
|
setNote(null);
|
||||||
|
try {
|
||||||
|
const started = await adminRebuildPreviews();
|
||||||
|
setRebuild(started);
|
||||||
|
setNote(
|
||||||
|
started.state === 'done'
|
||||||
|
? 'Nothing to rebuild: every camera raw is a JPEG-only import'
|
||||||
|
: `Rebuilding ${started.total} preview proxies`,
|
||||||
|
);
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : 'Could not rebuild the previews');
|
||||||
|
} finally {
|
||||||
|
setRebuildBusy(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const restoreCatalog = async (file: File | undefined) => {
|
const restoreCatalog = async (file: File | undefined) => {
|
||||||
if (!file || busy) return;
|
if (!file || busy) return;
|
||||||
@@ -161,6 +228,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 +246,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 +424,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 +519,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 +1044,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>
|
||||||
@@ -1030,6 +1250,47 @@ export default function AdminPanel({ user, onClose, onChanged, onRestored }: Pro
|
|||||||
container first (for example <code>-v /photos:/photos</code>), then use that container path.
|
container first (for example <code>-v /photos:/photos</code>), then use that container path.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<h3>Preview proxies</h3>
|
||||||
|
<p className="muted small">
|
||||||
|
Re-decode every camera raw from its original and replace its JPEG proxy, grid thumbnail
|
||||||
|
and 16-bit sidecar. Run this after a change to the raw pipeline: edits, ratings and
|
||||||
|
events are kept, and the originals are never modified.
|
||||||
|
</p>
|
||||||
|
<div className="btn-row">
|
||||||
|
<button
|
||||||
|
className="btn primary"
|
||||||
|
onClick={() => void rebuildPreviews()}
|
||||||
|
disabled={busy || rebuildBusy || rebuildRunning || rebuild.total === 0}
|
||||||
|
title={
|
||||||
|
rebuild.total === 0 && rebuild.state === 'done'
|
||||||
|
? 'The last rebuild found no camera raws to process'
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{rebuildRunning
|
||||||
|
? `Rebuilding ${rebuild.done} / ${rebuild.total}…`
|
||||||
|
: rebuildBusy
|
||||||
|
? 'Starting…'
|
||||||
|
: 'Rebuild previews'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{rebuildRunning && (
|
||||||
|
<p className="muted small">
|
||||||
|
{rebuild.done} of {rebuild.total} raws rebuilt
|
||||||
|
{rebuild.failed ? ` · ${rebuild.failed} failed` : ''} · the server keeps going when
|
||||||
|
this panel closes.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{rebuild.state === 'done' && (
|
||||||
|
<p className="muted small">
|
||||||
|
Rebuilt {rebuild.done - rebuild.failed} of {rebuild.total} raws
|
||||||
|
{rebuild.sidecars ? `, ${rebuild.sidecars} with a 16-bit sidecar` : ''}
|
||||||
|
{rebuild.failed ? ` · ${rebuild.failed} failed` : ''}.
|
||||||
|
{rebuild.errors.length > 0 ? ` First failure: ${rebuild.errors[0]}` : ''}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
</section>
|
</section>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
|||||||
@@ -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>
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
import { useEffect, useRef, useState } from 'react';
|
import { useEffect, useRef, useState } from 'react';
|
||||||
import { getBitmap } from '../lib/images';
|
import { get16BitSource, getBitmap } from '../lib/images';
|
||||||
|
import type { Preview16 } from '../lib/preview16';
|
||||||
import { rotatedBounds, Renderer } from '../gl/renderer';
|
import { rotatedBounds, Renderer } from '../gl/renderer';
|
||||||
import { buildLensCorrection, type LensCorrection } from '../lib/lensfun';
|
import { buildLensCorrection, type LensCorrection } from '../lib/lensEngine';
|
||||||
import type { PhotoRecord } from '../types';
|
import type { PhotoRecord } from '../types';
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
@@ -15,6 +16,7 @@ function CompareTile({ photo, onOpen }: { photo: PhotoRecord; onOpen: (id: strin
|
|||||||
const boxRef = useRef<HTMLDivElement>(null);
|
const boxRef = useRef<HTMLDivElement>(null);
|
||||||
const rendererRef = useRef<Renderer | null>(null);
|
const rendererRef = useRef<Renderer | null>(null);
|
||||||
const [bitmap, setBitmap] = useState<ImageBitmap | null>(null);
|
const [bitmap, setBitmap] = useState<ImageBitmap | null>(null);
|
||||||
|
const [hdr, setHdr] = useState<Preview16 | null>(null);
|
||||||
const [box, setBox] = useState({ w: 0, h: 0 });
|
const [box, setBox] = useState({ w: 0, h: 0 });
|
||||||
const [lensCorrection, setLensCorrection] = useState<LensCorrection | null>(null);
|
const [lensCorrection, setLensCorrection] = useState<LensCorrection | null>(null);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
@@ -29,6 +31,23 @@ function CompareTile({ photo, onOpen }: { photo: PhotoRecord; onOpen: (id: strin
|
|||||||
};
|
};
|
||||||
}, [photo]);
|
}, [photo]);
|
||||||
|
|
||||||
|
// Compare renders the full proxy, so the matching 16-bit sidecar is what lets
|
||||||
|
// a per-photo camera profile show here exactly as it does in Develop. Without
|
||||||
|
// a profile the JPEG already carries the body matrix, so skip the big fetch.
|
||||||
|
useEffect(() => {
|
||||||
|
let alive = true;
|
||||||
|
if (!photo.edits.cameraProfile) {
|
||||||
|
setHdr(null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
get16BitSource(photo)
|
||||||
|
.then((next) => alive && setHdr(next))
|
||||||
|
.catch(() => alive && setHdr(null));
|
||||||
|
return () => {
|
||||||
|
alive = false;
|
||||||
|
};
|
||||||
|
}, [photo]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let alive = true;
|
let alive = true;
|
||||||
if (!photo.edits.lens || !bitmap) {
|
if (!photo.edits.lens || !bitmap) {
|
||||||
@@ -98,14 +117,14 @@ function CompareTile({ photo, onOpen }: { photo: PhotoRecord; onOpen: (id: strin
|
|||||||
lens: lensCorrection,
|
lens: lensCorrection,
|
||||||
};
|
};
|
||||||
try {
|
try {
|
||||||
renderer.setImage(bitmap);
|
renderer.setImage(bitmap, hdr);
|
||||||
renderer.render(photo.edits, opts);
|
renderer.render(photo.edits, opts);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setError(err instanceof Error ? err.message : 'Rendering failed');
|
setError(err instanceof Error ? err.message : 'Rendering failed');
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
return () => cancelAnimationFrame(raf);
|
return () => cancelAnimationFrame(raf);
|
||||||
}, [bitmap, box, photo, lensCorrection]);
|
}, [bitmap, box, photo, lensCorrection, hdr]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<figure className="compare-tile" onDoubleClick={() => onOpen(photo.id)}>
|
<figure className="compare-tile" onDoubleClick={() => onOpen(photo.id)}>
|
||||||
|
|||||||
@@ -0,0 +1,248 @@
|
|||||||
|
import { useEffect, useMemo, useState } from 'react';
|
||||||
|
import { analyseGrey, greyFromPixels, groupDuplicates, sharpnessGrade } from '../lib/cull';
|
||||||
|
import type { CullStats } from '../lib/cull';
|
||||||
|
import type { PhotoRecord } from '../types';
|
||||||
|
|
||||||
|
interface Row {
|
||||||
|
photo: PhotoRecord;
|
||||||
|
stats: CullStats | null;
|
||||||
|
error?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
photos: PhotoRecord[];
|
||||||
|
onReject: (ids: string[]) => void;
|
||||||
|
onClose: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const THUMB_EDGE = 96;
|
||||||
|
|
||||||
|
async function statsFor(photo: PhotoRecord): Promise<CullStats> {
|
||||||
|
const src = photo.thumbUrl ?? photo.thumb;
|
||||||
|
const image = new Image();
|
||||||
|
image.decoding = 'async';
|
||||||
|
await new Promise<void>((resolve, reject) => {
|
||||||
|
image.onload = () => resolve();
|
||||||
|
image.onerror = () => reject(new Error('Could not read the thumbnail'));
|
||||||
|
image.src = src;
|
||||||
|
});
|
||||||
|
const width = THUMB_EDGE;
|
||||||
|
const height = Math.max(24, Math.round((width * image.naturalHeight) / Math.max(1, image.naturalWidth)));
|
||||||
|
const canvas = document.createElement('canvas');
|
||||||
|
canvas.width = width;
|
||||||
|
canvas.height = height;
|
||||||
|
const ctx = canvas.getContext('2d', { willReadFrequently: true });
|
||||||
|
if (!ctx) throw new Error('Could not analyse the thumbnail');
|
||||||
|
ctx.drawImage(image, 0, 0, width, height);
|
||||||
|
return analyseGrey(greyFromPixels(ctx.getImageData(0, 0, width, height).data), width, height);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Focus and duplicate pass over a selection, run on the thumbnails the grid
|
||||||
|
* already loaded. It never edits or rates anything by itself: the owner sees
|
||||||
|
* the scores and chooses what to reject.
|
||||||
|
*/
|
||||||
|
export default function CullAssistModal({ photos, onReject, onClose }: Props) {
|
||||||
|
const [rows, setRows] = useState<Row[]>([]);
|
||||||
|
const [done, setDone] = useState(0);
|
||||||
|
const [running, setRunning] = useState(true);
|
||||||
|
const [current, setCurrent] = useState('');
|
||||||
|
const [threshold, setThreshold] = useState(22);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let cancelled = false;
|
||||||
|
const next: Row[] = photos.map((photo) => ({ photo, stats: null }));
|
||||||
|
setRows(next.map((row) => ({ ...row })));
|
||||||
|
setDone(0);
|
||||||
|
setRunning(true);
|
||||||
|
|
||||||
|
void (async () => {
|
||||||
|
for (let i = 0; i < next.length; i++) {
|
||||||
|
if (cancelled) return;
|
||||||
|
setCurrent(next[i].photo.name);
|
||||||
|
try {
|
||||||
|
next[i] = { ...next[i], stats: await statsFor(next[i].photo) };
|
||||||
|
} catch (err) {
|
||||||
|
next[i] = {
|
||||||
|
...next[i],
|
||||||
|
error: err instanceof Error ? err.message : 'Analysis failed',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (cancelled) return;
|
||||||
|
setRows(next.map((row) => ({ ...row })));
|
||||||
|
setDone(i + 1);
|
||||||
|
}
|
||||||
|
if (!cancelled) {
|
||||||
|
setRunning(false);
|
||||||
|
setCurrent('');
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
cancelled = true;
|
||||||
|
};
|
||||||
|
}, [photos]);
|
||||||
|
|
||||||
|
const analysed = rows.filter((row) => row.stats);
|
||||||
|
const soft = analysed.filter((row) => (row.stats?.sharpness ?? 100) < threshold);
|
||||||
|
const duplicates = useMemo(
|
||||||
|
() =>
|
||||||
|
groupDuplicates(
|
||||||
|
analysed.map((row) => ({ ...row, hash: row.stats?.hash ?? '' })),
|
||||||
|
9,
|
||||||
|
),
|
||||||
|
[analysed],
|
||||||
|
);
|
||||||
|
const duplicateRejects = useMemo(() => {
|
||||||
|
const ids: string[] = [];
|
||||||
|
for (const group of duplicates) {
|
||||||
|
// Keep the sharpest frame of the burst; everything close to it is the
|
||||||
|
// alternative the photographer would otherwise have to compare by eye.
|
||||||
|
const sorted = [...group].sort(
|
||||||
|
(a, b) => (b.stats?.sharpness ?? 0) - (a.stats?.sharpness ?? 0),
|
||||||
|
);
|
||||||
|
for (const row of sorted.slice(1)) ids.push(row.photo.id);
|
||||||
|
}
|
||||||
|
return ids;
|
||||||
|
}, [duplicates]);
|
||||||
|
|
||||||
|
const pct = photos.length ? Math.round((done / photos.length) * 100) : 0;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className="modal-backdrop"
|
||||||
|
onPointerDown={(e) => e.target === e.currentTarget && !running && onClose()}
|
||||||
|
>
|
||||||
|
<div className="modal raw-modal cull-modal" role="dialog" aria-modal="true" aria-label="Cull assist">
|
||||||
|
<header className="modal-head">
|
||||||
|
<div>
|
||||||
|
<h2>Cull assist</h2>
|
||||||
|
<p className="muted small">
|
||||||
|
Focus and duplicate checks on {photos.length} photo{photos.length === 1 ? '' : 's'}.
|
||||||
|
Nothing is rated or rejected without your say-so.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
{!running && (
|
||||||
|
<button className="icon-btn" onClick={onClose} title="Close">
|
||||||
|
×
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<div className="modal-body">
|
||||||
|
{running && (
|
||||||
|
<>
|
||||||
|
<div className="progress-bar">
|
||||||
|
<div className="progress-fill" style={{ width: `${pct}%` }} />
|
||||||
|
</div>
|
||||||
|
<p className="muted small">
|
||||||
|
{done} of {photos.length}
|
||||||
|
{current ? ` · ${current}` : '…'}
|
||||||
|
</p>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{!running && (
|
||||||
|
<>
|
||||||
|
<div className="cull-summary">
|
||||||
|
<div>
|
||||||
|
<strong>{soft.length}</strong>
|
||||||
|
<span>soft under {threshold}</span>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<strong>{duplicates.length}</strong>
|
||||||
|
<span>duplicate set{duplicates.length === 1 ? '' : 's'}</span>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<strong>{analysed.length}</strong>
|
||||||
|
<span>analysed</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<label className="cull-threshold">
|
||||||
|
<span>Soft threshold</span>
|
||||||
|
<input
|
||||||
|
type="range"
|
||||||
|
min={5}
|
||||||
|
max={55}
|
||||||
|
value={threshold}
|
||||||
|
onChange={(e) => setThreshold(Number(e.target.value))}
|
||||||
|
/>
|
||||||
|
<span className="muted small">{threshold}</span>
|
||||||
|
</label>
|
||||||
|
|
||||||
|
<ul className="cull-list">
|
||||||
|
{[...analysed]
|
||||||
|
.sort((a, b) => (a.stats?.sharpness ?? 0) - (b.stats?.sharpness ?? 0))
|
||||||
|
.slice(0, 60)
|
||||||
|
.map((row) => {
|
||||||
|
const stats = row.stats as CullStats;
|
||||||
|
const grade = sharpnessGrade(stats.sharpness);
|
||||||
|
return (
|
||||||
|
<li key={row.photo.id}>
|
||||||
|
<span className="cull-name" title={row.photo.name}>
|
||||||
|
{row.photo.name}
|
||||||
|
</span>
|
||||||
|
<span className={`cull-grade ${grade}`}>{grade}</span>
|
||||||
|
<span className="cull-score">{stats.sharpness}</span>
|
||||||
|
<span className="muted small">
|
||||||
|
{stats.clippedHigh > 0.08
|
||||||
|
? 'highlights clipped'
|
||||||
|
: stats.clippedLow > 0.12
|
||||||
|
? 'crushed shadows'
|
||||||
|
: stats.mean < 30
|
||||||
|
? 'very dark'
|
||||||
|
: ''}
|
||||||
|
</span>
|
||||||
|
</li>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</ul>
|
||||||
|
{analysed.length > 60 && (
|
||||||
|
<p className="muted small">Showing the 60 softest frames.</p>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<footer className="modal-foot">
|
||||||
|
<span className="muted small">
|
||||||
|
Scores come from the thumbnails, so treat them as a first pass.
|
||||||
|
</span>
|
||||||
|
{running ? (
|
||||||
|
<button className="btn ghost" onClick={onClose}>
|
||||||
|
Hide
|
||||||
|
</button>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<button
|
||||||
|
className="btn ghost small"
|
||||||
|
disabled={!duplicateRejects.length}
|
||||||
|
onClick={() => {
|
||||||
|
onReject(duplicateRejects);
|
||||||
|
onClose();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Reject {duplicateRejects.length} duplicate alternative
|
||||||
|
{duplicateRejects.length === 1 ? '' : 's'}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
className="btn ghost small danger"
|
||||||
|
disabled={!soft.length}
|
||||||
|
onClick={() => {
|
||||||
|
onReject(soft.map((row) => row.photo.id));
|
||||||
|
onClose();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Reject {soft.length} soft
|
||||||
|
</button>
|
||||||
|
<button className="btn primary" onClick={onClose}>
|
||||||
|
Done
|
||||||
|
</button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</footer>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -2,16 +2,33 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
|||||||
import { buildSampler, clamp01 } from '../lib/curves';
|
import { buildSampler, clamp01 } from '../lib/curves';
|
||||||
import type { CurvePoint } from '../types';
|
import type { CurvePoint } from '../types';
|
||||||
|
|
||||||
|
export type ParametricKey = 'highlights' | 'lights' | 'darks' | 'blacks';
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
points: CurvePoint[];
|
points: CurvePoint[];
|
||||||
onChange: (points: CurvePoint[]) => void;
|
onChange: (points: CurvePoint[]) => void;
|
||||||
color: string;
|
color: string;
|
||||||
|
/** Region tone shaper values, shown as draggable dots on the curve. */
|
||||||
|
parametric?: Record<ParametricKey, number>;
|
||||||
|
onParametric?: (key: ParametricKey, value: number) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function CurveEditor({ points, onChange, color }: Props) {
|
/** Lightroom-scale zones: the four regions share the diagonal evenly. */
|
||||||
|
const ZONES: { key: ParametricKey; label: string; x: number }[] = [
|
||||||
|
{ key: 'highlights', label: 'Highlights', x: 0.875 },
|
||||||
|
{ key: 'lights', label: 'Lights', x: 0.625 },
|
||||||
|
{ key: 'darks', label: 'Darks', x: 0.375 },
|
||||||
|
{ key: 'blacks', label: 'Blacks', x: 0.125 },
|
||||||
|
];
|
||||||
|
|
||||||
|
/** Full slider travel moves a zone dot a quarter of the graph. */
|
||||||
|
const ZONE_TRAVEL = 0.18;
|
||||||
|
|
||||||
|
export default function CurveEditor({ points, onChange, color, parametric, onParametric }: Props) {
|
||||||
const svgRef = useRef<SVGSVGElement>(null);
|
const svgRef = useRef<SVGSVGElement>(null);
|
||||||
const pointsRef = useRef(points);
|
const pointsRef = useRef(points);
|
||||||
const [drag, setDrag] = useState<number | null>(null);
|
const [drag, setDrag] = useState<number | null>(null);
|
||||||
|
const [paramDrag, setParamDrag] = useState<ParametricKey | null>(null);
|
||||||
const [hover, setHover] = useState<number | null>(null);
|
const [hover, setHover] = useState<number | null>(null);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -42,6 +59,12 @@ export default function CurveEditor({ points, onChange, color }: Props) {
|
|||||||
|
|
||||||
const handleDown = (e: React.PointerEvent<SVGSVGElement>) => {
|
const handleDown = (e: React.PointerEvent<SVGSVGElement>) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
|
const paramAttr = (e.target as Element).getAttribute('data-param');
|
||||||
|
if (paramAttr && parametric && onParametric) {
|
||||||
|
setParamDrag(paramAttr as ParametricKey);
|
||||||
|
e.currentTarget.setPointerCapture(e.pointerId);
|
||||||
|
return;
|
||||||
|
}
|
||||||
const idxAttr = (e.target as Element).getAttribute('data-idx');
|
const idxAttr = (e.target as Element).getAttribute('data-idx');
|
||||||
let idx: number;
|
let idx: number;
|
||||||
if (idxAttr !== null) {
|
if (idxAttr !== null) {
|
||||||
@@ -57,6 +80,15 @@ export default function CurveEditor({ points, onChange, color }: Props) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const handleMove = (e: React.PointerEvent<SVGSVGElement>) => {
|
const handleMove = (e: React.PointerEvent<SVGSVGElement>) => {
|
||||||
|
if (paramDrag && parametric && onParametric) {
|
||||||
|
const zone = ZONES.find((item) => item.key === paramDrag);
|
||||||
|
if (!zone) return;
|
||||||
|
const p = toNorm(e.clientX, e.clientY);
|
||||||
|
const base = sampler(zone.x);
|
||||||
|
const value = ((p.y - base) / ZONE_TRAVEL) * 100;
|
||||||
|
onParametric(paramDrag, Math.round(Math.max(-100, Math.min(100, value))));
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (drag === null) return;
|
if (drag === null) return;
|
||||||
const pts = pointsRef.current;
|
const pts = pointsRef.current;
|
||||||
const idx = drag;
|
const idx = drag;
|
||||||
@@ -68,7 +100,10 @@ export default function CurveEditor({ points, onChange, color }: Props) {
|
|||||||
onChange(next);
|
onChange(next);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleUp = () => setDrag(null);
|
const handleUp = () => {
|
||||||
|
setDrag(null);
|
||||||
|
setParamDrag(null);
|
||||||
|
};
|
||||||
|
|
||||||
const removePoint = (idx: number) => {
|
const removePoint = (idx: number) => {
|
||||||
const pts = pointsRef.current;
|
const pts = pointsRef.current;
|
||||||
@@ -101,6 +136,37 @@ export default function CurveEditor({ points, onChange, color }: Props) {
|
|||||||
</g>
|
</g>
|
||||||
))}
|
))}
|
||||||
<line x1="0" y1="100" x2="100" y2="0" className="curve-diag" />
|
<line x1="0" y1="100" x2="100" y2="0" className="curve-diag" />
|
||||||
|
{parametric &&
|
||||||
|
onParametric &&
|
||||||
|
ZONES.map((zone) => {
|
||||||
|
const value = parametric[zone.key] ?? 0;
|
||||||
|
const y = clamp01(sampler(zone.x) + (value / 100) * ZONE_TRAVEL);
|
||||||
|
return (
|
||||||
|
<g key={zone.key} style={{ cursor: 'ns-resize' }}>
|
||||||
|
<line
|
||||||
|
x1={zone.x * 100}
|
||||||
|
y1="0"
|
||||||
|
x2={zone.x * 100}
|
||||||
|
y2="100"
|
||||||
|
stroke="rgba(255,255,255,0.12)"
|
||||||
|
strokeDasharray="2 3"
|
||||||
|
vectorEffect="non-scaling-stroke"
|
||||||
|
/>
|
||||||
|
<circle
|
||||||
|
data-param={zone.key}
|
||||||
|
cx={zone.x * 100}
|
||||||
|
cy={(1 - y) * 100}
|
||||||
|
r={paramDrag === zone.key ? 3.2 : 2.3}
|
||||||
|
fill="#141416"
|
||||||
|
stroke="#f0c86a"
|
||||||
|
strokeWidth="1.4"
|
||||||
|
vectorEffect="non-scaling-stroke"
|
||||||
|
>
|
||||||
|
<title>{`${zone.label}: ${value > 0 ? '+' : ''}${value}`}</title>
|
||||||
|
</circle>
|
||||||
|
</g>
|
||||||
|
);
|
||||||
|
})}
|
||||||
<path d={path} fill="none" stroke={color} strokeWidth="1.6" vectorEffect="non-scaling-stroke" />
|
<path d={path} fill="none" stroke={color} strokeWidth="1.6" vectorEffect="non-scaling-stroke" />
|
||||||
{points.map((p, i) => (
|
{points.map((p, i) => (
|
||||||
<circle
|
<circle
|
||||||
@@ -116,7 +182,9 @@ export default function CurveEditor({ points, onChange, color }: Props) {
|
|||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
</svg>
|
</svg>
|
||||||
<div className="curve-hint">Click to add a point · drag to shape · double-click a point to remove</div>
|
<div className="curve-hint">
|
||||||
|
Click to add a point · drag to shape · drag the four gold dots for highlights, lights, darks and blacks
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,70 @@
|
|||||||
|
import { memo, useEffect, useRef, useState } from 'react';
|
||||||
|
import { thumbTransform } from '../lib/edits';
|
||||||
|
import { useEditedThumb } from '../lib/editThumbs';
|
||||||
|
import type { PhotoRecord } from '../types';
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
photo: PhotoRecord;
|
||||||
|
/** Aspect of the tile the picture fills; the rotation transform needs it. */
|
||||||
|
boxAspect?: number;
|
||||||
|
alt?: string;
|
||||||
|
loading?: 'lazy' | 'eager';
|
||||||
|
draggable?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A thumbnail that follows the photo's edits.
|
||||||
|
*
|
||||||
|
* Edited photos get a freshly rendered small JPEG; everything else keeps the
|
||||||
|
* server/import thumbnail and the CSS orientation transform. Rendering starts
|
||||||
|
* only when the tile is close to the viewport.
|
||||||
|
*/
|
||||||
|
function EditedImage({
|
||||||
|
photo,
|
||||||
|
boxAspect = 4 / 3,
|
||||||
|
alt,
|
||||||
|
loading = 'lazy',
|
||||||
|
draggable = false,
|
||||||
|
}: Props) {
|
||||||
|
const ref = useRef<HTMLImageElement>(null);
|
||||||
|
const [nearView, setNearView] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const el = ref.current;
|
||||||
|
if (!el) return;
|
||||||
|
if (typeof IntersectionObserver === 'undefined') {
|
||||||
|
setNearView(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const observer = new IntersectionObserver(
|
||||||
|
(entries) => {
|
||||||
|
if (!entries.some((entry) => entry.isIntersecting)) return;
|
||||||
|
setNearView(true);
|
||||||
|
observer.disconnect();
|
||||||
|
},
|
||||||
|
{ rootMargin: '400px' },
|
||||||
|
);
|
||||||
|
observer.observe(el);
|
||||||
|
return () => observer.disconnect();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const edited = useEditedThumb(photo, nearView);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<img
|
||||||
|
ref={ref}
|
||||||
|
src={edited ?? photo.thumbUrl ?? photo.thumb}
|
||||||
|
alt={alt ?? photo.name}
|
||||||
|
loading={loading}
|
||||||
|
draggable={draggable}
|
||||||
|
// A rendered tile already has the crop, turn and flips baked in.
|
||||||
|
style={{ transform: edited ? 'none' : thumbTransform(photo, boxAspect) }}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Memoised: a selection change on the library re-renders the whole grid, and a
|
||||||
|
* picture whose photo, size and props did not change has no work to redo.
|
||||||
|
*/
|
||||||
|
export default memo(EditedImage);
|
||||||
@@ -17,9 +17,15 @@ 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;
|
||||||
|
onPublishGallery?: (id: string) => void;
|
||||||
|
/** Server-backed account, so RAW originals can be re-decoded. */
|
||||||
|
canReprocessRaw?: boolean;
|
||||||
|
onReprocessEvent?: (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 +45,14 @@ export default function EventSidebar({
|
|||||||
photos,
|
photos,
|
||||||
eventId,
|
eventId,
|
||||||
onSelectEvent,
|
onSelectEvent,
|
||||||
|
immichEnabled = false,
|
||||||
onCreate,
|
onCreate,
|
||||||
onRename,
|
onRename,
|
||||||
onDelete,
|
onDelete,
|
||||||
|
onSyncGallery,
|
||||||
|
onPublishGallery,
|
||||||
|
canReprocessRaw = false,
|
||||||
|
onReprocessEvent,
|
||||||
onReorderEvents,
|
onReorderEvents,
|
||||||
onDropPhotos,
|
onDropPhotos,
|
||||||
trashOpen,
|
trashOpen,
|
||||||
@@ -55,9 +66,11 @@ 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>();
|
||||||
|
const rawCounts = new Map<string, number>();
|
||||||
let unsorted = 0;
|
let unsorted = 0;
|
||||||
for (const p of photos) {
|
for (const p of photos) {
|
||||||
if (!p.eventId) {
|
if (!p.eventId) {
|
||||||
@@ -65,6 +78,7 @@ export default function EventSidebar({
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
counts.set(p.eventId, (counts.get(p.eventId) ?? 0) + 1);
|
counts.set(p.eventId, (counts.get(p.eventId) ?? 0) + 1);
|
||||||
|
if (p.raw) rawCounts.set(p.eventId, (rawCounts.get(p.eventId) ?? 0) + 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
const submit = async () => {
|
const submit = async () => {
|
||||||
@@ -72,8 +86,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 +204,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 +259,37 @@ 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">
|
||||||
|
{canReprocessRaw && onReprocessEvent && (rawCounts.get(event.id) ?? 0) > 0 && (
|
||||||
|
<button
|
||||||
|
className="icon-btn"
|
||||||
|
title={`Reprocess ${rawCounts.get(event.id)} RAW file${
|
||||||
|
rawCounts.get(event.id) === 1 ? '' : 's'
|
||||||
|
} in this event`}
|
||||||
|
onClick={() => onReprocessEvent(event.id)}
|
||||||
|
>
|
||||||
|
⟲
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
{immichEnabled &&
|
||||||
|
(event.immich
|
||||||
|
? onSyncGallery && (
|
||||||
|
<button
|
||||||
|
className="icon-btn"
|
||||||
|
title="Publish new photos and edits to this event's Immich gallery"
|
||||||
|
onClick={() => onSyncGallery(event.id)}
|
||||||
|
>
|
||||||
|
☁
|
||||||
|
</button>
|
||||||
|
)
|
||||||
|
: onPublishGallery && (
|
||||||
|
<button
|
||||||
|
className="icon-btn"
|
||||||
|
title="Create an Immich gallery for this event and publish its photos"
|
||||||
|
onClick={() => onPublishGallery(event.id)}
|
||||||
|
>
|
||||||
|
☁+
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
<button
|
<button
|
||||||
className="icon-btn"
|
className="icon-btn"
|
||||||
title="Rename event"
|
title="Rename event"
|
||||||
|
|||||||
@@ -5,6 +5,8 @@ import Slider from './Slider';
|
|||||||
import { getBitmap } from '../lib/images';
|
import { getBitmap } from '../lib/images';
|
||||||
import { frameToSource, grainCellPx, grainSampleWindow, outputSize, rotatedBounds, Renderer } from '../gl/renderer';
|
import { frameToSource, grainCellPx, grainSampleWindow, outputSize, rotatedBounds, Renderer } from '../gl/renderer';
|
||||||
import type { PhotoRecord } from '../types';
|
import type { PhotoRecord } from '../types';
|
||||||
|
import { COLOR_SPACE_OPTIONS } from '../lib/colorSpace';
|
||||||
|
import type { OutputColorSpace } from '../lib/icc';
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
photos: PhotoRecord[];
|
photos: PhotoRecord[];
|
||||||
@@ -280,8 +282,12 @@ export default function ExportModal({ photos, initial, recipes, onSaveRecipe, on
|
|||||||
value={opts.format}
|
value={opts.format}
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
const format = e.target.value as ExportFormat;
|
const format = e.target.value as ExportFormat;
|
||||||
|
const wide = format === 'jpeg' || format === 'tiff16';
|
||||||
patch({
|
patch({
|
||||||
format,
|
format,
|
||||||
|
// PNG/WebP output can carry converted pixels but no ICC tag, so
|
||||||
|
// keep those formats in the tagged sRGB default.
|
||||||
|
...(wide ? {} : { colorSpace: 'srgb' as OutputColorSpace }),
|
||||||
// Watermarking needs an 8-bit canvas pass; keep the option off
|
// Watermarking needs an 8-bit canvas pass; keep the option off
|
||||||
// rather than silently downgrading the 16-bit file.
|
// rather than silently downgrading the 16-bit file.
|
||||||
...(format === 'tiff16' ? { watermark: { ...opts.watermark, enabled: false } } : {}),
|
...(format === 'tiff16' ? { watermark: { ...opts.watermark, enabled: false } } : {}),
|
||||||
@@ -435,6 +441,20 @@ export default function ExportModal({ photos, initial, recipes, onSaveRecipe, on
|
|||||||
<div className="subhead">
|
<div className="subhead">
|
||||||
<span>Output</span>
|
<span>Output</span>
|
||||||
</div>
|
</div>
|
||||||
|
<label className="field">
|
||||||
|
<span>Colour space</span>
|
||||||
|
<select
|
||||||
|
value={opts.colorSpace ?? 'srgb'}
|
||||||
|
onChange={(e) => patch({ colorSpace: e.target.value as OutputColorSpace })}
|
||||||
|
disabled={busy || (opts.format !== 'jpeg' && opts.format !== 'tiff16')}
|
||||||
|
>
|
||||||
|
{COLOR_SPACE_OPTIONS.map((option) => (
|
||||||
|
<option key={option.value} value={option.value}>
|
||||||
|
{option.label}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
<Slider
|
<Slider
|
||||||
label="Output sharpening"
|
label="Output sharpening"
|
||||||
min={0}
|
min={0}
|
||||||
@@ -460,7 +480,7 @@ export default function ExportModal({ photos, initial, recipes, onSaveRecipe, on
|
|||||||
onChange={(e) => patch({ embedProfile: e.target.checked })}
|
onChange={(e) => patch({ embedProfile: e.target.checked })}
|
||||||
disabled={opts.format === 'webp' || opts.format === 'png'}
|
disabled={opts.format === 'webp' || opts.format === 'png'}
|
||||||
/>
|
/>
|
||||||
Embed sRGB profile (JPEG/TIFF)
|
Embed {COLOR_SPACE_OPTIONS.find((option) => option.value === (opts.colorSpace ?? 'srgb'))?.label ?? 'sRGB'} profile (JPEG/TIFF)
|
||||||
</label>
|
</label>
|
||||||
|
|
||||||
<div className="subhead">
|
<div className="subhead">
|
||||||
|
|||||||
@@ -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 ☁+ on an event to create its Immich
|
||||||
|
gallery and publish it, or ☁ to push new photos and edits to an existing one.
|
||||||
|
</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>
|
||||||
|
|||||||
@@ -0,0 +1,510 @@
|
|||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
import {
|
||||||
|
deleteTeamProfile,
|
||||||
|
loadTeamProfiles,
|
||||||
|
saveTeamProfile,
|
||||||
|
type TeamLensDraft,
|
||||||
|
type TeamLensProfile,
|
||||||
|
} from '../lib/lensProfiles';
|
||||||
|
import type { LensProfile, PhotoRecord } from '../types';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Calibrations the team measured for lenses the bundled database lacks. The
|
||||||
|
* numbers are stored on the server next to the bundled data, so everyone's
|
||||||
|
* editor and exports pick them up.
|
||||||
|
*/
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
photo: PhotoRecord;
|
||||||
|
/** Profile currently applied, used to prefill the form. */
|
||||||
|
profile?: LensProfile;
|
||||||
|
onClose: () => void;
|
||||||
|
/** Apply a saved calibration to the photo on screen. */
|
||||||
|
onUse: (profile: TeamLensProfile) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const DISTORTION_MODEL_ID = { poly3: 0, poly5: 1, ptlens: 2 } as const;
|
||||||
|
const DISTORTION_MODEL_NAME = { 0: 'poly3', 1: 'poly5', 2: 'ptlens' } as const;
|
||||||
|
const TCA_MODEL_ID = { poly3: 0, linear: 1 } as const;
|
||||||
|
const TCA_MODEL_NAME = { 0: 'poly3', 1: 'linear' } as const;
|
||||||
|
|
||||||
|
type DistortionModel = keyof typeof DISTORTION_MODEL_ID;
|
||||||
|
type TcaModel = keyof typeof TCA_MODEL_ID;
|
||||||
|
|
||||||
|
interface DistortionRow {
|
||||||
|
focal: string;
|
||||||
|
model: DistortionModel;
|
||||||
|
a: string;
|
||||||
|
b: string;
|
||||||
|
c: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface TcaRow {
|
||||||
|
focal: string;
|
||||||
|
model: TcaModel;
|
||||||
|
br: string;
|
||||||
|
cr: string;
|
||||||
|
vr: string;
|
||||||
|
bb: string;
|
||||||
|
cb: string;
|
||||||
|
vb: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface VignettingRow {
|
||||||
|
focal: string;
|
||||||
|
aperture: string;
|
||||||
|
distance: string;
|
||||||
|
k1: string;
|
||||||
|
k2: string;
|
||||||
|
k3: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Draft {
|
||||||
|
id?: string;
|
||||||
|
maker: string;
|
||||||
|
model: string;
|
||||||
|
mount: string;
|
||||||
|
crop: string;
|
||||||
|
notes: string;
|
||||||
|
d: DistortionRow[];
|
||||||
|
t: TcaRow[];
|
||||||
|
v: VignettingRow[];
|
||||||
|
}
|
||||||
|
|
||||||
|
const num = (value: string) => (value.trim() === '' ? 0 : Number(value));
|
||||||
|
const text = (value: number) => (Number.isFinite(value) && value !== 0 ? String(value) : '');
|
||||||
|
|
||||||
|
function toDraft(profile: TeamLensProfile): Draft {
|
||||||
|
return {
|
||||||
|
id: profile.id,
|
||||||
|
maker: profile.maker,
|
||||||
|
model: profile.model,
|
||||||
|
mount: profile.mount,
|
||||||
|
crop: String(profile.crop),
|
||||||
|
notes: profile.notes,
|
||||||
|
d: profile.d.map(([focal, model, a, b, c]) => ({
|
||||||
|
focal: String(focal),
|
||||||
|
model: DISTORTION_MODEL_NAME[model as 0 | 1 | 2] ?? 'poly3',
|
||||||
|
a: text(a),
|
||||||
|
b: text(b),
|
||||||
|
c: text(c),
|
||||||
|
})),
|
||||||
|
t: profile.t.map(([focal, model, br, cr, vr, bb, cb, vb]) => ({
|
||||||
|
focal: String(focal),
|
||||||
|
model: TCA_MODEL_NAME[model as 0 | 1] ?? 'poly3',
|
||||||
|
br: text(br),
|
||||||
|
cr: text(cr),
|
||||||
|
vr: text(vr),
|
||||||
|
bb: text(bb),
|
||||||
|
cb: text(cb),
|
||||||
|
vb: text(vb),
|
||||||
|
})),
|
||||||
|
v: profile.v.map(([focal, aperture, distance, k1, k2, k3]) => ({
|
||||||
|
focal: String(focal),
|
||||||
|
aperture: String(aperture),
|
||||||
|
distance: text(distance),
|
||||||
|
k1: text(k1),
|
||||||
|
k2: text(k2),
|
||||||
|
k3: text(k3),
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function toPayload(draft: Draft): TeamLensDraft {
|
||||||
|
const focal = draft.d.find((row) => row.focal.trim())?.focal;
|
||||||
|
return {
|
||||||
|
id: draft.id,
|
||||||
|
maker: draft.maker.trim(),
|
||||||
|
model: draft.model.trim(),
|
||||||
|
mount: draft.mount.trim(),
|
||||||
|
crop: num(draft.crop) || 1,
|
||||||
|
aspect: 0,
|
||||||
|
centerX: 0,
|
||||||
|
centerY: 0,
|
||||||
|
notes: draft.notes.trim(),
|
||||||
|
d: draft.d
|
||||||
|
.filter((row) => row.focal.trim())
|
||||||
|
.map((row) => [
|
||||||
|
num(row.focal),
|
||||||
|
DISTORTION_MODEL_ID[row.model],
|
||||||
|
num(row.a),
|
||||||
|
num(row.b),
|
||||||
|
num(row.c),
|
||||||
|
0,
|
||||||
|
]),
|
||||||
|
t: draft.t
|
||||||
|
.filter((row) => row.focal.trim())
|
||||||
|
.map((row) => [
|
||||||
|
num(row.focal),
|
||||||
|
TCA_MODEL_ID[row.model],
|
||||||
|
num(row.br),
|
||||||
|
num(row.cr),
|
||||||
|
num(row.vr),
|
||||||
|
num(row.bb),
|
||||||
|
num(row.cb),
|
||||||
|
num(row.vb),
|
||||||
|
]),
|
||||||
|
v: draft.v
|
||||||
|
.filter((row) => row.focal.trim())
|
||||||
|
.map((row) => [
|
||||||
|
num(row.focal),
|
||||||
|
num(row.aperture),
|
||||||
|
num(row.distance) || 1000,
|
||||||
|
num(row.k1),
|
||||||
|
num(row.k2),
|
||||||
|
num(row.k3),
|
||||||
|
]),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const sampleCounts = (profile: TeamLensProfile) =>
|
||||||
|
[
|
||||||
|
profile.d.length ? `${profile.d.length} distortion` : '',
|
||||||
|
profile.t.length ? `${profile.t.length} CA` : '',
|
||||||
|
profile.v.length ? `${profile.v.length} vignetting` : '',
|
||||||
|
]
|
||||||
|
.filter(Boolean)
|
||||||
|
.join(' · ') || 'no samples';
|
||||||
|
|
||||||
|
export default function LensCalibrationModal({ photo, profile, onClose, onUse }: Props) {
|
||||||
|
const [profiles, setProfiles] = useState<TeamLensProfile[] | null>(null);
|
||||||
|
const [draft, setDraft] = useState<Draft | null>(null);
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const blank = (): Draft => ({
|
||||||
|
maker: profile?.maker ?? '',
|
||||||
|
model: profile?.model ?? photo.meta?.lens ?? '',
|
||||||
|
mount: '',
|
||||||
|
crop: String(profile?.crop ?? 1),
|
||||||
|
notes: '',
|
||||||
|
d: [
|
||||||
|
{
|
||||||
|
focal: photo.meta?.focal ? String(photo.meta.focal) : '',
|
||||||
|
model: 'ptlens',
|
||||||
|
a: '',
|
||||||
|
b: '',
|
||||||
|
c: '',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
t: [],
|
||||||
|
v: [],
|
||||||
|
});
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let alive = true;
|
||||||
|
loadTeamProfiles(true)
|
||||||
|
.then((saved) => alive && setProfiles(saved))
|
||||||
|
.catch((err) => {
|
||||||
|
if (!alive) return;
|
||||||
|
setProfiles([]);
|
||||||
|
setError(err instanceof Error ? err.message : 'Could not load the team calibrations');
|
||||||
|
});
|
||||||
|
return () => {
|
||||||
|
alive = false;
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const onKey = (event: KeyboardEvent) => {
|
||||||
|
if (event.key !== 'Escape') return;
|
||||||
|
event.preventDefault();
|
||||||
|
event.stopImmediatePropagation();
|
||||||
|
if (!busy) onClose();
|
||||||
|
};
|
||||||
|
window.addEventListener('keydown', onKey, true);
|
||||||
|
return () => window.removeEventListener('keydown', onKey, true);
|
||||||
|
}, [busy, onClose]);
|
||||||
|
|
||||||
|
const patch = (next: Partial<Draft>) => setDraft((current) => (current ? { ...current, ...next } : current));
|
||||||
|
|
||||||
|
const patchRow = <K extends 'd' | 't' | 'v'>(
|
||||||
|
key: K,
|
||||||
|
index: number,
|
||||||
|
patchValue: Partial<Draft[K][number]>,
|
||||||
|
) =>
|
||||||
|
setDraft((current) => {
|
||||||
|
if (!current) return current;
|
||||||
|
const rows = current[key].map((row, i) => (i === index ? { ...row, ...patchValue } : row));
|
||||||
|
return { ...current, [key]: rows } as Draft;
|
||||||
|
});
|
||||||
|
|
||||||
|
const addRow = (key: 'd' | 't' | 'v') =>
|
||||||
|
setDraft((current) => {
|
||||||
|
if (!current) return current;
|
||||||
|
const focal = photo.meta?.focal ? String(photo.meta.focal) : '';
|
||||||
|
const aperture = photo.meta?.aperture ? String(photo.meta.aperture) : '';
|
||||||
|
if (key === 'd') return { ...current, d: [...current.d, { focal, model: 'ptlens', a: '', b: '', c: '' }] };
|
||||||
|
if (key === 't') {
|
||||||
|
return {
|
||||||
|
...current,
|
||||||
|
t: [...current.t, { focal, model: 'poly3', br: '', cr: '', vr: '', bb: '', cb: '', vb: '' }],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return { ...current, v: [...current.v, { focal, aperture, distance: '1000', k1: '', k2: '', k3: '' }] };
|
||||||
|
});
|
||||||
|
|
||||||
|
const removeRow = (key: 'd' | 't' | 'v', index: number) =>
|
||||||
|
setDraft((current) => {
|
||||||
|
if (!current) return current;
|
||||||
|
return { ...current, [key]: current[key].filter((_, i) => i !== index) } as Draft;
|
||||||
|
});
|
||||||
|
|
||||||
|
const save = async () => {
|
||||||
|
if (!draft || busy) return;
|
||||||
|
setBusy(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const saved = await saveTeamProfile(toPayload(draft));
|
||||||
|
setProfiles((current) =>
|
||||||
|
current
|
||||||
|
? [saved, ...current.filter((entry) => entry.id !== saved.id)]
|
||||||
|
: [saved],
|
||||||
|
);
|
||||||
|
setDraft(null);
|
||||||
|
onUse(saved);
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : 'Could not save the calibration');
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const remove = async (entry: TeamLensProfile) => {
|
||||||
|
if (busy) return;
|
||||||
|
if (!window.confirm(`Delete the team calibration for ${entry.maker} ${entry.model}?`)) return;
|
||||||
|
setBusy(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
await deleteTeamProfile(entry.id);
|
||||||
|
setProfiles((current) => current?.filter((saved) => saved.id !== entry.id) ?? []);
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : 'Could not delete the calibration');
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const field = (label: string, value: string, onChange: (value: string) => void, type = 'text') => (
|
||||||
|
<label className="lens-calib-field">
|
||||||
|
<span className="muted small">{label}</span>
|
||||||
|
<input
|
||||||
|
className="text-input"
|
||||||
|
type={type}
|
||||||
|
step="any"
|
||||||
|
value={value}
|
||||||
|
onChange={(event) => onChange(event.target.value)}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="modal-backdrop" onPointerDown={(e) => e.target === e.currentTarget && onClose()}>
|
||||||
|
<div className="modal lens-calib-modal">
|
||||||
|
<header className="modal-head">
|
||||||
|
<div>
|
||||||
|
<span className="settings-kicker">Team</span>
|
||||||
|
<h2>Lens calibrations</h2>
|
||||||
|
</div>
|
||||||
|
<button className="icon-btn" onClick={onClose} title="Close">
|
||||||
|
✕
|
||||||
|
</button>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<div className="modal-body">
|
||||||
|
{draft ? (
|
||||||
|
<>
|
||||||
|
<p className="muted small lens-defaults-lead">
|
||||||
|
Enter the measurements from your calibration tool. Coefficients are used as measured:
|
||||||
|
distortion is a·r³ + b·r² + c·r + 1 for PanoTools, 1 + a·r² + b·r⁴ for poly5 and
|
||||||
|
1 + k₁·r² for poly3. Add a row per focal length you measured.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div className="lens-calib-grid">
|
||||||
|
{field('Maker', draft.maker, (value) => patch({ maker: value }))}
|
||||||
|
{field('Model', draft.model, (value) => patch({ model: value }))}
|
||||||
|
{field('Mount', draft.mount, (value) => patch({ mount: value }))}
|
||||||
|
{field('Crop factor', draft.crop, (value) => patch({ crop: value }), 'number')}
|
||||||
|
</div>
|
||||||
|
{field('Notes', draft.notes, (value) => patch({ notes: value }))}
|
||||||
|
|
||||||
|
<section className="lens-calib-section">
|
||||||
|
<header>
|
||||||
|
<strong>Distortion</strong>
|
||||||
|
<button className="btn ghost tiny" onClick={() => addRow('d')}>
|
||||||
|
+ Sample
|
||||||
|
</button>
|
||||||
|
</header>
|
||||||
|
{draft.d.length === 0 && <p className="muted small">No distortion measured.</p>}
|
||||||
|
{draft.d.map((row, index) => (
|
||||||
|
<div className="lens-calib-row cols-distortion" key={index}>
|
||||||
|
{field('Focal mm', row.focal, (value) => patchRow('d', index, { focal: value }), 'number')}
|
||||||
|
<label className="lens-calib-field">
|
||||||
|
<span className="muted small">Model</span>
|
||||||
|
<select
|
||||||
|
className="text-input"
|
||||||
|
value={row.model}
|
||||||
|
onChange={(event) =>
|
||||||
|
patchRow('d', index, { model: event.target.value as DistortionModel })
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<option value="ptlens">PanoTools</option>
|
||||||
|
<option value="poly3">poly3</option>
|
||||||
|
<option value="poly5">poly5</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
{field('a', row.a, (value) => patchRow('d', index, { a: value }), 'number')}
|
||||||
|
{field('b', row.b, (value) => patchRow('d', index, { b: value }), 'number')}
|
||||||
|
{field('c', row.c, (value) => patchRow('d', index, { c: value }), 'number')}
|
||||||
|
<button
|
||||||
|
className="icon-btn"
|
||||||
|
title="Remove sample"
|
||||||
|
onClick={() => removeRow('d', index)}
|
||||||
|
>
|
||||||
|
✕
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section className="lens-calib-section">
|
||||||
|
<header>
|
||||||
|
<strong>Chromatic aberration</strong>
|
||||||
|
<button className="btn ghost tiny" onClick={() => addRow('t')}>
|
||||||
|
+ Sample
|
||||||
|
</button>
|
||||||
|
</header>
|
||||||
|
{draft.t.length === 0 && <p className="muted small">No lateral CA measured.</p>}
|
||||||
|
{draft.t.map((row, index) => (
|
||||||
|
<div className="lens-calib-row cols-tca" key={index}>
|
||||||
|
{field('Focal mm', row.focal, (value) => patchRow('t', index, { focal: value }), 'number')}
|
||||||
|
<label className="lens-calib-field">
|
||||||
|
<span className="muted small">Model</span>
|
||||||
|
<select
|
||||||
|
className="text-input"
|
||||||
|
value={row.model}
|
||||||
|
onChange={(event) => patchRow('t', index, { model: event.target.value as TcaModel })}
|
||||||
|
>
|
||||||
|
<option value="poly3">poly3</option>
|
||||||
|
<option value="linear">linear</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
{field('red b', row.br, (value) => patchRow('t', index, { br: value }), 'number')}
|
||||||
|
{field('red c', row.cr, (value) => patchRow('t', index, { cr: value }), 'number')}
|
||||||
|
{field('red v', row.vr, (value) => patchRow('t', index, { vr: value }), 'number')}
|
||||||
|
{field('blue b', row.bb, (value) => patchRow('t', index, { bb: value }), 'number')}
|
||||||
|
{field('blue c', row.cb, (value) => patchRow('t', index, { cb: value }), 'number')}
|
||||||
|
{field('blue v', row.vb, (value) => patchRow('t', index, { vb: value }), 'number')}
|
||||||
|
<button
|
||||||
|
className="icon-btn"
|
||||||
|
title="Remove sample"
|
||||||
|
onClick={() => removeRow('t', index)}
|
||||||
|
>
|
||||||
|
✕
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section className="lens-calib-section">
|
||||||
|
<header>
|
||||||
|
<strong>Vignetting</strong>
|
||||||
|
<button className="btn ghost tiny" onClick={() => addRow('v')}>
|
||||||
|
+ Sample
|
||||||
|
</button>
|
||||||
|
</header>
|
||||||
|
{draft.v.length === 0 && <p className="muted small">No vignetting measured.</p>}
|
||||||
|
{draft.v.map((row, index) => (
|
||||||
|
<div className="lens-calib-row cols-vignetting" key={index}>
|
||||||
|
{field('Focal mm', row.focal, (value) => patchRow('v', index, { focal: value }), 'number')}
|
||||||
|
{field('Aperture', row.aperture, (value) => patchRow('v', index, { aperture: value }), 'number')}
|
||||||
|
{field('Distance', row.distance, (value) => patchRow('v', index, { distance: value }), 'number')}
|
||||||
|
{field('k₁', row.k1, (value) => patchRow('v', index, { k1: value }), 'number')}
|
||||||
|
{field('k₂', row.k2, (value) => patchRow('v', index, { k2: value }), 'number')}
|
||||||
|
{field('k₃', row.k3, (value) => patchRow('v', index, { k3: value }), 'number')}
|
||||||
|
<button
|
||||||
|
className="icon-btn"
|
||||||
|
title="Remove sample"
|
||||||
|
onClick={() => removeRow('v', index)}
|
||||||
|
>
|
||||||
|
✕
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</section>
|
||||||
|
</>
|
||||||
|
) : profiles === null ? (
|
||||||
|
<p className="muted small">Loading the team calibrations…</p>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<p className="muted small lens-defaults-lead">
|
||||||
|
These are shared with everyone signed in to this library. The Optics panel finds them
|
||||||
|
by maker or model, next to the bundled profiles.
|
||||||
|
</p>
|
||||||
|
<div className="lens-defaults-list">
|
||||||
|
{profiles.length === 0 && (
|
||||||
|
<p className="muted small">No team calibrations yet — add the first one.</p>
|
||||||
|
)}
|
||||||
|
{profiles.map((entry) => (
|
||||||
|
<article className="lens-default-item" key={entry.id}>
|
||||||
|
<div className="lens-default-main">
|
||||||
|
<div className="lens-default-title">
|
||||||
|
<strong>
|
||||||
|
{entry.maker} {entry.model}
|
||||||
|
</strong>
|
||||||
|
<span className="muted small">crop {entry.crop}×</span>
|
||||||
|
</div>
|
||||||
|
<p className="lens-default-match">
|
||||||
|
{entry.mount || 'any mount'} <span className="muted small">· {sampleCounts(entry)}</span>
|
||||||
|
</p>
|
||||||
|
{entry.notes && <p className="muted small lens-default-meta">{entry.notes}</p>}
|
||||||
|
</div>
|
||||||
|
<div className="lens-default-actions">
|
||||||
|
<button className="btn ghost small" onClick={() => onUse(entry)}>
|
||||||
|
Use
|
||||||
|
</button>
|
||||||
|
<button className="btn ghost tiny" onClick={() => setDraft(toDraft(entry))}>
|
||||||
|
Edit
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
className="btn ghost tiny"
|
||||||
|
disabled={busy}
|
||||||
|
onClick={() => void remove(entry)}
|
||||||
|
>
|
||||||
|
Delete
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</article>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{error && <p className="small lens-error">{error}</p>}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<footer className="modal-foot">
|
||||||
|
{draft ? (
|
||||||
|
<>
|
||||||
|
<button className="btn ghost" onClick={() => setDraft(null)} disabled={busy}>
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
<button className="btn primary" onClick={() => void save()} disabled={busy}>
|
||||||
|
{busy ? 'Saving…' : draft.id ? 'Save calibration' : 'Add calibration'}
|
||||||
|
</button>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<button className="btn ghost" onClick={onClose}>
|
||||||
|
Done
|
||||||
|
</button>
|
||||||
|
<button className="btn primary" onClick={() => setDraft(blank())} disabled={busy}>
|
||||||
|
New calibration
|
||||||
|
</button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</footer>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,8 +1,9 @@
|
|||||||
import { useEffect, useRef, useState } from 'react';
|
import { useEffect, useRef, useState } from 'react';
|
||||||
import { COLOR_LABELS, isEdited, thumbTransform } from '../lib/edits';
|
import { COLOR_LABELS, isEdited } from '../lib/edits';
|
||||||
import { draggedPhotoIds, endDrag, PHOTO_DRAG, startPhotoDrag } from '../lib/drag';
|
import { draggedPhotoIds, endDrag, PHOTO_DRAG, startPhotoDrag } from '../lib/drag';
|
||||||
import type { ColorLabel, Flag, PhotoRecord } from '../types';
|
import type { ColorLabel, Flag, PhotoRecord } from '../types';
|
||||||
import Stars, { ColorSwatches, FlagButtons } from './Stars';
|
import Stars, { ColorSwatches, FlagButtons } from './Stars';
|
||||||
|
import EditedImage from './EditedImage';
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
photos: PhotoRecord[];
|
photos: PhotoRecord[];
|
||||||
@@ -15,12 +16,17 @@ 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;
|
||||||
onStack: () => void;
|
onStack: () => void;
|
||||||
onVirtualCopy: () => void;
|
onVirtualCopy: () => void;
|
||||||
onMerge: () => void;
|
onMerge: () => void;
|
||||||
|
/** Re-decode the selected RAW files with the server's current pipeline. */
|
||||||
|
onReprocessRaw?: () => void;
|
||||||
|
reprocessBusy?: boolean;
|
||||||
onPrint: () => void;
|
onPrint: () => void;
|
||||||
stacks: Map<string, { count: number; expanded: boolean }>;
|
stacks: Map<string, { count: number; expanded: boolean }>;
|
||||||
onToggleStack: (id: string) => void;
|
onToggleStack: (id: string) => void;
|
||||||
@@ -51,12 +57,16 @@ export default function LibraryGrid({
|
|||||||
onBulkRate,
|
onBulkRate,
|
||||||
onBulkFlag,
|
onBulkFlag,
|
||||||
onBulkColor,
|
onBulkColor,
|
||||||
|
onSendToImmich,
|
||||||
|
immichBusy = false,
|
||||||
onDelete,
|
onDelete,
|
||||||
onExport,
|
onExport,
|
||||||
onCompare,
|
onCompare,
|
||||||
onStack,
|
onStack,
|
||||||
onVirtualCopy,
|
onVirtualCopy,
|
||||||
onMerge,
|
onMerge,
|
||||||
|
onReprocessRaw,
|
||||||
|
reprocessBusy = false,
|
||||||
onPrint,
|
onPrint,
|
||||||
stacks,
|
stacks,
|
||||||
onToggleStack,
|
onToggleStack,
|
||||||
@@ -277,6 +287,26 @@ 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>
|
||||||
|
{onReprocessRaw && (
|
||||||
|
<button
|
||||||
|
className="btn ghost small"
|
||||||
|
onClick={onReprocessRaw}
|
||||||
|
disabled={reprocessBusy}
|
||||||
|
title="Re-decode the selected RAW files with the current pipeline settings"
|
||||||
|
>
|
||||||
|
{reprocessBusy ? 'Reprocessing…' : 'Reprocess RAW'}
|
||||||
|
</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>
|
||||||
@@ -429,13 +459,7 @@ export default function LibraryGrid({
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<div className="card-thumb">
|
<div className="card-thumb">
|
||||||
<img
|
<EditedImage photo={p} alt={p.name} />
|
||||||
src={p.thumbUrl ?? p.thumb}
|
|
||||||
alt={p.name}
|
|
||||||
loading="lazy"
|
|
||||||
draggable={false}
|
|
||||||
style={{ transform: thumbTransform(p) }}
|
|
||||||
/>
|
|
||||||
<div className="card-badges">
|
<div className="card-badges">
|
||||||
{p.flag === 'pick' && <span className="badge pick">✓</span>}
|
{p.flag === 'pick' && <span className="badge pick">✓</span>}
|
||||||
{p.flag === 'reject' && <span className="badge reject">✕</span>}
|
{p.flag === 'reject' && <span className="badge reject">✕</span>}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { useEffect, useState } from 'react';
|
import { useEffect, useState } from 'react';
|
||||||
import { normalizeEdits } from '../lib/edits';
|
import { normalizeEdits } from '../lib/edits';
|
||||||
import { getBitmap } from '../lib/images';
|
import { get16BitSource, getBitmap } from '../lib/images';
|
||||||
import { Renderer, rotatedBounds } from '../gl/renderer';
|
import { Renderer, rotatedBounds } from '../gl/renderer';
|
||||||
import type { PhotoRecord, Preset } from '../types';
|
import type { PhotoRecord, Preset } from '../types';
|
||||||
|
|
||||||
@@ -14,7 +14,8 @@ const CACHE_LIMIT = 900;
|
|||||||
const THUMB_EDGE = 200;
|
const THUMB_EDGE = 200;
|
||||||
|
|
||||||
/** The crop is part of the key so a turn, straighten or flip refreshes the tiles. */
|
/** The crop is part of the key so a turn, straighten or flip refreshes the tiles. */
|
||||||
const keyOf = (photoId: string, presetId: string, crop: string) => `${photoId}|${presetId}|${crop}`;
|
const keyOf = (photoId: string, presetId: string, crop: string, source: string) =>
|
||||||
|
`${photoId}|${presetId}|${crop}|${source}`;
|
||||||
|
|
||||||
export function usePresetThumbs(photo: PhotoRecord, presets: Preset[]): Record<string, string> {
|
export function usePresetThumbs(photo: PhotoRecord, presets: Preset[]): Record<string, string> {
|
||||||
const [thumbs, setThumbs] = useState<Record<string, string>>({});
|
const [thumbs, setThumbs] = useState<Record<string, string>>({});
|
||||||
@@ -23,6 +24,10 @@ export function usePresetThumbs(photo: PhotoRecord, presets: Preset[]): Record<s
|
|||||||
const presetKey = presets.map((p) => p.id).join('|');
|
const presetKey = presets.map((p) => p.id).join('|');
|
||||||
const crop = photo.edits.crop;
|
const crop = photo.edits.crop;
|
||||||
const cropKey = [crop.x, crop.y, crop.w, crop.h, crop.angle, crop.quarter, crop.flipH, crop.flipV].join(',');
|
const cropKey = [crop.x, crop.y, crop.w, crop.h, crop.angle, crop.quarter, crop.flipH, crop.flipV].join(',');
|
||||||
|
// The preset previews keep the photo's camera profile, so a reprocess or a
|
||||||
|
// different profile has to invalidate tiles the same way a crop does.
|
||||||
|
const profile = photo.edits.cameraProfile;
|
||||||
|
const sourceKey = `${photo.previewVersion ?? 0}|${profile ? profile.matrix.join(',') : ''}`;
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let alive = true;
|
let alive = true;
|
||||||
@@ -31,7 +36,7 @@ export function usePresetThumbs(photo: PhotoRecord, presets: Preset[]): Record<s
|
|||||||
|
|
||||||
const known: Record<string, string> = {};
|
const known: Record<string, string> = {};
|
||||||
for (const preset of presets) {
|
for (const preset of presets) {
|
||||||
const hit = cache.get(keyOf(photo.id, preset.id, cropKey));
|
const hit = cache.get(keyOf(photo.id, preset.id, cropKey, sourceKey));
|
||||||
if (hit) known[preset.id] = hit;
|
if (hit) known[preset.id] = hit;
|
||||||
}
|
}
|
||||||
setThumbs(known);
|
setThumbs(known);
|
||||||
@@ -43,6 +48,7 @@ export function usePresetThumbs(photo: PhotoRecord, presets: Preset[]): Record<s
|
|||||||
try {
|
try {
|
||||||
const bitmap = await getBitmap(photo);
|
const bitmap = await getBitmap(photo);
|
||||||
if (!alive) return;
|
if (!alive) return;
|
||||||
|
const hdr = profile ? await get16BitSource(photo).catch(() => null) : null;
|
||||||
renderer = new Renderer(canvas);
|
renderer = new Renderer(canvas);
|
||||||
// Every tile shows the photo as it is framed now, so a turned photo's
|
// Every tile shows the photo as it is framed now, so a turned photo's
|
||||||
// presets are turned too.
|
// presets are turned too.
|
||||||
@@ -52,18 +58,18 @@ export function usePresetThumbs(photo: PhotoRecord, presets: Preset[]): Record<s
|
|||||||
const scale = THUMB_EDGE / Math.max(cropW, cropH);
|
const scale = THUMB_EDGE / Math.max(cropW, cropH);
|
||||||
const width = Math.max(1, Math.round(cropW * scale));
|
const width = Math.max(1, Math.round(cropW * scale));
|
||||||
const height = Math.max(1, Math.round(cropH * scale));
|
const height = Math.max(1, Math.round(cropH * scale));
|
||||||
renderer.setImage(bitmap);
|
renderer.setImage(bitmap, hdr);
|
||||||
|
|
||||||
for (const preset of pending) {
|
for (const preset of pending) {
|
||||||
if (!alive) break;
|
if (!alive) break;
|
||||||
try {
|
try {
|
||||||
renderer.render({ ...normalizeEdits(preset.edits), crop }, {
|
renderer.render({ ...normalizeEdits(preset.edits), crop, cameraProfile: profile }, {
|
||||||
width,
|
width,
|
||||||
height,
|
height,
|
||||||
upscale: Math.max(width / cropW, height / cropH) > 1.05,
|
upscale: Math.max(width / cropW, height / cropH) > 1.05,
|
||||||
});
|
});
|
||||||
const url = canvas.toDataURL('image/jpeg', 0.72);
|
const url = canvas.toDataURL('image/jpeg', 0.72);
|
||||||
cache.set(keyOf(photo.id, preset.id, cropKey), url);
|
cache.set(keyOf(photo.id, preset.id, cropKey, sourceKey), url);
|
||||||
setThumbs((prev) => ({ ...prev, [preset.id]: url }));
|
setThumbs((prev) => ({ ...prev, [preset.id]: url }));
|
||||||
} catch {
|
} catch {
|
||||||
// One bad preset must not stop the rest of the grid.
|
// One bad preset must not stop the rest of the grid.
|
||||||
@@ -85,7 +91,7 @@ export function usePresetThumbs(photo: PhotoRecord, presets: Preset[]): Record<s
|
|||||||
renderer?.dispose();
|
renderer?.dispose();
|
||||||
};
|
};
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
}, [photo.id, presetKey, cropKey]);
|
}, [photo.id, presetKey, cropKey, sourceKey]);
|
||||||
|
|
||||||
return thumbs;
|
return thumbs;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,9 +3,11 @@ import {
|
|||||||
addGalleryComment,
|
addGalleryComment,
|
||||||
galleryDownloadAllUrl,
|
galleryDownloadAllUrl,
|
||||||
galleryDownloadUrl,
|
galleryDownloadUrl,
|
||||||
|
getGalleryStatus,
|
||||||
loadGallery,
|
loadGallery,
|
||||||
setGalleryPick,
|
setGalleryPick,
|
||||||
setGalleryReview,
|
setGalleryReview,
|
||||||
|
unlockGallery,
|
||||||
} from '../lib/api';
|
} from '../lib/api';
|
||||||
import type { GalleryPayload, GalleryPhoto } from '../lib/api';
|
import type { GalleryPayload, GalleryPhoto } from '../lib/api';
|
||||||
|
|
||||||
@@ -74,9 +76,22 @@ export default function ProofingGallery({ token }: { token: string }) {
|
|||||||
const [saving, setSaving] = useState<Set<string>>(new Set());
|
const [saving, setSaving] = useState<Set<string>>(new Set());
|
||||||
const [commentDraft, setCommentDraft] = useState('');
|
const [commentDraft, setCommentDraft] = useState('');
|
||||||
const [feedbackBusy, setFeedbackBusy] = useState(false);
|
const [feedbackBusy, setFeedbackBusy] = useState(false);
|
||||||
|
const [locked, setLocked] = useState(false);
|
||||||
|
const [password, setPassword] = useState('');
|
||||||
|
const [unlocking, setUnlocking] = useState(false);
|
||||||
|
|
||||||
const load = useCallback(async () => {
|
const load = useCallback(async () => {
|
||||||
try {
|
try {
|
||||||
|
// The status call is what turns a locked link into a password prompt
|
||||||
|
// instead of a dead end: the gallery body is a 401 while locked.
|
||||||
|
const status = await getGalleryStatus(token);
|
||||||
|
if (status.locked) {
|
||||||
|
setLocked(true);
|
||||||
|
setData(null);
|
||||||
|
setFatal(null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setLocked(false);
|
||||||
const payload = await loadGallery(token, identity.current.id);
|
const payload = await loadGallery(token, identity.current.id);
|
||||||
setData(payload);
|
setData(payload);
|
||||||
setPicks(new Set(payload.photos.filter((p) => p.mine).map((p) => p.id)));
|
setPicks(new Set(payload.photos.filter((p) => p.mine).map((p) => p.id)));
|
||||||
@@ -103,6 +118,21 @@ export default function ProofingGallery({ token }: { token: string }) {
|
|||||||
};
|
};
|
||||||
}, [data]);
|
}, [data]);
|
||||||
|
|
||||||
|
const unlock = async () => {
|
||||||
|
if (unlocking || !password) return;
|
||||||
|
setUnlocking(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
await unlockGallery(token, password);
|
||||||
|
setPassword('');
|
||||||
|
await load();
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : 'That password did not work');
|
||||||
|
} finally {
|
||||||
|
setUnlocking(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const rememberName = (name: string) => {
|
const rememberName = (name: string) => {
|
||||||
setClientName(name);
|
setClientName(name);
|
||||||
try {
|
try {
|
||||||
@@ -260,6 +290,38 @@ export default function ProofingGallery({ token }: { token: string }) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!data && locked) {
|
||||||
|
return (
|
||||||
|
<div className="proof">
|
||||||
|
<div className="proof-splash proof-lock">
|
||||||
|
<div className="logo large">Luminary</div>
|
||||||
|
<h1>This gallery is private</h1>
|
||||||
|
<p>Enter the password the photographer gave you.</p>
|
||||||
|
<form
|
||||||
|
className="proof-lock-form"
|
||||||
|
onSubmit={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
void unlock();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
value={password}
|
||||||
|
autoFocus
|
||||||
|
autoComplete="current-password"
|
||||||
|
placeholder="Gallery password"
|
||||||
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
|
/>
|
||||||
|
<button className="btn primary" type="submit" disabled={!password || unlocking}>
|
||||||
|
{unlocking ? 'Opening…' : 'Open gallery'}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
{error && <p className="proof-subtle">{error}</p>}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
if (!data) {
|
if (!data) {
|
||||||
return (
|
return (
|
||||||
<div className="proof">
|
<div className="proof">
|
||||||
@@ -320,7 +382,7 @@ export default function ProofingGallery({ token }: { token: string }) {
|
|||||||
>
|
>
|
||||||
My picks {pickedCount ? `(${pickedCount})` : ''}
|
My picks {pickedCount ? `(${pickedCount})` : ''}
|
||||||
</button>
|
</button>
|
||||||
{pickedCount > 0 && (
|
{pickedCount > 0 && data.downloads?.allowed !== false && (
|
||||||
<a
|
<a
|
||||||
className="btn ghost small"
|
className="btn ghost small"
|
||||||
href={galleryDownloadAllUrl(token, identity.current.id)}
|
href={galleryDownloadAllUrl(token, identity.current.id)}
|
||||||
@@ -419,9 +481,11 @@ export default function ProofingGallery({ token }: { token: string }) {
|
|||||||
<div className="proof-lb-bar">
|
<div className="proof-lb-bar">
|
||||||
<div className="proof-lb-title">
|
<div className="proof-lb-title">
|
||||||
<span className="proof-lb-name">{lightboxPhoto.name}</span>
|
<span className="proof-lb-name">{lightboxPhoto.name}</span>
|
||||||
<a className="btn ghost small" href={galleryDownloadUrl(token, lightboxPhoto.id)} download>
|
{data.downloads?.allowed !== false && (
|
||||||
Download
|
<a className="btn ghost small" href={galleryDownloadUrl(token, lightboxPhoto.id)} download>
|
||||||
</a>
|
Download
|
||||||
|
</a>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
<button
|
<button
|
||||||
className={`proof-lb-pick ${picks.has(lightboxPhoto.id) ? 'on' : ''}`}
|
className={`proof-lb-pick ${picks.has(lightboxPhoto.id) ? 'on' : ''}`}
|
||||||
|
|||||||
@@ -0,0 +1,103 @@
|
|||||||
|
export interface RawReprocessFailure {
|
||||||
|
name: string;
|
||||||
|
error: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RawReprocessJob {
|
||||||
|
running: boolean;
|
||||||
|
/** Files attempted so far, including failures. */
|
||||||
|
done: number;
|
||||||
|
total: number;
|
||||||
|
current: string;
|
||||||
|
eventName?: string;
|
||||||
|
failures: RawReprocessFailure[];
|
||||||
|
cancelled?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
job: RawReprocessJob;
|
||||||
|
onCancel: () => void;
|
||||||
|
onClose: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Progress and summary for a RAW re-decode run. The job keeps running while the
|
||||||
|
* dialog is open; Cancel stops it after the file already in flight.
|
||||||
|
*/
|
||||||
|
export default function RawReprocessModal({ job, onCancel, onClose }: Props) {
|
||||||
|
const succeeded = Math.max(0, job.done - job.failures.length);
|
||||||
|
const pct = job.total ? Math.round((job.done / job.total) * 100) : 0;
|
||||||
|
const scope = job.eventName ? `“${job.eventName}”` : 'the selection';
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className="modal-backdrop"
|
||||||
|
onPointerDown={(e) => e.target === e.currentTarget && !job.running && onClose()}
|
||||||
|
>
|
||||||
|
<div className="modal raw-modal" role="dialog" aria-modal="true" aria-label="RAW reprocess">
|
||||||
|
<header className="modal-head">
|
||||||
|
<div>
|
||||||
|
<h2>{job.running ? 'Reprocessing RAW files' : 'RAW reprocess summary'}</h2>
|
||||||
|
<p className="muted small">
|
||||||
|
{job.total} RAW file{job.total === 1 ? '' : 's'} from {scope}. Existing edits and crops
|
||||||
|
are kept.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
{!job.running && (
|
||||||
|
<button className="icon-btn" onClick={onClose} title="Close">
|
||||||
|
×
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<div className="modal-body">
|
||||||
|
<div className="progress-bar">
|
||||||
|
<div className="progress-fill" style={{ width: `${pct}%` }} />
|
||||||
|
</div>
|
||||||
|
<p className="muted small">
|
||||||
|
{job.running
|
||||||
|
? job.cancelled
|
||||||
|
? `Stopping after the current file · ${job.done} of ${job.total}`
|
||||||
|
: `${job.done} of ${job.total}${job.current ? ` · ${job.current}` : '…'}`
|
||||||
|
: job.cancelled
|
||||||
|
? `Stopped after ${job.done} of ${job.total}. Reprocessed ${succeeded}.`
|
||||||
|
: `Reprocessed ${succeeded} of ${job.total}.`}
|
||||||
|
</p>
|
||||||
|
|
||||||
|
{!job.running && job.failures.length > 0 && (
|
||||||
|
<div className="failures">
|
||||||
|
<strong>
|
||||||
|
{job.failures.length} file{job.failures.length === 1 ? '' : 's'} failed
|
||||||
|
</strong>
|
||||||
|
<ul>
|
||||||
|
{job.failures.slice(0, 12).map((failure) => (
|
||||||
|
<li key={failure.name}>
|
||||||
|
{failure.name}: {failure.error}
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
{job.failures.length > 12 && (
|
||||||
|
<p className="muted small">And {job.failures.length - 12} more…</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<footer className="modal-foot">
|
||||||
|
{job.running ? (
|
||||||
|
<>
|
||||||
|
<span className="muted small">Cancel stops after the current file.</span>
|
||||||
|
<button className="btn ghost danger" onClick={onCancel} disabled={job.cancelled}>
|
||||||
|
{job.cancelled ? 'Stopping…' : 'Cancel'}
|
||||||
|
</button>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<button className="btn primary" onClick={onClose}>
|
||||||
|
Done
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</footer>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,9 +1,10 @@
|
|||||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||||
import { createShare, getShare, pushProof, revokeShare } from '../lib/api';
|
import { createShare, getShare, pushProof, revokeShare, saveShareSettings } from '../lib/api';
|
||||||
import type { ShareState } from '../lib/api';
|
import type { ShareState } from '../lib/api';
|
||||||
import { DEFAULT_EXPORT, renderPhotoBlob } from '../lib/export';
|
import { DEFAULT_EXPORT, renderPhotoBlob } from '../lib/export';
|
||||||
import type { ExportOptions } from '../lib/export';
|
import type { ExportOptions } from '../lib/export';
|
||||||
import type { PhotoRecord } from '../types';
|
import type { PhotoRecord } from '../types';
|
||||||
|
import { Renderer } from '../gl/renderer';
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
event: { id: string; name: string };
|
event: { id: string; name: string };
|
||||||
@@ -50,6 +51,13 @@ export default function ShareModal({ event, photos, onClose, onToast, onProofPub
|
|||||||
const [published, setPublished] = useState(0);
|
const [published, setPublished] = useState(0);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const [copied, setCopied] = useState(false);
|
const [copied, setCopied] = useState(false);
|
||||||
|
const [passwordDraft, setPasswordDraft] = useState('');
|
||||||
|
const [expiryDraft, setExpiryDraft] = useState('');
|
||||||
|
const [watermarkDraft, setWatermarkDraft] = useState('');
|
||||||
|
const [downloadsOn, setDownloadsOn] = useState(true);
|
||||||
|
const [capDraft, setCapDraft] = useState('0');
|
||||||
|
const [savingSettings, setSavingSettings] = useState(false);
|
||||||
|
const settingsLoaded = useRef(false);
|
||||||
|
|
||||||
const refresh = useCallback(async () => {
|
const refresh = useCallback(async () => {
|
||||||
try {
|
try {
|
||||||
@@ -93,15 +101,44 @@ export default function ShareModal({ event, photos, onClose, onToast, onProofPub
|
|||||||
|
|
||||||
const namesByPhoto = useMemo(() => new Map(photos.map((p) => [p.id, p.name])), [photos]);
|
const namesByPhoto = useMemo(() => new Map(photos.map((p) => [p.id, p.name])), [photos]);
|
||||||
|
|
||||||
const publishProofs = async () => {
|
// Seeded once: the 20-second refresh must not overwrite fields being typed.
|
||||||
|
useEffect(() => {
|
||||||
|
const saved = share?.settings;
|
||||||
|
if (!saved || settingsLoaded.current) return;
|
||||||
|
settingsLoaded.current = true;
|
||||||
|
setExpiryDraft(saved.expiresAt ? new Date(saved.expiresAt).toISOString().slice(0, 10) : '');
|
||||||
|
setWatermarkDraft(saved.watermark ?? '');
|
||||||
|
setDownloadsOn(saved.allowDownloads !== false);
|
||||||
|
setCapDraft(String(saved.downloadCap || 0));
|
||||||
|
}, [share]);
|
||||||
|
|
||||||
|
const publishProofs = async (watermark = share?.settings?.watermark ?? '') => {
|
||||||
if (!photos.length || publishing) return 0;
|
if (!photos.length || publishing) return 0;
|
||||||
|
// The gallery watermark is baked into the published proof, so the
|
||||||
|
// downloadable file carries it too — not just the on-screen overlay.
|
||||||
|
const proofExport: ExportOptions = {
|
||||||
|
...PROOF_EXPORT,
|
||||||
|
watermark: {
|
||||||
|
...PROOF_EXPORT.watermark,
|
||||||
|
enabled: Boolean(watermark.trim()),
|
||||||
|
text: watermark.trim(),
|
||||||
|
},
|
||||||
|
};
|
||||||
setPublishing(true);
|
setPublishing(true);
|
||||||
setPublished(0);
|
setPublished(0);
|
||||||
setError(null);
|
setError(null);
|
||||||
let done = 0;
|
let done = 0;
|
||||||
|
// One context and one shader compile for the whole batch: a proof run over
|
||||||
|
// an event would otherwise create and tear down a renderer per photo.
|
||||||
|
let shared: Renderer | null = null;
|
||||||
|
try {
|
||||||
|
shared = new Renderer(document.createElement('canvas'));
|
||||||
|
} catch {
|
||||||
|
shared = null;
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
for (const photo of photos) {
|
for (const photo of photos) {
|
||||||
const blob = await renderPhotoBlob(photo, PROOF_EXPORT);
|
const blob = await renderPhotoBlob(photo, proofExport, shared ?? undefined);
|
||||||
const result = await pushProof(photo.id, await proofBase64(blob));
|
const result = await pushProof(photo.id, await proofBase64(blob));
|
||||||
onProofPublished?.(photo.id, result.thumbUrl, result.proofAt);
|
onProofPublished?.(photo.id, result.thumbUrl, result.proofAt);
|
||||||
done += 1;
|
done += 1;
|
||||||
@@ -113,6 +150,7 @@ export default function ShareModal({ event, photos, onClose, onToast, onProofPub
|
|||||||
setError(err instanceof Error ? err.message : 'Could not publish the edited proofs');
|
setError(err instanceof Error ? err.message : 'Could not publish the edited proofs');
|
||||||
return done;
|
return done;
|
||||||
} finally {
|
} finally {
|
||||||
|
shared?.dispose();
|
||||||
setPublishing(false);
|
setPublishing(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -122,9 +160,10 @@ export default function ShareModal({ event, photos, onClose, onToast, onProofPub
|
|||||||
setError(null);
|
setError(null);
|
||||||
try {
|
try {
|
||||||
await createShare(event.id);
|
await createShare(event.id);
|
||||||
await refresh();
|
const state = await getShare(event.id);
|
||||||
|
setShare(state);
|
||||||
// A gallery without rendered proofs would show the unedited originals.
|
// A gallery without rendered proofs would show the unedited originals.
|
||||||
await publishProofs();
|
await publishProofs(state.settings?.watermark ?? '');
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setError(err instanceof Error ? err.message : 'Could not create the link');
|
setError(err instanceof Error ? err.message : 'Could not create the link');
|
||||||
} finally {
|
} finally {
|
||||||
@@ -144,6 +183,28 @@ export default function ShareModal({ event, photos, onClose, onToast, onProofPub
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const saveSettings = async (password?: string) => {
|
||||||
|
if (savingSettings) return;
|
||||||
|
setSavingSettings(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const settings = await saveShareSettings(event.id, {
|
||||||
|
...(password === undefined ? {} : { password }),
|
||||||
|
expiresAt: expiryDraft ? new Date(`${expiryDraft}T23:59:59`).getTime() : null,
|
||||||
|
watermark: watermarkDraft.trim(),
|
||||||
|
allowDownloads: downloadsOn,
|
||||||
|
downloadCap: Math.max(0, Math.round(Number(capDraft) || 0)),
|
||||||
|
});
|
||||||
|
setShare((prev) => (prev ? { ...prev, settings } : prev));
|
||||||
|
setPasswordDraft('');
|
||||||
|
onToast(password === '' ? 'Gallery password removed' : 'Gallery settings saved');
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : 'Could not save the gallery settings');
|
||||||
|
} finally {
|
||||||
|
setSavingSettings(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const revoke = async () => {
|
const revoke = async () => {
|
||||||
if (!window.confirm('Turn off this proofing link? Anyone using it will lose access and its picks will be cleared.')) {
|
if (!window.confirm('Turn off this proofing link? Anyone using it will lose access and its picks will be cleared.')) {
|
||||||
return;
|
return;
|
||||||
@@ -212,6 +273,91 @@ export default function ShareModal({ event, photos, onClose, onToast, onProofPub
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div className="share-settings">
|
||||||
|
<div className="share-picks-head">
|
||||||
|
<span>Access and delivery</span>
|
||||||
|
<span className="muted small">
|
||||||
|
{share.settings?.passwordSet ? 'Password protected' : 'Anyone with the link'}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div className="share-settings-grid">
|
||||||
|
<label>
|
||||||
|
<span>Password</span>
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
value={passwordDraft}
|
||||||
|
autoComplete="new-password"
|
||||||
|
placeholder={
|
||||||
|
share.settings?.passwordSet ? 'Set — type a new one' : 'Optional'
|
||||||
|
}
|
||||||
|
onChange={(e) => setPasswordDraft(e.target.value)}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
<span>Expires</span>
|
||||||
|
<input
|
||||||
|
type="date"
|
||||||
|
value={expiryDraft}
|
||||||
|
onChange={(e) => setExpiryDraft(e.target.value)}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
<span>Download cap</span>
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
min={0}
|
||||||
|
step={1}
|
||||||
|
value={capDraft}
|
||||||
|
onChange={(e) => setCapDraft(e.target.value)}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label className="share-settings-wide">
|
||||||
|
<span>Watermark on proofs</span>
|
||||||
|
<input
|
||||||
|
value={watermarkDraft}
|
||||||
|
maxLength={80}
|
||||||
|
placeholder="© Studio name"
|
||||||
|
onChange={(e) => setWatermarkDraft(e.target.value)}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<div className="share-settings-actions">
|
||||||
|
<button
|
||||||
|
className={`chip tiny ${downloadsOn ? 'on' : ''}`}
|
||||||
|
onClick={() => setDownloadsOn((v) => !v)}
|
||||||
|
title="Let clients download their picks"
|
||||||
|
>
|
||||||
|
Downloads {downloadsOn ? 'on' : 'off'}
|
||||||
|
</button>
|
||||||
|
<span className="muted small">
|
||||||
|
Cap 0 means unlimited · {share.settings?.downloadCount ?? 0} used
|
||||||
|
</span>
|
||||||
|
<div className="spacer" />
|
||||||
|
{share.settings?.passwordSet && (
|
||||||
|
<button
|
||||||
|
className="btn ghost small"
|
||||||
|
disabled={savingSettings}
|
||||||
|
onClick={() => void saveSettings('')}
|
||||||
|
>
|
||||||
|
Remove password
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
<button
|
||||||
|
className="btn primary small"
|
||||||
|
disabled={savingSettings}
|
||||||
|
onClick={() =>
|
||||||
|
void saveSettings(passwordDraft.trim() ? passwordDraft.trim() : undefined)
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{savingSettings ? 'Saving…' : 'Save settings'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<p className="muted small">
|
||||||
|
Expiry closes the link at the end of that day. The watermark is rendered into
|
||||||
|
freshly published proofs; republish after changing it.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div className="share-publish">
|
<div className="share-publish">
|
||||||
<div>
|
<div>
|
||||||
<strong>Edited proofs</strong>
|
<strong>Edited proofs</strong>
|
||||||
|
|||||||
@@ -36,6 +36,7 @@ const GROUPS: { title: string; rows: [string, string][] }[] = [
|
|||||||
['C', 'Crop & straighten'],
|
['C', 'Crop & straighten'],
|
||||||
['Q', 'Spot healing brush'],
|
['Q', 'Spot healing brush'],
|
||||||
['M', 'Edit the selected local mask'],
|
['M', 'Edit the selected local mask'],
|
||||||
|
['O', 'Show or hide the mask tint'],
|
||||||
['Enter', 'Apply the crop'],
|
['Enter', 'Apply the crop'],
|
||||||
['\\ (hold)', 'Before / after'],
|
['\\ (hold)', 'Before / after'],
|
||||||
['1 – 5', 'Star rating'],
|
['1 – 5', 'Star rating'],
|
||||||
|
|||||||
@@ -0,0 +1,194 @@
|
|||||||
|
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||||
|
import { listTether, removeTetherFile, tetherFileUrl } from '../lib/api';
|
||||||
|
import type { TetherFile } from '../lib/api';
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
event: { id: string; name: string };
|
||||||
|
/** Imports the frames and resolves with how many became photos. */
|
||||||
|
onImport: (files: File[]) => Promise<number>;
|
||||||
|
onClose: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface LogEntry {
|
||||||
|
name: string;
|
||||||
|
at: number;
|
||||||
|
ok: boolean;
|
||||||
|
message: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const POLL_MS = 4000;
|
||||||
|
|
||||||
|
function stamp(ms: number) {
|
||||||
|
return new Date(ms).toLocaleTimeString(undefined, {
|
||||||
|
hour: '2-digit',
|
||||||
|
minute: '2-digit',
|
||||||
|
second: '2-digit',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tethering: watch a folder on the server and import what appears in it.
|
||||||
|
*
|
||||||
|
* Cameras and capture apps write into `<data>/tether/<event>`; this panel
|
||||||
|
* polls that folder, pulls each new frame, runs the normal import path (so raw
|
||||||
|
* decoding, metadata and cloud mirroring all behave the same as a drag and
|
||||||
|
* drop), then deletes the file from the folder. A file is only deleted after a
|
||||||
|
* successful import, so a closed tab or a dropped connection leaves it queued.
|
||||||
|
*/
|
||||||
|
export default function TetherPanel({ event, onImport, onClose }: Props) {
|
||||||
|
const [folder, setFolder] = useState('');
|
||||||
|
const [waiting, setWaiting] = useState<TetherFile[]>([]);
|
||||||
|
const [log, setLog] = useState<LogEntry[]>([]);
|
||||||
|
const [watching, setWatching] = useState(true);
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [imported, setImported] = useState(0);
|
||||||
|
const seen = useRef(new Set<string>());
|
||||||
|
const working = useRef(false);
|
||||||
|
const watchingRef = useRef(true);
|
||||||
|
watchingRef.current = watching;
|
||||||
|
|
||||||
|
const drain = useCallback(async () => {
|
||||||
|
if (working.current || !watchingRef.current) return;
|
||||||
|
working.current = true;
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
const state = await listTether(event.id);
|
||||||
|
setFolder(state.folder);
|
||||||
|
setWaiting(state.files);
|
||||||
|
setError(null);
|
||||||
|
for (const file of state.files) {
|
||||||
|
if (!watchingRef.current) break;
|
||||||
|
const key = `${file.name}:${file.mtime}:${file.size}`;
|
||||||
|
if (seen.current.has(key)) continue;
|
||||||
|
seen.current.add(key);
|
||||||
|
try {
|
||||||
|
const res = await fetch(tetherFileUrl(event.id, file.name), {
|
||||||
|
credentials: 'same-origin',
|
||||||
|
});
|
||||||
|
if (!res.ok) throw new Error(`Download failed (${res.status})`);
|
||||||
|
const blob = await res.blob();
|
||||||
|
const upload = new File([blob], file.name, {
|
||||||
|
type: blob.type || 'application/octet-stream',
|
||||||
|
lastModified: file.mtime,
|
||||||
|
});
|
||||||
|
const count = await onImport([upload]);
|
||||||
|
if (count < 1) {
|
||||||
|
seen.current.delete(key);
|
||||||
|
throw new Error('Nothing was imported');
|
||||||
|
}
|
||||||
|
await removeTetherFile(event.id, file.name).catch(() => undefined);
|
||||||
|
setImported((n) => n + count);
|
||||||
|
setLog((entries) =>
|
||||||
|
[{ name: file.name, at: Date.now(), ok: true, message: 'imported' }, ...entries].slice(0, 40),
|
||||||
|
);
|
||||||
|
setWaiting((files) => files.filter((item) => item.name !== file.name));
|
||||||
|
} catch (err) {
|
||||||
|
seen.current.delete(key);
|
||||||
|
setLog((entries) =>
|
||||||
|
[
|
||||||
|
{
|
||||||
|
name: file.name,
|
||||||
|
at: Date.now(),
|
||||||
|
ok: false,
|
||||||
|
message: err instanceof Error ? err.message : 'Import failed',
|
||||||
|
},
|
||||||
|
...entries,
|
||||||
|
].slice(0, 40),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : 'Could not read the tether folder');
|
||||||
|
} finally {
|
||||||
|
working.current = false;
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}, [event.id, onImport]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void drain();
|
||||||
|
const timer = window.setInterval(() => void drain(), POLL_MS);
|
||||||
|
return () => window.clearInterval(timer);
|
||||||
|
}, [drain]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className="modal-backdrop"
|
||||||
|
onPointerDown={(e) => e.target === e.currentTarget && onClose()}
|
||||||
|
>
|
||||||
|
<div className="modal tether-modal" role="dialog" aria-modal="true" aria-label="Tethering">
|
||||||
|
<header className="modal-head">
|
||||||
|
<div>
|
||||||
|
<h2>Tethering</h2>
|
||||||
|
<p className="muted small">
|
||||||
|
Frames dropped into the folder are imported into “{event.name}” automatically.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<button className="icon-btn" onClick={onClose} title="Close">
|
||||||
|
×
|
||||||
|
</button>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<div className="modal-body">
|
||||||
|
{error && <div className="banner error">{error}</div>}
|
||||||
|
|
||||||
|
<div className="tether-folder">
|
||||||
|
<span className="muted small">Watch folder on the server</span>
|
||||||
|
<code>{folder || 'Reading…'}</code>
|
||||||
|
<p className="muted small">
|
||||||
|
Point a tethering app, a camera's transfer folder or a sync client at this path.
|
||||||
|
JPEG, TIFF, WebP and camera raw files are picked up.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="tether-actions">
|
||||||
|
<button
|
||||||
|
className={`chip ${watching ? 'on' : ''}`}
|
||||||
|
onClick={() => setWatching((value) => !value)}
|
||||||
|
>
|
||||||
|
{watching ? 'Watching' : 'Paused'}
|
||||||
|
</button>
|
||||||
|
<span className="muted small">
|
||||||
|
{busy
|
||||||
|
? 'Pulling frames…'
|
||||||
|
: waiting.length
|
||||||
|
? `${waiting.length} frame${waiting.length === 1 ? '' : 's'} queued`
|
||||||
|
: 'Folder is empty'}
|
||||||
|
</span>
|
||||||
|
<div className="spacer" />
|
||||||
|
<span className="muted small">
|
||||||
|
{imported} imported this session
|
||||||
|
</span>
|
||||||
|
<button className="btn ghost small" onClick={() => void drain()} disabled={busy}>
|
||||||
|
Check now
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{log.length > 0 && (
|
||||||
|
<ul className="tether-log">
|
||||||
|
{log.map((entry, index) => (
|
||||||
|
<li key={`${entry.name}:${entry.at}:${index}`} className={entry.ok ? 'ok' : 'fail'}>
|
||||||
|
<span className="tether-time">{stamp(entry.at)}</span>
|
||||||
|
<span className="tether-name" title={entry.name}>
|
||||||
|
{entry.name}
|
||||||
|
</span>
|
||||||
|
<span className="muted small">{entry.message}</span>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<footer className="modal-foot">
|
||||||
|
<span className="muted small">
|
||||||
|
Files leave the folder only after a successful import.
|
||||||
|
</span>
|
||||||
|
<button className="btn" onClick={onClose}>
|
||||||
|
Done
|
||||||
|
</button>
|
||||||
|
</footer>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -7,11 +7,14 @@ interface Props {
|
|||||||
selectedCount: number;
|
selectedCount: number;
|
||||||
cloudLabel: string;
|
cloudLabel: string;
|
||||||
cloudOn: boolean;
|
cloudOn: boolean;
|
||||||
|
/** Desktop mode has no account, so the team-server button is not shown. */
|
||||||
|
localMode?: boolean;
|
||||||
onViewChange: (view: ViewMode) => void;
|
onViewChange: (view: ViewMode) => void;
|
||||||
onImport: () => void;
|
onImport: () => void;
|
||||||
onExport: () => void;
|
onExport: () => void;
|
||||||
onCloud: () => void;
|
onCloud: () => void;
|
||||||
onHelp: () => void;
|
onHelp: () => void;
|
||||||
|
onAbout: () => void;
|
||||||
onSearch: () => void;
|
onSearch: () => void;
|
||||||
onCatalog: () => void;
|
onCatalog: () => void;
|
||||||
canShare: boolean;
|
canShare: boolean;
|
||||||
@@ -25,11 +28,13 @@ export default function TopBar({
|
|||||||
selectedCount,
|
selectedCount,
|
||||||
cloudLabel,
|
cloudLabel,
|
||||||
cloudOn,
|
cloudOn,
|
||||||
|
localMode = false,
|
||||||
onViewChange,
|
onViewChange,
|
||||||
onImport,
|
onImport,
|
||||||
onExport,
|
onExport,
|
||||||
onCloud,
|
onCloud,
|
||||||
onHelp,
|
onHelp,
|
||||||
|
onAbout,
|
||||||
onSearch,
|
onSearch,
|
||||||
onCatalog,
|
onCatalog,
|
||||||
canShare,
|
canShare,
|
||||||
@@ -37,10 +42,16 @@ export default function TopBar({
|
|||||||
}: Props) {
|
}: Props) {
|
||||||
return (
|
return (
|
||||||
<header className="topbar">
|
<header className="topbar">
|
||||||
<div className="brand">
|
<button
|
||||||
<span className="dot" />
|
type="button"
|
||||||
|
className="brand brand-btn"
|
||||||
|
onClick={onAbout}
|
||||||
|
title="About Luminary"
|
||||||
|
aria-label="About Luminary"
|
||||||
|
>
|
||||||
|
<img className="brand-mark" src="/logo.png" alt="" height={20} />
|
||||||
Luminary
|
Luminary
|
||||||
</div>
|
</button>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
className="icon-btn mobile-only catalog-btn"
|
className="icon-btn mobile-only catalog-btn"
|
||||||
@@ -70,10 +81,12 @@ export default function TopBar({
|
|||||||
</nav>
|
</nav>
|
||||||
|
|
||||||
<div className="topbar-actions">
|
<div className="topbar-actions">
|
||||||
<button className={`cloud-pill ${cloudOn ? 'on' : ''}`} onClick={onCloud} title="Team server">
|
{!localMode && (
|
||||||
<span className="cloud-dot" />
|
<button className={`cloud-pill ${cloudOn ? 'on' : ''}`} onClick={onCloud} title="Team server">
|
||||||
{cloudLabel}
|
<span className="cloud-dot" />
|
||||||
</button>
|
{cloudLabel}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
{canShare && (
|
{canShare && (
|
||||||
<button className="btn ghost" onClick={onShare} title="Share this event for client proofing">
|
<button className="btn ghost" onClick={onShare} title="Share this event for client proofing">
|
||||||
Share
|
Share
|
||||||
|
|||||||
@@ -0,0 +1,40 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import { blendCoverage, maskSize } from './masks';
|
||||||
|
|
||||||
|
/** Coverage values are 0–1 inside the baker, which this keeps readable. */
|
||||||
|
describe('mask texture size', () => {
|
||||||
|
it('keeps square mask pixels so a round brush stays round', () => {
|
||||||
|
const tall = maskSize(3000, 9000);
|
||||||
|
expect(tall.h).toBeLessThanOrEqual(1400);
|
||||||
|
expect(tall.w / tall.h).toBeCloseTo(1 / 3, 2);
|
||||||
|
const wide = maskSize(15000, 1000);
|
||||||
|
expect(wide.h).toBeGreaterThanOrEqual(120);
|
||||||
|
expect(wide.w / wide.h).toBeCloseTo(15, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('uses the full width for a normal photo', () => {
|
||||||
|
expect(maskSize(3464, 5202)).toEqual({ w: 800, h: 1201 });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('mask group compositing', () => {
|
||||||
|
it('starts a group with the first shape whatever its mode says', () => {
|
||||||
|
expect(blendCoverage(0, 0.6, 'subtract', true)).toBe(0.6);
|
||||||
|
expect(blendCoverage(0, 0.6, 'intersect', true)).toBe(0.6);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('unions added shapes instead of stacking them', () => {
|
||||||
|
expect(blendCoverage(0.4, 0.7, 'add', false)).toBe(0.7);
|
||||||
|
expect(blendCoverage(0.7, 0.4, 'add', false)).toBe(0.7);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('subtracts coverage from the group', () => {
|
||||||
|
expect(blendCoverage(1, 0.25, 'subtract', false)).toBeCloseTo(0.75, 6);
|
||||||
|
expect(blendCoverage(1, 1, 'subtract', false)).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps only the overlap for an intersect shape', () => {
|
||||||
|
expect(blendCoverage(0.8, 0.5, 'intersect', false)).toBeCloseTo(0.4, 6);
|
||||||
|
expect(blendCoverage(0.8, 0, 'intersect', false)).toBe(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,15 +1,20 @@
|
|||||||
import type { LocalLayer } from '../types';
|
import type { LocalComponent, LocalLayer } from '../types';
|
||||||
import { MAX_LOCAL_LAYERS } from '../lib/edits';
|
import { MAX_LOCAL_LAYERS } from '../lib/edits';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Local masks are baked on the CPU into one RGBA texture, one layer per
|
* Local masks are baked on the CPU into two RGBA textures, one layer per
|
||||||
* channel, so the grade shader can apply up to four adjustments in a single
|
* channel, so the grade shader can apply up to eight adjustments in a single
|
||||||
* pass. The mask is source-space, which keeps brushes and gradients attached to
|
* pass. A layer's mask is a group of shapes composited in order: add unions,
|
||||||
* the picture through crops, straightening, zoom and lens correction.
|
* subtract cuts a hole, intersect keeps the overlap. The mask is source-space,
|
||||||
|
* which keeps brushes and gradients attached to the picture through crops,
|
||||||
|
* straightening, zoom and lens correction.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
export interface PackedMasks {
|
export interface PackedMasks {
|
||||||
|
/** Layers 1–4, one per channel. */
|
||||||
data: Uint8Array;
|
data: Uint8Array;
|
||||||
|
/** Layers 5–8, one per channel. */
|
||||||
|
data2: Uint8Array;
|
||||||
w: number;
|
w: number;
|
||||||
h: number;
|
h: number;
|
||||||
}
|
}
|
||||||
@@ -20,19 +25,22 @@ export function maskSignature(layers: LocalLayer[], srcW: number, srcH: number)
|
|||||||
srcW,
|
srcW,
|
||||||
srcH,
|
srcH,
|
||||||
layers: layers.slice(0, MAX_LOCAL_LAYERS).map((layer) => ({
|
layers: layers.slice(0, MAX_LOCAL_LAYERS).map((layer) => ({
|
||||||
kind: layer.kind,
|
components: (layer.components ?? []).map((component) => ({
|
||||||
inverted: layer.inverted,
|
kind: component.kind,
|
||||||
feather: layer.feather,
|
mode: component.mode,
|
||||||
brush: layer.brush,
|
inverted: component.inverted,
|
||||||
linear: layer.linear,
|
feather: component.feather,
|
||||||
radial: layer.radial,
|
brush: component.brush,
|
||||||
raster: layer.raster
|
linear: component.linear,
|
||||||
? {
|
radial: component.radial,
|
||||||
width: layer.raster.width,
|
raster: component.raster
|
||||||
height: layer.raster.height,
|
? {
|
||||||
hash: rasterHash(layer.raster.data),
|
width: component.raster.width,
|
||||||
}
|
height: component.raster.height,
|
||||||
: null,
|
hash: rasterHash(component.raster.data),
|
||||||
|
}
|
||||||
|
: null,
|
||||||
|
})),
|
||||||
})),
|
})),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -46,8 +54,8 @@ function rasterHash(data: string) {
|
|||||||
return `${data.length}:${hash >>> 0}`;
|
return `${data.length}:${hash >>> 0}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
function drawRaster(ctx: CanvasRenderingContext2D, layer: LocalLayer, w: number, h: number) {
|
function drawRaster(ctx: CanvasRenderingContext2D, component: LocalComponent, w: number, h: number) {
|
||||||
const mask = layer.raster;
|
const mask = component.raster;
|
||||||
if (!mask) return;
|
if (!mask) return;
|
||||||
try {
|
try {
|
||||||
const binary = atob(mask.data);
|
const binary = atob(mask.data);
|
||||||
@@ -79,13 +87,13 @@ function makeCanvas(w: number, h: number) {
|
|||||||
return canvas;
|
return canvas;
|
||||||
}
|
}
|
||||||
|
|
||||||
function drawRadial(ctx: CanvasRenderingContext2D, layer: LocalLayer, w: number, h: number) {
|
function drawRadial(ctx: CanvasRenderingContext2D, component: LocalComponent, w: number, h: number) {
|
||||||
const { cx, cy, rx, ry } = layer.radial;
|
const { cx, cy, rx, ry } = component.radial;
|
||||||
ctx.save();
|
ctx.save();
|
||||||
ctx.translate(cx * w, cy * h);
|
ctx.translate(cx * w, cy * h);
|
||||||
ctx.scale(Math.max(1, rx * w), Math.max(1, ry * h));
|
ctx.scale(Math.max(1, rx * w), Math.max(1, ry * h));
|
||||||
const gradient = ctx.createRadialGradient(0, 0, 0, 0, 0, 1);
|
const gradient = ctx.createRadialGradient(0, 0, 0, 0, 0, 1);
|
||||||
const inner = Math.max(0, Math.min(0.98, 1 - layer.feather / 100));
|
const inner = Math.max(0, Math.min(0.98, 1 - component.feather / 100));
|
||||||
gradient.addColorStop(0, 'rgba(255,255,255,1)');
|
gradient.addColorStop(0, 'rgba(255,255,255,1)');
|
||||||
if (inner > 0.001) gradient.addColorStop(inner, 'rgba(255,255,255,1)');
|
if (inner > 0.001) gradient.addColorStop(inner, 'rgba(255,255,255,1)');
|
||||||
gradient.addColorStop(1, 'rgba(255,255,255,0)');
|
gradient.addColorStop(1, 'rgba(255,255,255,0)');
|
||||||
@@ -96,8 +104,8 @@ function drawRadial(ctx: CanvasRenderingContext2D, layer: LocalLayer, w: number,
|
|||||||
ctx.restore();
|
ctx.restore();
|
||||||
}
|
}
|
||||||
|
|
||||||
function drawLinear(ctx: CanvasRenderingContext2D, layer: LocalLayer, w: number, h: number) {
|
function drawLinear(ctx: CanvasRenderingContext2D, component: LocalComponent, w: number, h: number) {
|
||||||
const { x1, y1, x2, y2 } = layer.linear;
|
const { x1, y1, x2, y2 } = component.linear;
|
||||||
const gradient = ctx.createLinearGradient(x1 * w, y1 * h, x2 * w, y2 * h);
|
const gradient = ctx.createLinearGradient(x1 * w, y1 * h, x2 * w, y2 * h);
|
||||||
gradient.addColorStop(0, 'rgba(255,255,255,1)');
|
gradient.addColorStop(0, 'rgba(255,255,255,1)');
|
||||||
gradient.addColorStop(1, 'rgba(255,255,255,0)');
|
gradient.addColorStop(1, 'rgba(255,255,255,0)');
|
||||||
@@ -105,70 +113,163 @@ function drawLinear(ctx: CanvasRenderingContext2D, layer: LocalLayer, w: number,
|
|||||||
ctx.fillRect(0, 0, w, h);
|
ctx.fillRect(0, 0, w, h);
|
||||||
}
|
}
|
||||||
|
|
||||||
function drawBrush(ctx: CanvasRenderingContext2D, layer: LocalLayer, w: number, h: number) {
|
/**
|
||||||
ctx.lineCap = 'round';
|
* One brush dab: white, solid out to `1 - feather` of the radius and fading to
|
||||||
ctx.lineJoin = 'round';
|
* nothing at the rim. Feather is the width of that band, so a stroke softens
|
||||||
for (const stroke of layer.brush.strokes) {
|
* inside the brush outline instead of spreading a halo past it.
|
||||||
|
*/
|
||||||
|
function brushDab(feather: number) {
|
||||||
|
const size = 64;
|
||||||
|
const canvas = makeCanvas(size, size);
|
||||||
|
const ctx = canvas.getContext('2d');
|
||||||
|
if (!ctx) return canvas;
|
||||||
|
const r = size / 2;
|
||||||
|
// A hair of softness even at 0 keeps the rim from aliasing on screen.
|
||||||
|
const soft = Math.max(0.02, Math.min(1, feather / 100));
|
||||||
|
const gradient = ctx.createRadialGradient(r, r, r * (1 - soft), r, r, r);
|
||||||
|
gradient.addColorStop(0, 'rgba(255,255,255,1)');
|
||||||
|
gradient.addColorStop(0.45, 'rgba(255,255,255,0.88)');
|
||||||
|
gradient.addColorStop(1, 'rgba(255,255,255,0)');
|
||||||
|
ctx.fillStyle = gradient;
|
||||||
|
ctx.fillRect(0, 0, size, size);
|
||||||
|
return canvas;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Stamps the dab along the path. A stroked line can only have a hard edge, so
|
||||||
|
* the stroke is drawn as overlapping dabs: the rim is the dab's falloff, which
|
||||||
|
* keeps the mask inside the brush circle and smooth at every size.
|
||||||
|
*/
|
||||||
|
function drawBrush(ctx: CanvasRenderingContext2D, component: LocalComponent, w: number, h: number) {
|
||||||
|
const dab = brushDab(component.feather);
|
||||||
|
for (const stroke of component.brush.strokes) {
|
||||||
if (!stroke.points.length) continue;
|
if (!stroke.points.length) continue;
|
||||||
const width = Math.max(1, stroke.size * 2 * w);
|
const radius = Math.max(1, stroke.size * w);
|
||||||
|
const stamp = (x: number, y: number) =>
|
||||||
|
ctx.drawImage(dab, x - radius, y - radius, radius * 2, radius * 2);
|
||||||
ctx.globalCompositeOperation = stroke.erase ? 'destination-out' : 'source-over';
|
ctx.globalCompositeOperation = stroke.erase ? 'destination-out' : 'source-over';
|
||||||
ctx.strokeStyle = 'rgba(255,255,255,1)';
|
const first = stroke.points[0];
|
||||||
ctx.fillStyle = 'rgba(255,255,255,1)';
|
stamp(first.x * w, first.y * h);
|
||||||
ctx.lineWidth = width;
|
// Close enough that consecutive dabs overlap well inside the soft band.
|
||||||
if (stroke.points.length === 1) {
|
const spacing = Math.max(0.75, radius * 0.35);
|
||||||
ctx.beginPath();
|
|
||||||
ctx.arc(stroke.points[0].x * w, stroke.points[0].y * h, width / 2, 0, Math.PI * 2);
|
|
||||||
ctx.fill();
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
ctx.beginPath();
|
|
||||||
ctx.moveTo(stroke.points[0].x * w, stroke.points[0].y * h);
|
|
||||||
for (let i = 1; i < stroke.points.length; i++) {
|
for (let i = 1; i < stroke.points.length; i++) {
|
||||||
ctx.lineTo(stroke.points[i].x * w, stroke.points[i].y * h);
|
const a = stroke.points[i - 1];
|
||||||
|
const b = stroke.points[i];
|
||||||
|
const dx = (b.x - a.x) * w;
|
||||||
|
const dy = (b.y - a.y) * h;
|
||||||
|
const steps = Math.max(1, Math.ceil(Math.hypot(dx, dy) / spacing));
|
||||||
|
for (let step = 1; step <= steps; step++) {
|
||||||
|
stamp(a.x * w + (dx * step) / steps, a.y * h + (dy * step) / steps);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
ctx.stroke();
|
|
||||||
}
|
}
|
||||||
ctx.globalCompositeOperation = 'source-over';
|
ctx.globalCompositeOperation = 'source-over';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function drawComponent(ctx: CanvasRenderingContext2D, component: LocalComponent, w: number, h: number) {
|
||||||
|
if (component.kind === 'radial') drawRadial(ctx, component, w, h);
|
||||||
|
else if (component.kind === 'linear') drawLinear(ctx, component, w, h);
|
||||||
|
else if (component.kind === 'raster') drawRaster(ctx, component, w, h);
|
||||||
|
else drawBrush(ctx, component, w, h);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* How one shape's coverage joins the accumulated mask inside its layer. The
|
||||||
|
* first shape starts the group, so its mode is ignored: there is nothing to
|
||||||
|
* subtract from or intersect with yet.
|
||||||
|
*/
|
||||||
|
export function blendCoverage(
|
||||||
|
acc: number,
|
||||||
|
value: number,
|
||||||
|
mode: LocalComponent['mode'],
|
||||||
|
first: boolean,
|
||||||
|
) {
|
||||||
|
if (first) return value;
|
||||||
|
if (mode === 'subtract') return acc * (1 - value);
|
||||||
|
if (mode === 'intersect') return acc * value;
|
||||||
|
return Math.max(acc, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mask texture size. Pixels are square, so both dimensions scale together with
|
||||||
|
* the source: clamping only the height would squeeze every round dab into an
|
||||||
|
* ellipse on tall or wide frames, so the width shrinks instead.
|
||||||
|
*/
|
||||||
|
export function maskSize(srcW: number, srcH: number) {
|
||||||
|
const safeW = Math.max(1, srcW);
|
||||||
|
const safeH = Math.max(1, srcH);
|
||||||
|
let w = 800;
|
||||||
|
let h = Math.round((w * safeH) / safeW);
|
||||||
|
const limit = h > 1400 ? 1400 : h < 120 ? 120 : 0;
|
||||||
|
if (limit) {
|
||||||
|
h = limit;
|
||||||
|
w = Math.max(160, Math.round((h * safeW) / safeH));
|
||||||
|
}
|
||||||
|
return { w, h: Math.max(1, h) };
|
||||||
|
}
|
||||||
|
|
||||||
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, h } = maskSize(srcW, srcH);
|
||||||
const h = Math.max(120, Math.min(1400, Math.round((w * Math.max(1, srcH)) / Math.max(1, srcW))));
|
|
||||||
const out = new Uint8Array(w * h * 4);
|
const out = new Uint8Array(w * h * 4);
|
||||||
|
const out2 = new Uint8Array(w * h * 4);
|
||||||
const count = Math.min(MAX_LOCAL_LAYERS, layers.length);
|
const count = Math.min(MAX_LOCAL_LAYERS, layers.length);
|
||||||
if (!count) return { data: out, w, h };
|
if (!count) return { data: out, data2: out2, w, h };
|
||||||
|
|
||||||
for (let index = 0; index < count; index++) {
|
for (let index = 0; index < count; index++) {
|
||||||
const layer = layers[index];
|
const layer = layers[index];
|
||||||
const canvas = makeCanvas(w, h);
|
const components = layer.components ?? [];
|
||||||
const ctx = canvas.getContext('2d');
|
const acc = new Uint8Array(w * h);
|
||||||
if (!ctx) continue;
|
let first = true;
|
||||||
ctx.clearRect(0, 0, w, h);
|
|
||||||
|
|
||||||
if (layer.kind === 'radial') drawRadial(ctx, layer, w, h);
|
for (const component of components) {
|
||||||
else if (layer.kind === 'linear') drawLinear(ctx, layer, w, h);
|
const canvas = makeCanvas(w, h);
|
||||||
else if (layer.kind === 'raster') drawRaster(ctx, layer, w, h);
|
const ctx = canvas.getContext('2d');
|
||||||
else drawBrush(ctx, layer, w, h);
|
if (!ctx) continue;
|
||||||
|
ctx.clearRect(0, 0, w, h);
|
||||||
|
drawComponent(ctx, component, w, h);
|
||||||
|
|
||||||
let source = canvas;
|
let source = canvas;
|
||||||
if ((layer.kind === 'brush' || layer.kind === 'raster') && layer.feather > 0) {
|
if (component.kind === 'raster') {
|
||||||
const blur = makeCanvas(w, h);
|
// Generated masks are low-resolution coverage, so their feather is tied
|
||||||
const bctx = blur.getContext('2d');
|
// to the frame width and only ever loosens the outside edge.
|
||||||
if (bctx) {
|
source = featherMask(canvas, ((component.feather / 100) * w) / 16);
|
||||||
bctx.filter = `blur(${Math.max(0.1, ((layer.feather / 100) * w) / 16)}px)`;
|
|
||||||
bctx.drawImage(canvas, 0, 0);
|
|
||||||
source = blur;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const pixels = source.getContext('2d')?.getImageData(0, 0, w, h).data;
|
||||||
|
if (!pixels) continue;
|
||||||
|
for (let p = 0, o = 0; p < pixels.length; p += 4, o++) {
|
||||||
|
let value = pixels[p + 3] / 255;
|
||||||
|
if (component.inverted) value = 1 - value;
|
||||||
|
acc[o] = Math.round(blendCoverage(acc[o] / 255, value, component.mode, first) * 255);
|
||||||
|
}
|
||||||
|
first = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
const pixels = source.getContext('2d')?.getImageData(0, 0, w, h).data;
|
const channel = index % 4;
|
||||||
if (!pixels) continue;
|
const target = index < 4 ? out : out2;
|
||||||
const channel = index;
|
for (let o = 0; o < acc.length; o++) target[o * 4 + channel] = acc[o];
|
||||||
for (let p = 0, o = 0; p < pixels.length; p += 4, o += 4) {
|
|
||||||
const alpha = pixels[p + 3];
|
|
||||||
out[o + channel] = layer.inverted ? 255 - alpha : alpha;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return { data: out, w, h };
|
return { data: out, data2: out2, w, h };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,83 +0,0 @@
|
|||||||
/**
|
|
||||||
* The published package's `types` entry points at a file that is not shipped in
|
|
||||||
* 0.1.3, so declare the small surface we use here.
|
|
||||||
*/
|
|
||||||
declare module '@neoanaloglabkk/lensfun-wasm' {
|
|
||||||
export interface LensfunInitOptions {
|
|
||||||
moduleFactory?: (options?: Record<string, unknown>) => Promise<unknown>;
|
|
||||||
moduleJsUrl?: string;
|
|
||||||
wasmUrl?: string;
|
|
||||||
dataUrl?: string;
|
|
||||||
dbPath?: string;
|
|
||||||
autoInitDb?: boolean;
|
|
||||||
locateFile?: (path: string, prefix: string) => string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface LensMatch {
|
|
||||||
handle: number;
|
|
||||||
maker: string;
|
|
||||||
model: string;
|
|
||||||
score: number;
|
|
||||||
minFocal: number;
|
|
||||||
maxFocal: number;
|
|
||||||
minAperture: number;
|
|
||||||
maxAperture: number;
|
|
||||||
cropFactor: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface CameraMatch {
|
|
||||||
maker: string;
|
|
||||||
model: string;
|
|
||||||
variant: string;
|
|
||||||
mount: string;
|
|
||||||
cropFactor: number;
|
|
||||||
score: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface SearchLensesInput {
|
|
||||||
lensMaker?: string;
|
|
||||||
lensModel: string;
|
|
||||||
cameraMaker?: string;
|
|
||||||
cameraModel?: string;
|
|
||||||
searchFlags?: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface SearchCamerasInput {
|
|
||||||
maker?: string;
|
|
||||||
model?: string;
|
|
||||||
searchFlags?: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface CorrectionInput {
|
|
||||||
lensHandle: number;
|
|
||||||
width: number;
|
|
||||||
height: number;
|
|
||||||
focal: number;
|
|
||||||
crop: number;
|
|
||||||
step?: number;
|
|
||||||
reverse?: boolean;
|
|
||||||
includeTca?: boolean;
|
|
||||||
includeVignetting?: boolean;
|
|
||||||
aperture?: number;
|
|
||||||
distance?: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface CorrectionMaps {
|
|
||||||
gridWidth: number;
|
|
||||||
gridHeight: number;
|
|
||||||
step: number;
|
|
||||||
geometry: Float32Array;
|
|
||||||
tca?: Float32Array;
|
|
||||||
vignetting?: Float32Array;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface LensfunClient {
|
|
||||||
dispose(): void;
|
|
||||||
searchLenses(input: SearchLensesInput): LensMatch[];
|
|
||||||
searchCameras(input: SearchCamerasInput): CameraMatch[];
|
|
||||||
getAvailableModifications(lensHandle: number, crop: number): number;
|
|
||||||
buildCorrectionMaps(input: CorrectionInput): CorrectionMaps;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function createLensfun(options?: LensfunInitOptions): Promise<LensfunClient>;
|
|
||||||
}
|
|
||||||