Refactor to TypeScript ES modules and add metadata sidebar
This commit is contained in:
@@ -1,3 +1,4 @@
|
||||
/app/node_modules/
|
||||
/app/dist/
|
||||
/app/public/js/
|
||||
/app/.env
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
node_modules/
|
||||
dist/
|
||||
app/public/js/
|
||||
.idea
|
||||
.env
|
||||
.directory
|
||||
/app/config.dev.json
|
||||
|
||||
+190
@@ -0,0 +1,190 @@
|
||||
# Contributing to Immich Public Proxy
|
||||
|
||||
Thanks for your interest in contributing. This guide covers what the project is, what it deliberately is not, and how to work on it productively. It is written for both human contributors and LLM coding agents - please read it end to end before opening a PR or making suggestions.
|
||||
|
||||
## Project philosophy and hard constraints
|
||||
|
||||
Immich Public Proxy (IPP) exists to share Immich photos publicly without exposing the Immich instance itself. Everything about the design follows from that single goal.
|
||||
|
||||
**Optimize for auditability.** Because IPP proxies a private photo library, the code stays small enough to audit for security-relevant behavior. New features that meaningfully grow the *attack surface* need a strong justification, even if they're functionally useful. "Lean" here is a security property, not a line-count target - features that add purely client-side UI complexity (a sidebar, a date-grouped view) don't trip this constraint; features that add new ways the server can talk to Immich, accept input, or persist state do.
|
||||
|
||||
**Read-only access to Immich. This is non-negotiable.** IPP must never modify Immich, its data, or its files. It does not use an Immich API key. The only Immich endpoints it calls are the ones reachable via a public share key. This rule rules out a large class of feature requests; see "What will not be accepted" below.
|
||||
|
||||
**Stateless.** No database, no user accounts, no long-lived secrets beyond an encrypted cookie session for share passwords. Avoid adding persistent state. If you think you need a cache, estimate the real cost of not having it first.
|
||||
|
||||
**Privacy at the boundary.** Any invalid, expired, or upstream-failed request returns 404. Do not leak upstream Immich status codes, error bodies, or share existence to the client.
|
||||
|
||||
## Architecture at a glance
|
||||
|
||||
Request flow for a typical share URL like `https://proxy.example.com/share/<key>`:
|
||||
|
||||
1. Express routes in `app/src/index.ts` receive the request.
|
||||
2. `app/src/immich.ts` fetches the share metadata from Immich over the local network, validates it, and returns the asset list.
|
||||
3. For a gallery, `app/src/gallery/builder.ts` builds the view-model and `app/src/view/gallery.tsx` renders it server-side with Preact. The page embeds a JSON init block consumed by the client.
|
||||
4. The client gallery lives in `app/src/client/` (TypeScript ES modules, compiled file-for-file by `tsc` into `app/public/js/`). It wires PhotoSwipe v5 with a virtualized justified-rows layout. There is no client-side framework hydration.
|
||||
5. For individual assets (image, video, thumbnail, download, zip), Express streams bytes from Immich back to the client without touching disk via `app/src/stream/`.
|
||||
|
||||
### Repository layout
|
||||
|
||||
```
|
||||
.github/workflows/ CI: builds and pushes Docker image on v* tags
|
||||
app/
|
||||
config.json Runtime configuration, overrideable via volume or inline
|
||||
package.json Node project manifest
|
||||
tsconfig.json Server TypeScript config (compiles src/ to dist/)
|
||||
tsconfig.client.json Client TypeScript config (compiles src/client/ + src/shared/ to public/js/)
|
||||
vitest.config.ts Unit-test runner config
|
||||
src/
|
||||
index.ts Express setup and routes
|
||||
immich.ts Upstream Immich API calls, share + token caches
|
||||
encrypt.ts Cookie-session encryption for password-protected shares
|
||||
invalidRequestHandler.ts Centralised 404 / custom-response handling
|
||||
http.ts Operator-configured HTTP response headers
|
||||
share.ts Share-level info + policy (title, canDownload)
|
||||
types.ts Server-only TypeScript types
|
||||
config/
|
||||
loader.ts loadConfig() reads env / file, applies migrations
|
||||
migrations.ts Backward-compat shims for legacy config-key shapes
|
||||
access.ts getConfigOption() reads the loaded config
|
||||
gallery/
|
||||
builder.ts Gallery view-model construction
|
||||
exif.ts EXIF / location whitelisting for the sidebar
|
||||
filename.ts Download filename derivation
|
||||
stream/
|
||||
asset.ts Single-asset stream (image / video / thumbnail)
|
||||
download.ts Zip pipeline (concurrency-bounded, retry, abort)
|
||||
utils/
|
||||
log.ts Timestamped log.info / log.warn / log.error
|
||||
sanitize.ts Filename-character sanitization
|
||||
text.ts escapeHtml + toString narrowing
|
||||
view/ Preact SSR templates (.tsx)
|
||||
shared/types.ts Types shared between server SSR and client (GalleryItem, etc.)
|
||||
client/ Client gallery, virtualization, lightbox, sidebar
|
||||
public/ Static assets served as-is
|
||||
photoswipe/ Vendored PhotoSwipe v5
|
||||
thumbhash/, fonts/, images/
|
||||
style.css, photoswipe-overrides.css
|
||||
tests/ Vitest unit tests for pure functions
|
||||
docs/ User-facing docs linked from the README
|
||||
Dockerfile Multi-stage build, runs as the non-root `node` user
|
||||
docker-compose.yml Reference deployment
|
||||
```
|
||||
|
||||
The server tsconfig excludes `src/client/`; the client tsconfig only includes `src/client/` and `src/shared/`. Compiled client output (`app/public/js/`) is gitignored.
|
||||
|
||||
## Tech stack
|
||||
|
||||
- **Node.js** (LTS, per the `node:lts-alpine` base image).
|
||||
- **TypeScript** with `strictNullChecks` enabled.
|
||||
- Server: target ES6, module CommonJS (`tsconfig.json`).
|
||||
- Client: target ES2022, module ESNext, browser libs (`tsconfig.client.json`). Compiled file-for-file by `tsc`; no bundler.
|
||||
- **Express 4** for HTTP.
|
||||
- **Preact** with `preact-render-to-string` for SSR-only templates. No client-side Preact.
|
||||
- **PhotoSwipe v5** for the lightbox (vendored under `app/public/photoswipe/`).
|
||||
- **thumbhash** for low-res placeholders (vendored).
|
||||
- **archiver** for streaming "download all" zips.
|
||||
- **cookie-session** for password-protected share sessions.
|
||||
- **tsx** for running the server in dev with watch + ESM-native imports.
|
||||
- **concurrently** to run the server and client tsc watchers side-by-side in dev.
|
||||
- **vitest** for unit tests on pure functions.
|
||||
- **ESLint** with `eslint-config-standard`.
|
||||
|
||||
## Development setup
|
||||
|
||||
```bash
|
||||
cd app
|
||||
npm install
|
||||
npm run dev
|
||||
```
|
||||
|
||||
Required environment variables (set in `app/.env` or your shell):
|
||||
|
||||
- `IMMICH_URL` - local URL to your Immich instance. Should not be public.
|
||||
- `PUBLIC_BASE_URL` - optional. Public base URL for IPP without trailing slash. Omit to derive from request hostname.
|
||||
- `IPP_PORT` - optional. Default 3000.
|
||||
|
||||
To exercise the full gallery flow you need a real Immich instance you can hit, with at least one public share created. The README has the user-facing setup steps for spinning that up.
|
||||
|
||||
Configuration overrides go in `app/config.json` or inline via env (see `docs/inline-configuration.md`). Always read config through `getConfigOption('ipp.path.to.key', defaultValue)` rather than reading the JSON directly.
|
||||
|
||||
## Build, lint, test
|
||||
|
||||
```bash
|
||||
npm run build # both server and client tsc; output to dist/ and public/js/
|
||||
npm run build:server # server only
|
||||
npm run build:client # client only
|
||||
npm test # vitest run (unit tests on pure functions)
|
||||
npm run test:watch # vitest in watch mode
|
||||
npm run test:container # build a podman image and run it locally
|
||||
npx eslint src/ # lint
|
||||
```
|
||||
|
||||
`npm test` runs the pure-function unit tests in `app/tests/`. Add tests there for any new pure logic (filename derivation, escaping, layout math, EXIF whitelisting, etc.); skip HTTP plumbing.
|
||||
|
||||
Beyond unit tests, exercise the gallery end-to-end against a real Immich instance: happy path plus failure paths (expired share, trashed asset, password protection, very large albums, video range requests).
|
||||
|
||||
## Conventions for adding code
|
||||
|
||||
**Configuration.** New options go in `app/config.json` under the appropriate `ipp.*` namespace, read via `getConfigOption`, and documented in the relevant table in `README.md`. Prefer a group toggle plus per-field overrides over a single flat boolean when several related toggles cluster, following the `ipp.showMetadata` pattern. Existing keys keep working; if you rename one, add a backward-compat shim with a startup deprecation warning, as was done for the v2.0 gallery key rename.
|
||||
|
||||
**Privacy of responses.** Always return 404 for invalid or upstream-failed requests. Use `invalidRequestHandler` rather than crafting ad-hoc error responses. Do not surface Immich status codes or error bodies to the client.
|
||||
|
||||
**Escaping.** Any string that originates from Immich and is embedded into HTML by the SSR templates must be escaped (use `escapeHtml` from `utils/text.ts`). Strings that cross to the client via the init JSON block stay as plain text and are rendered with `textContent`, not `innerHTML` - that retired the "pre-escaped HTML over the wire" contract that the early gallery shipped with.
|
||||
|
||||
**PhotoSwipe UI.** Custom toolbar buttons, captions, and panels are registered through `lightbox.pswp.ui.registerElement`. The back button, download, fullscreen, and caption registrations live in `app/src/client/lightbox-ui.ts`; the info sidebar (a substantial UI element) lives in `app/src/client/sidebar.ts`. New small registrations join `lightbox-ui.ts`; anything panel-sized gets its own file.
|
||||
|
||||
**Streaming.** Assets are streamed from Immich to the client without buffering to disk. Keep it that way. The `archiver` zip flow is also fully streamed (with per-asset retry, an idle-timeout transform, and abort-on-failure semantics).
|
||||
|
||||
**File organisation.** Group functions by cohesion, not by file count. A file deserves its own name when it carries a coherent concept worth a separate filename - "filename sanitization" or "config loader" pass; "narrow unknown to string" does not. When several small helpers share a theme, group them in one file (`utils/text.ts` for escaping + narrowing; `share.ts` for share-level info + policy). When a single concern is substantial enough to dominate a file on its own, give it its own name (`config/migrations.ts`, `stream/download.ts`). IPP optimises for audit reading rather than tree-shakeable reuse, so fewer cohesive files beat many one-export micro-modules. Same lens applies on the client (`app/src/client/`): each module is a viewport-of-code that earns its name.
|
||||
|
||||
Where to put a new function: ask what category of thing it is, not where it gets called from. Share-level policy decisions and share-derived info go in `share.ts`. Per-asset view-model transforms (filename derivation, EXIF whitelisting) go alongside `gallery/builder.ts`. HTTP response setup driven by operator config goes in `http.ts`. Streaming pipelines go in `stream/`. If a new function doesn't fit any existing category, prefer adding to the closest existing file over creating a new single-function module - revisit when a real second member of the category appears.
|
||||
|
||||
**No client framework, no bundler.** The client is TypeScript compiled file-for-file by `tsc` into plain ES modules served by Express static. Do not introduce a frontend framework (React / Svelte / Vue / Solid) or a bundler (Webpack / Rollup / Vite / Parcel). PhotoSwipe is loaded as ESM directly. Inter-module imports inside `app/src/client/` use `.js` extensions in the source - that's required by the client's `moduleResolution: bundler` setup and matches what the browser fetches.
|
||||
|
||||
**Code style.** ESLint standard config. Run lint locally before opening a PR.
|
||||
|
||||
## Release process
|
||||
|
||||
Releases are triggered by pushing a `v*` tag. The `.github/workflows/ci.yaml` workflow builds a multi-arch (`linux/amd64`, `linux/arm64`) image, pushes to both GHCR and Docker Hub, and attaches a build-provenance attestation to each registry.
|
||||
|
||||
Maintainer workflow for a release:
|
||||
|
||||
1. Update `app/package.json` version with `npm version <patch|minor|major>` from inside `app/`.
|
||||
2. Push the resulting tag. CI does the rest.
|
||||
|
||||
Do not push tags as part of a PR; releases are cut by the maintainer.
|
||||
|
||||
## Pull requests
|
||||
|
||||
For anything non-trivial, open a [Feature Request discussion](https://github.com/alangrainger/immich-public-proxy/discussions/categories/feature-requests) first. The maintainer would rather discuss fit with the read-only/lean philosophy before you spend time on a PR.
|
||||
|
||||
- Branch from `main`.
|
||||
- Update the README config tables if you added or changed config keys.
|
||||
- If your change has a user-visible behavior, include a one-line note in the PR description about how to exercise it.
|
||||
|
||||
## What will not be accepted
|
||||
|
||||
Repeating the README's feature-request guidance for emphasis:
|
||||
|
||||
- Anything that modifies Immich or its files in any way.
|
||||
- Anything that requires an Immich API key or other privileged access.
|
||||
- Uploading photos to Immich.
|
||||
- Persistent state, databases, or user accounts on the IPP side.
|
||||
- Client-side bundlers (Webpack / Rollup / Vite / Parcel) or frontend frameworks (React / Svelte / Vue / Solid). Client code is TypeScript compiled file-for-file by `tsc` to plain ES modules served directly - no bundling, no framework runtime, no plugin ecosystem.
|
||||
- Features that meaningfully expand the proxy's attack surface for a niche use case.
|
||||
|
||||
If your idea sits near these lines, raise it as a discussion before coding.
|
||||
|
||||
## For LLM agents
|
||||
|
||||
If you are an AI coding agent working on this repo, the rules above apply to you. A few specific reminders:
|
||||
|
||||
- **Read this whole file before suggesting or making changes.** The read-only, lean, stateless constraints are project-defining and must not be relaxed for convenience.
|
||||
- **Do not suggest features from the "will not be accepted" list**, even if they are technically interesting. Push back on requests that would violate the constraints, and explain why.
|
||||
- **Do not add backwards-compatibility shims** unless a config key is being renamed or a public behavior is changing. Dead-code shims rot.
|
||||
- **Do not add caches, memoization, queues, or background jobs** without first estimating the real cost of not having them. The existing share-metadata cache in `immich.ts` is for freshness coalescing, not optimisation; mirror that bar.
|
||||
- **Do not add error handling for cases that cannot happen.** Trust internal invariants. Validate only at the boundary (incoming request, Immich response).
|
||||
- **Default to writing no comments.** Add a comment only when the *why* is non-obvious: a security-relevant invariant, a workaround for a specific upstream bug, or behavior that would surprise a careful reader. Do not narrate the *what*.
|
||||
- **Match the project's existing style.** Server-side Preact SSR, TypeScript ES modules on the client (compiled by `tsc`, no bundler, no framework), plain CSS. Do not introduce new patterns without discussion.
|
||||
|
||||
If something in this guide conflicts with an instruction you have been given, stop and raise the conflict rather than silently working around it.
|
||||
+2
-1
@@ -5,7 +5,8 @@ WORKDIR /app
|
||||
COPY --chown=node:node app/ ./
|
||||
|
||||
RUN npm ci \
|
||||
&& npx tsc
|
||||
&& npx tsc \
|
||||
&& npx tsc -p tsconfig.client.json
|
||||
|
||||
FROM node:lts-alpine AS runner
|
||||
|
||||
|
||||
@@ -236,11 +236,75 @@ Example: hide the download button inside the lightbox even though zip downloads
|
||||
|
||||
### Metadata
|
||||
|
||||
Configured under `ipp.showMetadata`.
|
||||
Configured under `ipp.showMetadata`. The lightbox includes a slide-in info sidebar (toggle with the **i** key or the info button in the toolbar) that surfaces whatever metadata you opt into here.
|
||||
|
||||
| Option | Type | Description |
|
||||
|---------------|--------|----------------------------------------------------|
|
||||
| `description` | `bool` | Show the description as a caption below the photo. |
|
||||
|---------------|----------|---------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| `description` | `object` | Where to show the description. `{ "caption": bool, "sidebar": bool }`. Both default `false`. See [Description](#description). |
|
||||
| `exif` | `object` | Camera / file EXIF group. Set `enabled: true` to expose any of the per-field flags below. See [EXIF group](#exif-group). |
|
||||
| `location` | `object` | Location group (city / state / country / GPS). Set `enabled: true` to expose any of the per-field flags below. See [Location group](#location-group). |
|
||||
|
||||
Within each group, the master `enabled` toggle controls whether the group's fields are sent at all. Per-field flags default to `true` once the group is enabled, so you can turn off individual fields without renaming or removing them.
|
||||
|
||||
IPP only sends a field if **both** the group's `enabled` is true AND the field's flag is true. If Immich itself isn't exposing metadata for the share (the per-share toggle on the Immich side), no metadata is available regardless of these settings.
|
||||
|
||||
The info sidebar (and its toolbar toggle button) only appear when there is at least one section the operator has opted into - i.e. `description.sidebar`, `exif.enabled`, or `location.enabled` is true. With all three off, the sidebar UI is suppressed.
|
||||
|
||||
#### Description
|
||||
|
||||
Under `ipp.showMetadata.description`:
|
||||
|
||||
| Option | Type | Description |
|
||||
|-----------|--------|--------------------------------------------------------------------------|
|
||||
| `caption` | `bool` | Show the description below the photo as a lightbox caption. |
|
||||
| `sidebar` | `bool` | Show the description at the top of the info sidebar. |
|
||||
|
||||
Set both to show in both places; set neither and the description is not included at all. (Legacy `description: true` / `description: false` boolean form is still accepted and migrates to `{caption, sidebar}` of the same value with a deprecation warning.)
|
||||
|
||||
#### EXIF group
|
||||
|
||||
Under `ipp.showMetadata.exif`:
|
||||
|
||||
| Option | Type | Description |
|
||||
|---------------------|--------|--------------------------------------------------------------------------|
|
||||
| `enabled` | `bool` | Master switch for the EXIF group. Default `false`. |
|
||||
| `dateTimeOriginal` | `bool` | Show the date the photo was taken (per EXIF). |
|
||||
| `fileName` | `bool` | Show the original filename. |
|
||||
| `dimensions` | `bool` | Show width x height and megapixel count. |
|
||||
| `fileSize` | `bool` | Show the file size. |
|
||||
| `make` | `bool` | Camera manufacturer (e.g. "Canon"). |
|
||||
| `model` | `bool` | Camera model (e.g. "EOS R5"). |
|
||||
| `lensModel` | `bool` | Lens model. |
|
||||
| `exposureTime` | `bool` | Shutter speed (e.g. "1/200"). |
|
||||
| `iso` | `bool` | ISO sensitivity. |
|
||||
| `fNumber` | `bool` | Aperture f-number. |
|
||||
| `focalLength` | `bool` | Focal length in millimetres. |
|
||||
|
||||
#### Location group
|
||||
|
||||
Under `ipp.showMetadata.location`:
|
||||
|
||||
| Option | Type | Description |
|
||||
|------------|--------|----------------------------------------------------------------------|
|
||||
| `enabled` | `bool` | Master switch for the location group. Default `false`. |
|
||||
| `city` | `bool` | Show city. |
|
||||
| `state` | `bool` | Show state / region. |
|
||||
| `country` | `bool` | Show country. |
|
||||
| `gps` | `bool` | Show GPS coordinates and an "Open in OpenStreetMap" link. |
|
||||
|
||||
Example: show description in the sidebar only (not as a caption), show full EXIF, and hide GPS coordinates while keeping city / state / country:
|
||||
|
||||
```json
|
||||
{
|
||||
"ipp": {
|
||||
"showMetadata": {
|
||||
"description": { "caption": false, "sidebar": true },
|
||||
"exif": { "enabled": true },
|
||||
"location": { "enabled": true, "gps": false }
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Customising your error response pages
|
||||
|
||||
@@ -278,8 +342,8 @@ From inside a Docker container, you can't reach another container using `localho
|
||||
You can [add feature requests here](https://github.com/alangrainger/immich-public-proxy/discussions/categories/feature-requests?discussions_q=is%3Aopen+category%3A%22Feature+Requests%22+sort%3Atop),
|
||||
however my goal with this project is to keep it as lean as possible.
|
||||
|
||||
Due to the sensitivity of data contained within Immich, I want anyone with a bit of coding knowledge
|
||||
to be able to read this codebase and fully understand everything it is doing.
|
||||
Due to the sensitivity of data contained within Immich, this project optimises for auditability: the code
|
||||
stays small enough that someone with coding experience can review it for security-relevant behavior.
|
||||
|
||||
The most basic rule for this project is that it has **read-only** access to Immich.
|
||||
|
||||
|
||||
+25
-1
@@ -11,7 +11,31 @@
|
||||
"allowSlugLinks": true,
|
||||
"showHomePage": true,
|
||||
"showMetadata": {
|
||||
"description": false
|
||||
"description": {
|
||||
"caption": false,
|
||||
"sidebar": false
|
||||
},
|
||||
"exif": {
|
||||
"enabled": false,
|
||||
"dateTimeOriginal": true,
|
||||
"fileName": true,
|
||||
"dimensions": true,
|
||||
"fileSize": true,
|
||||
"make": true,
|
||||
"model": true,
|
||||
"lensModel": true,
|
||||
"exposureTime": true,
|
||||
"iso": true,
|
||||
"fNumber": true,
|
||||
"focalLength": true
|
||||
},
|
||||
"location": {
|
||||
"enabled": false,
|
||||
"city": true,
|
||||
"state": true,
|
||||
"country": true,
|
||||
"gps": true
|
||||
}
|
||||
},
|
||||
"customInvalidResponse": false,
|
||||
"gallery": {
|
||||
|
||||
Generated
+2330
-323
File diff suppressed because it is too large
Load Diff
+15
-9
@@ -2,9 +2,13 @@
|
||||
"name": "immich-public-proxy",
|
||||
"version": "2.2.1",
|
||||
"scripts": {
|
||||
"dev": "ts-node src/index.ts",
|
||||
"build": "npx tsc",
|
||||
"test": "podman build --build-arg PACKAGE_VERSION=$(npm pkg get version | xargs) --format docker -t immich-proxy-test .. && podman run --init -it -p=3000:3000 --env-file .env --restart=always immich-proxy-test",
|
||||
"dev": "concurrently -n server,client -c blue,green \"tsx watch src/index.ts\" \"tsc -w -p tsconfig.client.json\"",
|
||||
"build": "tsc && tsc -p tsconfig.client.json",
|
||||
"build:server": "tsc",
|
||||
"build:client": "tsc -p tsconfig.client.json",
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest",
|
||||
"test:container": "podman build --build-arg PACKAGE_VERSION=$(npm pkg get version | xargs) --format docker -t immich-proxy-test .. && podman run --init -it -p=3000:3000 --env-file .env --restart=always immich-proxy-test",
|
||||
"start": "node dist/index.js"
|
||||
},
|
||||
"author": "Alan Grainger",
|
||||
@@ -30,12 +34,14 @@
|
||||
"@types/archiver": "^6.0.3",
|
||||
"@types/cookie-session": "^2.0.49",
|
||||
"@types/express": "^4.17.21",
|
||||
"@types/node": "^16.18.111",
|
||||
"@typescript-eslint/eslint-plugin": "5.29.0",
|
||||
"@typescript-eslint/parser": "5.29.0",
|
||||
"eslint": "^8.49.0",
|
||||
"@types/node": "^22",
|
||||
"@typescript-eslint/eslint-plugin": "^7",
|
||||
"@typescript-eslint/parser": "^7",
|
||||
"concurrently": "^10.0.3",
|
||||
"eslint": "^8.57.0",
|
||||
"eslint-config-standard": "^17.1.0",
|
||||
"ts-node": "^10.9.2",
|
||||
"typescript": "^5.6.2"
|
||||
"tsx": "^4",
|
||||
"typescript": "^5.6.2",
|
||||
"vitest": "^2"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,8 +51,11 @@
|
||||
color: var(--pswp-icon-color);
|
||||
}
|
||||
|
||||
/* Hide PhotoSwipe's default top-right X close button - we use a top-left
|
||||
back arrow instead (registered as `back-button` in client/lightbox-ui.ts),
|
||||
matching Immich's native asset-viewer affordance. */
|
||||
.pswp__button--close {
|
||||
margin-right: 10px;
|
||||
display: none;
|
||||
}
|
||||
|
||||
.pswp__button--download-button {
|
||||
|
||||
+161
-2
@@ -99,8 +99,8 @@ html, body {
|
||||
background-size: cover;
|
||||
background-position: center;
|
||||
background-repeat: no-repeat;
|
||||
/* left / top / width / height set per-tile by layoutGrid() in web.js;
|
||||
background-image is the decoded thumbhash placeholder, set by web.js. */
|
||||
/* left / top / width / height set per-tile by the client layout module;
|
||||
background-image is the decoded thumbhash placeholder, set by `tiles.ts`. */
|
||||
}
|
||||
|
||||
#gallery img {
|
||||
@@ -385,3 +385,162 @@ html, body {
|
||||
font-size: 13px;
|
||||
}
|
||||
}
|
||||
|
||||
/* ============================================================================
|
||||
Info sidebar. Docks to the right of the lightbox on desktop; becomes a
|
||||
bottom sheet on narrow viewports.
|
||||
============================================================================ */
|
||||
|
||||
.ipp-sidebar {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
width: 360px;
|
||||
background: var(--color-bg);
|
||||
color: var(--color-fg);
|
||||
border-left: 1px solid var(--color-gray);
|
||||
z-index: 1700;
|
||||
transform: translateX(100%);
|
||||
transition: transform 200ms ease;
|
||||
overflow-y: auto;
|
||||
font-family: var(--font-sans);
|
||||
font-size: 14px;
|
||||
line-height: 1.5;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding: 0 8px 24px;
|
||||
}
|
||||
html.ipp-sidebar-open .ipp-sidebar {
|
||||
transform: translateX(0);
|
||||
}
|
||||
|
||||
/* On narrow viewports the sidebar becomes a bottom sheet so the photo isn't
|
||||
crowded out. PhotoSwipe paddingFn skips the right-padding in this mode. */
|
||||
@media (max-width: 640px) {
|
||||
.ipp-sidebar {
|
||||
top: auto;
|
||||
width: 100%;
|
||||
height: 60vh;
|
||||
border-left: none;
|
||||
border-top: 1px solid var(--color-gray);
|
||||
transform: translateY(100%);
|
||||
}
|
||||
html.ipp-sidebar-open .ipp-sidebar {
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
.ipp-sidebar-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 12px 4px 8px;
|
||||
position: sticky;
|
||||
top: 0;
|
||||
background: var(--color-bg);
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.ipp-sidebar-close {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border: none;
|
||||
border-radius: 50%;
|
||||
background: transparent;
|
||||
color: var(--color-fg);
|
||||
cursor: pointer;
|
||||
padding: 0;
|
||||
}
|
||||
.ipp-sidebar-close:hover {
|
||||
background: rgba(127, 127, 127, 0.15);
|
||||
}
|
||||
.ipp-sidebar-close svg {
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
}
|
||||
|
||||
.ipp-sidebar-title {
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
.ipp-sidebar-section {
|
||||
padding: 8px 16px;
|
||||
}
|
||||
|
||||
.ipp-sidebar-heading {
|
||||
font-size: 13px;
|
||||
opacity: 0.7;
|
||||
margin: 8px 0 4px;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.ipp-sidebar-description {
|
||||
margin: 0;
|
||||
padding: 8px 0 16px;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.ipp-sidebar-row {
|
||||
display: flex;
|
||||
gap: 16px;
|
||||
padding: 12px 0;
|
||||
}
|
||||
.ipp-sidebar-row-icon {
|
||||
flex: 0 0 auto;
|
||||
width: 24px;
|
||||
color: var(--color-fg);
|
||||
opacity: 0.8;
|
||||
}
|
||||
.ipp-sidebar-row-icon svg {
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
display: block;
|
||||
}
|
||||
.ipp-sidebar-row-body {
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
}
|
||||
.ipp-sidebar-row-body p {
|
||||
margin: 0 0 4px;
|
||||
word-break: break-word;
|
||||
}
|
||||
.ipp-sidebar-filename {
|
||||
font-weight: 500;
|
||||
}
|
||||
.ipp-sidebar-lens {
|
||||
font-weight: 500;
|
||||
}
|
||||
.ipp-sidebar-stats {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px 12px;
|
||||
font-size: 13px;
|
||||
opacity: 0.8;
|
||||
}
|
||||
|
||||
.ipp-sidebar-date {
|
||||
padding: 12px 0;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.ipp-sidebar-coords {
|
||||
font-size: 13px;
|
||||
opacity: 0.7;
|
||||
margin: 4px 0 4px;
|
||||
}
|
||||
.ipp-sidebar-osm {
|
||||
color: var(--color-primary);
|
||||
text-decoration: underline;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.ipp-sidebar-empty {
|
||||
padding: 16px;
|
||||
opacity: 0.6;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
@@ -1,895 +0,0 @@
|
||||
// @ts-check
|
||||
// ============================================================================
|
||||
// Gallery client - virtualized justified/square grid, PhotoSwipe v5 lightbox
|
||||
//
|
||||
// Layout is pre-computed for all items based on container width. Only tiles
|
||||
// within viewport ± 1 viewport-height buffer exist in the DOM at any moment.
|
||||
// PhotoSwipe runs with a full dataSource array so the lightbox navigates
|
||||
// across all items regardless of which tiles are currently rendered.
|
||||
// ============================================================================
|
||||
|
||||
// Runtime URLs served by Express, not filesystem paths. TypeScript's resolver
|
||||
// can't follow them, so we silence its module-not-found errors here. The
|
||||
// imports themselves work fine at runtime.
|
||||
// @ts-ignore
|
||||
import PhotoSwipeLightbox from '/share/static/photoswipe/photoswipe-lightbox.esm.js'
|
||||
// @ts-ignore
|
||||
import { thumbHashToDataURL } from '/share/static/thumbhash/thumbhash.js'
|
||||
|
||||
/**
|
||||
* @typedef {Object} GalleryItem
|
||||
* @property {string} id
|
||||
* @property {'IMAGE'|'VIDEO'} type
|
||||
* @property {string} previewUrl
|
||||
* @property {string} thumbnailUrl
|
||||
* @property {string} [downloadUrl]
|
||||
* @property {string} [videoData] JSON-stringified video source info
|
||||
* @property {string} [description] Escaped HTML fragment for the lightbox caption
|
||||
* @property {string} downloadFilename
|
||||
* @property {number} [width]
|
||||
* @property {number} [height]
|
||||
* @property {string} [thumbhash]
|
||||
* @property {string} [fileCreatedAt] ISO date
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {Object} LightboxConfig
|
||||
* @property {boolean} [showArrows]
|
||||
* @property {boolean} [showDownload]
|
||||
* @property {boolean} [mobileArrows]
|
||||
* @property {Record<string, unknown>} [options]
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {Object} InitParams
|
||||
* @property {GalleryItem[]} [items]
|
||||
* @property {number} [openItem] 1-based; opens lightbox on the Nth item
|
||||
* @property {LightboxConfig} [lightboxConfig]
|
||||
* @property {boolean} [groupByDate]
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {Object} LayoutEntry
|
||||
* @property {number} index
|
||||
* @property {number} left
|
||||
* @property {number} top
|
||||
* @property {number} width
|
||||
* @property {number} height
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {Object} HeaderEntry
|
||||
* @property {string} label
|
||||
* @property {number} top
|
||||
* @property {number} height
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {Object} GroupSpec
|
||||
* @property {string | null} label
|
||||
* @property {number[]} indices
|
||||
*/
|
||||
|
||||
// Justified-rows target row height (matches Immich's main view)
|
||||
const TARGET_ROW_HEIGHT = 235
|
||||
const GAP = 4
|
||||
const MOBILE_BREAKPOINT = 640
|
||||
const MOBILE_COLS = 3
|
||||
const IMAGE_LOAD_MARGIN_PX = 300
|
||||
const SCROLL_SETTLE_MS = 100
|
||||
const BUFFER_VIEWPORTS = 1
|
||||
// Height reserved for each month header (must agree with .group-header CSS)
|
||||
const HEADER_HEIGHT = 48
|
||||
// Vertical gap between groups
|
||||
const GROUP_GAP = 16
|
||||
|
||||
// MDI icons (Apache 2.0). Same icon set Immich uses for its viewer.
|
||||
const ICON_DOWNLOAD = '<svg class="pswp__icn" viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M5,20H19V18H5M19,9H15V3H9V9H5L12,16L19,9Z"/></svg>'
|
||||
const ICON_FULLSCREEN = '<svg class="pswp__icn" viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M5,5H10V7H7V10H5V5M14,5H19V10H17V7H14V5M17,14H19V19H14V17H17V14M10,17V19H5V14H7V17H10Z"/></svg>'
|
||||
const ICON_FULLSCREEN_EXIT = '<svg class="pswp__icn" viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M14,14H19V16H16V19H14V14M5,14H10V19H8V16H5V14M8,5H10V10H5V8H8V5M19,8V10H14V5H16V8H19Z"/></svg>'
|
||||
|
||||
// ----- module state ---------------------------------------------------------
|
||||
|
||||
/** @type {GalleryItem[]} */
|
||||
let items = []
|
||||
/** @type {LayoutEntry[]} - sparse, indexed by GalleryItem index */
|
||||
let layout = []
|
||||
/** @type {HeaderEntry[]} - empty when groupByDate is off */
|
||||
let headers = []
|
||||
let groupByDate = false
|
||||
/** @type {HTMLElement | null} */
|
||||
let container = null
|
||||
/** @type {any} - PhotoSwipeLightbox instance; external module, leave untyped */
|
||||
let lightbox = null
|
||||
/** @type {LightboxConfig} */
|
||||
let lightboxConfig = {}
|
||||
/** @type {boolean} - true while our pushed history entry is live */
|
||||
let lightboxPushedHistory = false
|
||||
/** @type {boolean} - guards against re-entering the popstate handler during our own history.back() */
|
||||
let closingFromHistory = false
|
||||
/** @type {Map<number, HTMLAnchorElement>} */
|
||||
const renderedTiles = new Map()
|
||||
/** @type {Map<string, HTMLElement>} */
|
||||
const renderedHeaders = new Map()
|
||||
let lastContainerW = 0
|
||||
|
||||
// Selection mode (mode-toggle UX: hidden checkmarks until activated)
|
||||
let selectMode = false
|
||||
/** @type {Set<string>} - set of asset IDs */
|
||||
const selected = new Set()
|
||||
/** @type {HTMLElement | null} */
|
||||
let toolbarEl = null
|
||||
/** @type {HTMLElement | null} */
|
||||
let countEl = null
|
||||
/** @type {HTMLButtonElement | null} */
|
||||
let selectAllBtn = null
|
||||
/** @type {HTMLButtonElement | null} */
|
||||
let cancelBtn = null
|
||||
/** @type {HTMLButtonElement | null} */
|
||||
let downloadBtn = null
|
||||
|
||||
// Inline SVG for the check icon shown inside selected tiles' checkmark circle
|
||||
const CHECK_SVG = '<svg viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M21,7L9,19L3.5,13.5L4.91,12.09L9,16.17L19.59,5.59L21,7Z"/></svg>'
|
||||
|
||||
// Long-press threshold for entering select mode via touch/mouse
|
||||
const LONG_PRESS_MS = 500
|
||||
|
||||
// ----- layout computation ---------------------------------------------------
|
||||
|
||||
function computeLayout (containerW) {
|
||||
const tileLayout = new Array(items.length)
|
||||
const newHeaders = []
|
||||
const groups = groupByDate ? groupItemsByMonth() : [{ label: null, indices: itemIndices() }]
|
||||
const isMobile = containerW < MOBILE_BREAKPOINT
|
||||
let y = 0
|
||||
for (let g = 0; g < groups.length; g++) {
|
||||
const group = groups[g]
|
||||
if (group.label) {
|
||||
newHeaders.push({ label: group.label, top: y, height: HEADER_HEIGHT })
|
||||
y += HEADER_HEIGHT
|
||||
}
|
||||
y = isMobile
|
||||
? layoutSquareGroup(containerW, group.indices, y, tileLayout)
|
||||
: layoutJustifiedGroup(containerW, group.indices, y, tileLayout)
|
||||
if (g < groups.length - 1) y += GROUP_GAP
|
||||
}
|
||||
return {
|
||||
layout: tileLayout,
|
||||
headers: newHeaders,
|
||||
totalHeight: Math.max(0, y)
|
||||
}
|
||||
}
|
||||
|
||||
function itemIndices () {
|
||||
const out = new Array(items.length)
|
||||
for (let i = 0; i < items.length; i++) out[i] = i
|
||||
return out
|
||||
}
|
||||
|
||||
/** @returns {GroupSpec[]} */
|
||||
function groupItemsByMonth () {
|
||||
// Preserve item order (already sorted desc by render.ts when grouping is on)
|
||||
/** @type {Map<string, GroupSpec>} */
|
||||
const map = new Map()
|
||||
for (let i = 0; i < items.length; i++) {
|
||||
const key = (items[i].fileCreatedAt || '').slice(0, 7) || 'undated'
|
||||
let g = map.get(key)
|
||||
if (!g) {
|
||||
g = { label: monthLabel(key), indices: [] }
|
||||
map.set(key, g)
|
||||
}
|
||||
g.indices.push(i)
|
||||
}
|
||||
return Array.from(map.values())
|
||||
}
|
||||
|
||||
/** @param {string} key @returns {string} */
|
||||
function monthLabel (key) {
|
||||
if (key === 'undated') return 'Undated'
|
||||
const parts = key.split('-')
|
||||
const y = Number(parts[0])
|
||||
const m = Number(parts[1])
|
||||
if (!y || !m) return key
|
||||
// Intl.DateTimeFormat picks up the browser's locale; UTC timeZone keeps
|
||||
// the displayed month consistent with the UTC YYYY-MM bucket key.
|
||||
return new Intl.DateTimeFormat(undefined, {
|
||||
year: 'numeric',
|
||||
month: 'long',
|
||||
timeZone: 'UTC'
|
||||
}).format(new Date(Date.UTC(y, m - 1, 1)))
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {number} containerW
|
||||
* @param {number[]} indices
|
||||
* @param {number} startY
|
||||
* @param {LayoutEntry[]} tileLayout
|
||||
* @returns {number} The y position past the last tile (no trailing gap)
|
||||
*/
|
||||
function layoutSquareGroup (containerW, indices, startY, tileLayout) {
|
||||
const tileSize = Math.floor((containerW - (MOBILE_COLS - 1) * GAP) / MOBILE_COLS)
|
||||
let col = 0
|
||||
let x = 0
|
||||
let y = startY
|
||||
for (const idx of indices) {
|
||||
tileLayout[idx] = { index: idx, left: x, top: y, width: tileSize, height: tileSize }
|
||||
col++
|
||||
if (col === MOBILE_COLS) {
|
||||
col = 0
|
||||
x = 0
|
||||
y += tileSize + GAP
|
||||
} else {
|
||||
x += tileSize + GAP
|
||||
}
|
||||
}
|
||||
// If the last row was partial, advance y to past it
|
||||
if (col > 0) y += tileSize
|
||||
// Otherwise back off the trailing inter-row gap
|
||||
else if (y > startY) y -= GAP
|
||||
return y
|
||||
}
|
||||
|
||||
function layoutJustifiedGroup (containerW, indices, startY, tileLayout) {
|
||||
let rowItems = []
|
||||
let aspectSum = 0
|
||||
let y = startY
|
||||
|
||||
const applyRow = (rowItems, height, isLastRow) => {
|
||||
const intHeight = Math.floor(height)
|
||||
let x = 0
|
||||
rowItems.forEach(({ idx, aspect }, i) => {
|
||||
const isFinalInRow = i === rowItems.length - 1
|
||||
const w = (!isLastRow && isFinalInRow)
|
||||
? containerW - x
|
||||
: Math.floor(aspect * height)
|
||||
tileLayout[idx] = { index: idx, left: x, top: y, width: w, height: intHeight }
|
||||
x += w + GAP
|
||||
})
|
||||
y += intHeight + GAP
|
||||
}
|
||||
|
||||
for (const idx of indices) {
|
||||
const item = items[idx]
|
||||
const w = item.width || 1
|
||||
const h = item.height || 1
|
||||
const aspect = w / h
|
||||
rowItems.push({ idx, aspect })
|
||||
aspectSum += aspect
|
||||
const projectedH = (containerW - (rowItems.length - 1) * GAP) / aspectSum
|
||||
if (projectedH <= TARGET_ROW_HEIGHT) {
|
||||
applyRow(rowItems, projectedH, false)
|
||||
rowItems = []
|
||||
aspectSum = 0
|
||||
}
|
||||
}
|
||||
if (rowItems.length) applyRow(rowItems, TARGET_ROW_HEIGHT, true)
|
||||
|
||||
// y advanced past the last row's trailing gap; back off
|
||||
return y > startY ? y - GAP : y
|
||||
}
|
||||
|
||||
// ----- tile DOM construction ------------------------------------------------
|
||||
|
||||
function onThumbError () {
|
||||
this.closest('a').classList.add('thumb-error')
|
||||
}
|
||||
|
||||
// Cache of decoded thumbhash → PNG data URL. Same thumbhash on multiple
|
||||
// tile-creations (revisits during virtualization) reuses the same URL.
|
||||
const thumbhashCache = new Map()
|
||||
|
||||
function decodeThumbhash (base64) {
|
||||
const cached = thumbhashCache.get(base64)
|
||||
if (cached) return cached
|
||||
try {
|
||||
const binary = atob(base64)
|
||||
const bytes = new Uint8Array(binary.length)
|
||||
for (let i = 0; i < bytes.length; i++) bytes[i] = binary.charCodeAt(i)
|
||||
const url = thumbHashToDataURL(bytes)
|
||||
thumbhashCache.set(base64, url)
|
||||
return url
|
||||
} catch (e) {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function createTile (index) {
|
||||
const item = items[index]
|
||||
const l = layout[index]
|
||||
const a = document.createElement('a')
|
||||
a.dataset.index = index
|
||||
if (item.type !== 'VIDEO') a.href = item.previewUrl
|
||||
a.style.left = l.left + 'px'
|
||||
a.style.top = l.top + 'px'
|
||||
a.style.width = l.width + 'px'
|
||||
a.style.height = l.height + 'px'
|
||||
|
||||
if (item.thumbhash) {
|
||||
const url = decodeThumbhash(item.thumbhash)
|
||||
if (url) a.style.backgroundImage = 'url(' + url + ')'
|
||||
}
|
||||
|
||||
const img = document.createElement('img')
|
||||
// alt left empty: browsers paint alt text over the thumbhash background
|
||||
// while the thumbnail downloads. Description (if any) is shown in the
|
||||
// lightbox caption instead.
|
||||
img.alt = ''
|
||||
img.dataset.src = item.thumbnailUrl
|
||||
img.onerror = onThumbError
|
||||
// Mark the image as drawable once its bytes are decoded; the CSS rule
|
||||
// `#gallery img.loaded` fades opacity from 0 to 1 so the thumbhash blurs
|
||||
// into the sharp image instead of snapping (and masks Chrome/Edge's brief
|
||||
// white flash between `img.src` being set and the bytes actually painting).
|
||||
img.onload = () => img.classList.add('loaded')
|
||||
a.appendChild(img)
|
||||
|
||||
if (item.type === 'VIDEO') {
|
||||
const playIcon = document.createElement('div')
|
||||
playIcon.className = 'play-icon'
|
||||
a.appendChild(playIcon)
|
||||
}
|
||||
|
||||
// Selection checkmark (rendered only when select mode is even possible -
|
||||
// i.e. when the page included the toolbar element)
|
||||
if (toolbarEl) {
|
||||
const check = document.createElement('div')
|
||||
check.className = 'tile-check'
|
||||
check.innerHTML = CHECK_SVG
|
||||
check.addEventListener('click', (e) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
if (!selectMode) enterSelectMode()
|
||||
toggleSelection(item.id)
|
||||
})
|
||||
a.appendChild(check)
|
||||
if (selected.has(item.id)) a.classList.add('selected')
|
||||
attachLongPress(a, item.id)
|
||||
}
|
||||
|
||||
a.addEventListener('click', (e) => {
|
||||
e.preventDefault()
|
||||
if (selectMode) {
|
||||
toggleSelection(item.id)
|
||||
} else {
|
||||
openLightbox(index)
|
||||
}
|
||||
})
|
||||
|
||||
return a
|
||||
}
|
||||
|
||||
// ----- long-press (enter select mode) --------------------------------------
|
||||
|
||||
function attachLongPress (tile, id) {
|
||||
let timer = null
|
||||
let pressed = false
|
||||
const cancel = () => {
|
||||
if (timer) { clearTimeout(timer); timer = null }
|
||||
}
|
||||
tile.addEventListener('pointerdown', (e) => {
|
||||
// Ignore right/middle clicks
|
||||
if (e.button !== undefined && e.button !== 0) return
|
||||
pressed = false
|
||||
timer = setTimeout(() => {
|
||||
timer = null
|
||||
pressed = true
|
||||
if (!selectMode) enterSelectMode()
|
||||
toggleSelection(id)
|
||||
}, LONG_PRESS_MS)
|
||||
})
|
||||
tile.addEventListener('pointerup', cancel)
|
||||
tile.addEventListener('pointercancel', cancel)
|
||||
tile.addEventListener('pointerleave', cancel)
|
||||
tile.addEventListener('pointermove', (e) => {
|
||||
// Cancel long-press if pointer moves significantly (scroll, drag)
|
||||
if (Math.abs(e.movementX) + Math.abs(e.movementY) > 6) cancel()
|
||||
})
|
||||
// Swallow the synthetic click that follows a successful long-press so it
|
||||
// doesn't open the lightbox.
|
||||
tile.addEventListener('click', (e) => {
|
||||
if (pressed) {
|
||||
pressed = false
|
||||
e.preventDefault()
|
||||
e.stopImmediatePropagation()
|
||||
}
|
||||
}, true)
|
||||
}
|
||||
|
||||
// ----- selection state -----------------------------------------------------
|
||||
|
||||
function enterSelectMode () {
|
||||
if (selectMode) return
|
||||
selectMode = true
|
||||
if (container) container.classList.add('select-mode')
|
||||
if (toolbarEl) toolbarEl.hidden = false
|
||||
}
|
||||
|
||||
function exitSelectMode () {
|
||||
if (!selectMode) return
|
||||
selectMode = false
|
||||
// Clear DOM markers on the tiles currently in the DOM
|
||||
for (const a of renderedTiles.values()) a.classList.remove('selected')
|
||||
selected.clear()
|
||||
if (container) container.classList.remove('select-mode')
|
||||
if (toolbarEl) toolbarEl.hidden = true
|
||||
updateSelectionUI()
|
||||
}
|
||||
|
||||
function toggleSelection (id) {
|
||||
if (selected.has(id)) selected.delete(id)
|
||||
else selected.add(id)
|
||||
const idx = items.findIndex(it => it.id === id)
|
||||
const tile = idx >= 0 ? renderedTiles.get(idx) : null
|
||||
if (tile) tile.classList.toggle('selected', selected.has(id))
|
||||
// Auto-exit if user deselected the last item
|
||||
if (selected.size === 0 && selectMode) exitSelectMode()
|
||||
else updateSelectionUI()
|
||||
}
|
||||
|
||||
function updateSelectionUI () {
|
||||
if (countEl) {
|
||||
countEl.textContent = selected.size + ' selected'
|
||||
}
|
||||
if (downloadBtn) downloadBtn.disabled = selected.size === 0
|
||||
if (selectAllBtn) {
|
||||
selectAllBtn.textContent =
|
||||
selected.size === items.length ? 'Deselect all' : 'Select all'
|
||||
}
|
||||
}
|
||||
|
||||
function selectAllOrNone () {
|
||||
if (selected.size === items.length) {
|
||||
// Deselect all but keep select mode active
|
||||
for (const a of renderedTiles.values()) a.classList.remove('selected')
|
||||
selected.clear()
|
||||
updateSelectionUI()
|
||||
} else {
|
||||
if (!selectMode) enterSelectMode()
|
||||
for (const item of items) selected.add(item.id)
|
||||
for (const a of renderedTiles.values()) a.classList.add('selected')
|
||||
updateSelectionUI()
|
||||
}
|
||||
}
|
||||
|
||||
function downloadSelected () {
|
||||
if (selected.size === 0) return
|
||||
// Single selection: download the file directly so the user gets the image
|
||||
// (or video) instead of a one-entry zip.
|
||||
if (selected.size === 1) {
|
||||
const id = selected.values().next().value
|
||||
const item = items.find(it => it.id === id)
|
||||
if (item && item.downloadUrl) {
|
||||
const a = document.createElement('a')
|
||||
a.href = item.downloadUrl
|
||||
a.download = item.downloadFilename || ''
|
||||
document.body.appendChild(a)
|
||||
a.click()
|
||||
a.remove()
|
||||
return
|
||||
}
|
||||
}
|
||||
// Form POST so the browser handles streaming the zip directly to disk.
|
||||
const form = document.createElement('form')
|
||||
form.method = 'POST'
|
||||
form.action = window.location.pathname + '/download'
|
||||
const input = document.createElement('input')
|
||||
input.type = 'hidden'
|
||||
input.name = 'assets'
|
||||
input.value = JSON.stringify(Array.from(selected))
|
||||
form.appendChild(input)
|
||||
document.body.appendChild(form)
|
||||
form.submit()
|
||||
form.remove()
|
||||
}
|
||||
|
||||
function setupToolbar () {
|
||||
toolbarEl = document.getElementById('select-toolbar')
|
||||
// No toolbar means downloads aren't allowed for this share; nothing to wire
|
||||
if (!toolbarEl) return
|
||||
countEl = document.getElementById('select-count')
|
||||
selectAllBtn = /** @type {HTMLButtonElement | null} */ (document.getElementById('select-all'))
|
||||
cancelBtn = /** @type {HTMLButtonElement | null} */ (document.getElementById('select-cancel'))
|
||||
downloadBtn = /** @type {HTMLButtonElement | null} */ (document.getElementById('select-download'))
|
||||
if (cancelBtn) cancelBtn.addEventListener('click', exitSelectMode)
|
||||
if (selectAllBtn) selectAllBtn.addEventListener('click', selectAllOrNone)
|
||||
if (downloadBtn) downloadBtn.addEventListener('click', downloadSelected)
|
||||
updateSelectionUI()
|
||||
}
|
||||
|
||||
// ----- virtualization -------------------------------------------------------
|
||||
|
||||
function getVisibleRange () {
|
||||
const containerTop = container.getBoundingClientRect().top
|
||||
const viewportTopInContainer = -containerTop
|
||||
const viewportBottomInContainer = viewportTopInContainer + window.innerHeight
|
||||
const buffer = window.innerHeight * BUFFER_VIEWPORTS
|
||||
return {
|
||||
top: viewportTopInContainer - buffer,
|
||||
bottom: viewportBottomInContainer + buffer
|
||||
}
|
||||
}
|
||||
|
||||
function createHeader (header) {
|
||||
const el = document.createElement('h2')
|
||||
el.className = 'group-header'
|
||||
el.style.top = header.top + 'px'
|
||||
el.textContent = header.label
|
||||
return el
|
||||
}
|
||||
|
||||
function virtualize () {
|
||||
if (!container || !layout.length) return
|
||||
const { top, bottom } = getVisibleRange()
|
||||
|
||||
// Tiles
|
||||
const neededTiles = new Set()
|
||||
for (const l of layout) {
|
||||
if (!l) continue
|
||||
if (l.top + l.height < top) continue
|
||||
if (l.top > bottom) break
|
||||
neededTiles.add(l.index)
|
||||
}
|
||||
for (const [index, el] of renderedTiles) {
|
||||
if (!neededTiles.has(index)) {
|
||||
el.remove()
|
||||
renderedTiles.delete(index)
|
||||
}
|
||||
}
|
||||
for (const index of neededTiles) {
|
||||
if (renderedTiles.has(index)) continue
|
||||
const tile = createTile(index)
|
||||
container.appendChild(tile)
|
||||
renderedTiles.set(index, tile)
|
||||
}
|
||||
|
||||
// Group headers (when grouping is enabled; headers is empty otherwise)
|
||||
const neededHeaders = new Set()
|
||||
for (const h of headers) {
|
||||
if (h.top + h.height < top) continue
|
||||
if (h.top > bottom) break
|
||||
neededHeaders.add(h.label)
|
||||
}
|
||||
for (const [label, el] of renderedHeaders) {
|
||||
if (!neededHeaders.has(label)) {
|
||||
el.remove()
|
||||
renderedHeaders.delete(label)
|
||||
}
|
||||
}
|
||||
for (const label of neededHeaders) {
|
||||
if (renderedHeaders.has(label)) continue
|
||||
const h = headers.find(x => x.label === label)
|
||||
if (!h) continue
|
||||
const el = createHeader(h)
|
||||
container.appendChild(el)
|
||||
renderedHeaders.set(label, el)
|
||||
}
|
||||
}
|
||||
|
||||
function computeLayoutAndRender () {
|
||||
if (!container) return
|
||||
const containerW = container.clientWidth
|
||||
if (containerW <= 0) return
|
||||
if (containerW === lastContainerW) {
|
||||
virtualize()
|
||||
return
|
||||
}
|
||||
lastContainerW = containerW
|
||||
|
||||
const result = computeLayout(containerW)
|
||||
layout = result.layout
|
||||
headers = result.headers
|
||||
container.style.height = result.totalHeight + 'px'
|
||||
|
||||
for (const [, el] of renderedTiles) el.remove()
|
||||
renderedTiles.clear()
|
||||
for (const [, el] of renderedHeaders) el.remove()
|
||||
renderedHeaders.clear()
|
||||
|
||||
virtualize()
|
||||
loadVisibleTiles()
|
||||
}
|
||||
|
||||
// ----- image src lifecycle --------------------------------------------------
|
||||
|
||||
function loadVisibleTiles () {
|
||||
if (!container) return
|
||||
const vpHeight = window.innerHeight
|
||||
const containerTop = container.getBoundingClientRect().top
|
||||
for (const a of renderedTiles.values()) {
|
||||
const img = a.firstElementChild
|
||||
if (!(img instanceof HTMLImageElement)) continue
|
||||
const aTopInVp = containerTop + parseFloat(a.style.top || '0')
|
||||
const aHeight = parseFloat(a.style.height || '0')
|
||||
const isFar = aTopInVp + aHeight < -IMAGE_LOAD_MARGIN_PX ||
|
||||
aTopInVp > vpHeight + IMAGE_LOAD_MARGIN_PX
|
||||
if (isFar) {
|
||||
if (img.src && !img.complete) {
|
||||
img.dataset.src = img.src
|
||||
img.removeAttribute('src')
|
||||
}
|
||||
} else if (img.dataset.src) {
|
||||
img.src = img.dataset.src
|
||||
img.removeAttribute('data-src')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ----- scroll handling ------------------------------------------------------
|
||||
|
||||
let scrollFrame = null
|
||||
let loadTimer = null
|
||||
|
||||
function onScroll () {
|
||||
if (scrollFrame == null) {
|
||||
scrollFrame = requestAnimationFrame(() => {
|
||||
scrollFrame = null
|
||||
virtualize()
|
||||
})
|
||||
}
|
||||
if (loadTimer) clearTimeout(loadTimer)
|
||||
loadTimer = setTimeout(() => {
|
||||
loadTimer = null
|
||||
loadVisibleTiles()
|
||||
}, SCROLL_SETTLE_MS)
|
||||
}
|
||||
|
||||
// ----- PhotoSwipe -----------------------------------------------------------
|
||||
|
||||
function parseVideoData (item) {
|
||||
try {
|
||||
const data = JSON.parse(item.videoData || '{}')
|
||||
const source = (data.source && data.source[0]) || {}
|
||||
return { src: source.src || '', type: source.type || 'video/mp4' }
|
||||
} catch (e) {
|
||||
return { src: '', type: 'video/mp4' }
|
||||
}
|
||||
}
|
||||
|
||||
function escapeAttr (s) {
|
||||
return String(s).replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<').replace(/>/g, '>')
|
||||
}
|
||||
|
||||
function buildDataSource () {
|
||||
return items.map(item => {
|
||||
if (item.type === 'VIDEO') {
|
||||
const v = parseVideoData(item)
|
||||
return {
|
||||
html:
|
||||
'<div class="pswp__video-wrap">' +
|
||||
'<video controls playsinline poster="' + escapeAttr(item.thumbnailUrl) + '">' +
|
||||
'<source src="' + escapeAttr(v.src) + '" type="' + escapeAttr(v.type) + '">' +
|
||||
'</video>' +
|
||||
'</div>'
|
||||
}
|
||||
}
|
||||
return {
|
||||
src: item.previewUrl,
|
||||
width: item.width || 1600,
|
||||
height: item.height || 1200,
|
||||
msrc: item.thumbnailUrl,
|
||||
alt: item.description || ''
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function initLightbox () {
|
||||
const { options = {} } = lightboxConfig
|
||||
|
||||
lightbox = new PhotoSwipeLightbox({
|
||||
bgOpacity: 1,
|
||||
showHideAnimationType: 'fade',
|
||||
closeOnVerticalDrag: true,
|
||||
arrowKeys: true,
|
||||
loop: false,
|
||||
padding: { top: 56, bottom: 56, left: 16, right: 16 },
|
||||
...options,
|
||||
dataSource: buildDataSource(),
|
||||
pswpModule: () => import('/share/static/photoswipe/photoswipe.esm.js')
|
||||
})
|
||||
|
||||
// Download button (only registered if config enables it)
|
||||
if (lightboxConfig.showDownload) {
|
||||
lightbox.on('uiRegister', () => {
|
||||
lightbox.pswp.ui.registerElement({
|
||||
name: 'download-button',
|
||||
order: 8,
|
||||
isButton: true,
|
||||
tagName: 'a',
|
||||
ariaLabel: 'Download',
|
||||
html: ICON_DOWNLOAD,
|
||||
onInit: (el, pswp) => {
|
||||
el.setAttribute('target', '_blank')
|
||||
el.setAttribute('rel', 'noopener')
|
||||
const update = () => {
|
||||
const item = items[pswp.currIndex]
|
||||
if (item && item.downloadUrl) {
|
||||
el.href = item.downloadUrl
|
||||
el.setAttribute('download', item.downloadFilename || '')
|
||||
} else {
|
||||
el.removeAttribute('href')
|
||||
}
|
||||
}
|
||||
update()
|
||||
pswp.on('change', update)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// Fullscreen toggle. Skipped on browsers without Fullscreen API support
|
||||
// for arbitrary elements (notably iOS Safari on iPhone).
|
||||
if (document.fullscreenEnabled) {
|
||||
lightbox.on('uiRegister', () => {
|
||||
lightbox.pswp.ui.registerElement({
|
||||
name: 'fullscreen-button',
|
||||
order: 9,
|
||||
isButton: true,
|
||||
html: ICON_FULLSCREEN,
|
||||
onInit: (el, pswp) => {
|
||||
const update = () => {
|
||||
const active = document.fullscreenElement === pswp.element
|
||||
el.innerHTML = active ? ICON_FULLSCREEN_EXIT : ICON_FULLSCREEN
|
||||
el.setAttribute('aria-label', active ? 'Exit fullscreen' : 'Fullscreen')
|
||||
el.setAttribute('title', active ? 'Exit fullscreen' : 'Fullscreen')
|
||||
}
|
||||
update()
|
||||
el.addEventListener('click', () => {
|
||||
if (document.fullscreenElement) {
|
||||
document.exitFullscreen().catch(() => {})
|
||||
} else {
|
||||
pswp.element.requestFullscreen().catch(() => {})
|
||||
}
|
||||
})
|
||||
document.addEventListener('fullscreenchange', update)
|
||||
pswp.on('destroy', () => {
|
||||
document.removeEventListener('fullscreenchange', update)
|
||||
if (document.fullscreenElement === pswp.element) {
|
||||
document.exitFullscreen().catch(() => {})
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// Caption from EXIF description (only present when item.description is set;
|
||||
// server-side gated on ipp.showMetadata.description). Content is already
|
||||
// HTML-escaped in render.ts, so innerHTML assignment is safe.
|
||||
lightbox.on('uiRegister', () => {
|
||||
lightbox.pswp.ui.registerElement({
|
||||
name: 'caption',
|
||||
order: 9,
|
||||
isButton: false,
|
||||
appendTo: 'root',
|
||||
onInit: (el, pswp) => {
|
||||
el.classList.add('pswp__caption')
|
||||
const render = () => {
|
||||
const item = items[pswp.currIndex]
|
||||
const text = (item && item.description) || ''
|
||||
el.innerHTML = text
|
||||
el.hidden = !text
|
||||
}
|
||||
render()
|
||||
pswp.on('change', render)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
// Hash navigation + back-button handling: push a history entry on open so
|
||||
// the mobile back gesture closes the lightbox; sync the hash with the
|
||||
// current slide as the user pages through.
|
||||
lightbox.on('uiRegister', () => {
|
||||
const pswp = lightbox.pswp
|
||||
const item = items[pswp.currIndex]
|
||||
if (item) {
|
||||
history.pushState({ pswp: true }, '', '#' + item.id)
|
||||
lightboxPushedHistory = true
|
||||
}
|
||||
pswp.on('change', () => {
|
||||
const it = items[pswp.currIndex]
|
||||
if (it) history.replaceState({ pswp: lightboxPushedHistory }, '', '#' + it.id)
|
||||
})
|
||||
pswp.on('close', () => {
|
||||
scrollToCurrentSlide(pswp.currIndex)
|
||||
const wasFromHistory = closingFromHistory
|
||||
closingFromHistory = false
|
||||
if (wasFromHistory) {
|
||||
// popstate already moved us back; nothing more to do
|
||||
lightboxPushedHistory = false
|
||||
} else if (lightboxPushedHistory) {
|
||||
// UI close (button / Esc / swipe-down): consume our pushed entry
|
||||
closingFromHistory = true
|
||||
lightboxPushedHistory = false
|
||||
history.back()
|
||||
} else {
|
||||
history.replaceState(null, '', window.location.pathname + window.location.search)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
window.addEventListener('popstate', () => {
|
||||
if (closingFromHistory) {
|
||||
// Our own history.back() during a UI-driven close
|
||||
closingFromHistory = false
|
||||
return
|
||||
}
|
||||
if (lightbox && lightbox.pswp && lightboxPushedHistory) {
|
||||
closingFromHistory = true
|
||||
lightbox.pswp.close()
|
||||
}
|
||||
})
|
||||
|
||||
// Optional control hiding (defaults match Immich's behavior)
|
||||
const docEl = document.documentElement
|
||||
if (!lightboxConfig.showArrows) docEl.classList.add('pswp-no-arrows')
|
||||
if (!lightboxConfig.mobileArrows) docEl.classList.add('pswp-no-mobile-arrows')
|
||||
|
||||
lightbox.init()
|
||||
}
|
||||
|
||||
function openLightbox (index) {
|
||||
if (lightbox) lightbox.loadAndOpen(index)
|
||||
}
|
||||
|
||||
/**
|
||||
* Scroll the page so the tile for the given item is comfortably in view.
|
||||
* Called from the lightbox close handler - if the user navigated prev/next
|
||||
* inside the lightbox, or arrived via a #asset-id deep link, the tile they
|
||||
* end on may be far from the original scroll position. We only scroll when
|
||||
* the tile is genuinely off-screen, so closing on a still-visible tile
|
||||
* doesn't jiggle the page.
|
||||
*/
|
||||
function scrollToCurrentSlide (index) {
|
||||
if (!container || index == null || !layout[index]) return
|
||||
const entry = layout[index]
|
||||
const containerTop = container.getBoundingClientRect().top + window.scrollY
|
||||
const tileTop = containerTop + entry.top
|
||||
const tileBottom = tileTop + entry.height
|
||||
const viewportTop = window.scrollY
|
||||
const viewportBottom = viewportTop + window.innerHeight
|
||||
// Already mostly visible - leave the scroll alone
|
||||
if (tileTop >= viewportTop && tileBottom <= viewportBottom) return
|
||||
// Center the tile vertically in the viewport
|
||||
const targetScroll = tileTop - (window.innerHeight - entry.height) / 2
|
||||
window.scrollTo({ top: Math.max(0, targetScroll), behavior: 'instant' })
|
||||
}
|
||||
|
||||
// ----- entry point ----------------------------------------------------------
|
||||
|
||||
function readInitParams () {
|
||||
const el = document.getElementById('ipp-init')
|
||||
if (!el) return {}
|
||||
try { return JSON.parse(el.textContent || '{}') } catch (e) { return {} }
|
||||
}
|
||||
|
||||
function init () {
|
||||
const params = readInitParams()
|
||||
items = params.items || []
|
||||
lightboxConfig = params.lightboxConfig || {}
|
||||
groupByDate = !!params.groupByDate
|
||||
container = document.getElementById('gallery')
|
||||
if (!container) return
|
||||
|
||||
setupToolbar()
|
||||
initLightbox()
|
||||
|
||||
let resizeFrame
|
||||
const resizeObserver = new ResizeObserver(() => {
|
||||
if (resizeFrame) cancelAnimationFrame(resizeFrame)
|
||||
resizeFrame = requestAnimationFrame(computeLayoutAndRender)
|
||||
})
|
||||
resizeObserver.observe(container)
|
||||
|
||||
window.addEventListener('scroll', onScroll, { passive: true })
|
||||
|
||||
// Deep-link: prefer #asset-id in the URL hash, fall back to ?openItem
|
||||
const hash = window.location.hash.slice(1)
|
||||
if (hash) {
|
||||
const idx = items.findIndex(it => it.id === hash)
|
||||
if (idx >= 0) openLightbox(idx)
|
||||
} else if (params.openItem && params.openItem > 0 && params.openItem <= items.length) {
|
||||
openLightbox(params.openItem - 1)
|
||||
}
|
||||
}
|
||||
|
||||
init()
|
||||
@@ -0,0 +1,53 @@
|
||||
// Gallery client entry point. Reads the JSON init block from the page,
|
||||
// populates shared state, sets up the toolbar + lightbox, attaches the
|
||||
// resize / scroll observers, and handles deep-link opening.
|
||||
//
|
||||
// Layout is pre-computed for all items based on container width. Only tiles
|
||||
// within viewport ± 1 viewport-height buffer exist in the DOM at any moment.
|
||||
// PhotoSwipe runs with a full dataSource array so the lightbox navigates
|
||||
// across all items regardless of which tiles are currently rendered.
|
||||
|
||||
import type { InitParams } from '../shared/types.js'
|
||||
import { state } from './state.js'
|
||||
import { setupToolbar } from './selection.js'
|
||||
import { initLightbox, openLightbox } from './lightbox.js'
|
||||
import { computeLayoutAndRender, onScroll } from './virtualization.js'
|
||||
|
||||
function readInitParams (): InitParams {
|
||||
const el = document.getElementById('ipp-init')
|
||||
if (!el) return {}
|
||||
try { return JSON.parse(el.textContent || '{}') } catch (e) { return {} }
|
||||
}
|
||||
|
||||
function init () {
|
||||
const params = readInitParams()
|
||||
state.items = params.items || []
|
||||
state.lightboxConfig = params.lightboxConfig || {}
|
||||
if (params.metadataConfig) state.metadataConfig = params.metadataConfig
|
||||
state.groupByDate = !!params.groupByDate
|
||||
state.container = document.getElementById('gallery')
|
||||
if (!state.container) return
|
||||
|
||||
setupToolbar()
|
||||
initLightbox()
|
||||
|
||||
let resizeFrame: number | undefined
|
||||
const resizeObserver = new ResizeObserver(() => {
|
||||
if (resizeFrame) cancelAnimationFrame(resizeFrame)
|
||||
resizeFrame = requestAnimationFrame(computeLayoutAndRender)
|
||||
})
|
||||
resizeObserver.observe(state.container)
|
||||
|
||||
window.addEventListener('scroll', onScroll, { passive: true })
|
||||
|
||||
// Deep-link: prefer #asset-id in the URL hash, fall back to ?openItem
|
||||
const hash = window.location.hash.slice(1)
|
||||
if (hash) {
|
||||
const idx = state.items.findIndex(it => it.id === hash)
|
||||
if (idx >= 0) openLightbox(idx)
|
||||
} else if (params.openItem && params.openItem > 0 && params.openItem <= state.items.length) {
|
||||
openLightbox(params.openItem - 1)
|
||||
}
|
||||
}
|
||||
|
||||
init()
|
||||
@@ -0,0 +1,172 @@
|
||||
// Justified-rows + square-grid layout, with optional month grouping. Pure
|
||||
// geometry: takes a container width, returns positions for every tile and
|
||||
// every header. Called by virtualization on first render and on resize.
|
||||
|
||||
import {
|
||||
state,
|
||||
TARGET_ROW_HEIGHT,
|
||||
GAP,
|
||||
MOBILE_BREAKPOINT,
|
||||
MOBILE_COLS,
|
||||
HEADER_HEIGHT,
|
||||
GROUP_GAP,
|
||||
type LayoutEntry,
|
||||
type HeaderEntry,
|
||||
type GroupSpec
|
||||
} from './state.js'
|
||||
|
||||
export interface LayoutResult {
|
||||
layout: LayoutEntry[]
|
||||
headers: HeaderEntry[]
|
||||
totalHeight: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute tile positions, group-header positions, and total scroll height
|
||||
* for the gallery at the given container width.
|
||||
*
|
||||
* Reads `state.items` and `state.groupByDate`. Output is pure data - the
|
||||
* caller (virtualization) is responsible for actually placing DOM nodes
|
||||
* according to the returned positions.
|
||||
*
|
||||
* Switches between a mobile square grid (under MOBILE_BREAKPOINT) and the
|
||||
* justified-rows algorithm. When grouping by date is enabled, items are
|
||||
* bucketed by YYYY-MM and a header is reserved before each group.
|
||||
*/
|
||||
export function computeLayout (containerW: number): LayoutResult {
|
||||
const tileLayout: LayoutEntry[] = new Array(state.items.length)
|
||||
const newHeaders: HeaderEntry[] = []
|
||||
const groups: GroupSpec[] = state.groupByDate
|
||||
? groupItemsByMonth()
|
||||
: [{ label: null, indices: itemIndices() }]
|
||||
const isMobile = containerW < MOBILE_BREAKPOINT
|
||||
let y = 0
|
||||
for (let g = 0; g < groups.length; g++) {
|
||||
const group = groups[g]
|
||||
if (group.label) {
|
||||
newHeaders.push({ label: group.label, top: y, height: HEADER_HEIGHT })
|
||||
y += HEADER_HEIGHT
|
||||
}
|
||||
y = isMobile
|
||||
? layoutSquareGroup(containerW, group.indices, y, tileLayout)
|
||||
: layoutJustifiedGroup(containerW, group.indices, y, tileLayout)
|
||||
if (g < groups.length - 1) y += GROUP_GAP
|
||||
}
|
||||
return {
|
||||
layout: tileLayout,
|
||||
headers: newHeaders,
|
||||
totalHeight: Math.max(0, y)
|
||||
}
|
||||
}
|
||||
|
||||
function itemIndices (): number[] {
|
||||
const out = new Array(state.items.length)
|
||||
for (let i = 0; i < state.items.length; i++) out[i] = i
|
||||
return out
|
||||
}
|
||||
|
||||
function groupItemsByMonth (): GroupSpec[] {
|
||||
// Preserve item order (already sorted desc by render.ts when grouping is on)
|
||||
const map = new Map<string, GroupSpec>()
|
||||
for (let i = 0; i < state.items.length; i++) {
|
||||
const key = (state.items[i].fileCreatedAt || '').slice(0, 7) || 'undated'
|
||||
let g = map.get(key)
|
||||
if (!g) {
|
||||
g = { label: monthLabel(key), indices: [] }
|
||||
map.set(key, g)
|
||||
}
|
||||
g.indices.push(i)
|
||||
}
|
||||
return Array.from(map.values())
|
||||
}
|
||||
|
||||
function monthLabel (key: string): string {
|
||||
if (key === 'undated') return 'Undated'
|
||||
const parts = key.split('-')
|
||||
const y = Number(parts[0])
|
||||
const m = Number(parts[1])
|
||||
if (!y || !m) return key
|
||||
// Intl.DateTimeFormat picks up the browser's locale; UTC timeZone keeps
|
||||
// the displayed month consistent with the UTC YYYY-MM bucket key.
|
||||
return new Intl.DateTimeFormat(undefined, {
|
||||
year: 'numeric',
|
||||
month: 'long',
|
||||
timeZone: 'UTC'
|
||||
}).format(new Date(Date.UTC(y, m - 1, 1)))
|
||||
}
|
||||
|
||||
/**
|
||||
* Lay out one group as a fixed-column square grid (mobile path).
|
||||
* Writes positions into `tileLayout` in place.
|
||||
*
|
||||
* @returns The y position past the last tile in this group (no trailing gap).
|
||||
*/
|
||||
function layoutSquareGroup (containerW: number, indices: number[], startY: number, tileLayout: LayoutEntry[]): number {
|
||||
const tileSize = Math.floor((containerW - (MOBILE_COLS - 1) * GAP) / MOBILE_COLS)
|
||||
let col = 0
|
||||
let x = 0
|
||||
let y = startY
|
||||
for (const idx of indices) {
|
||||
tileLayout[idx] = { index: idx, left: x, top: y, width: tileSize, height: tileSize }
|
||||
col++
|
||||
if (col === MOBILE_COLS) {
|
||||
col = 0
|
||||
x = 0
|
||||
y += tileSize + GAP
|
||||
} else {
|
||||
x += tileSize + GAP
|
||||
}
|
||||
}
|
||||
// If the last row was partial, advance y to past it
|
||||
if (col > 0) y += tileSize
|
||||
// Otherwise back off the trailing inter-row gap
|
||||
else if (y > startY) y -= GAP
|
||||
return y
|
||||
}
|
||||
|
||||
/**
|
||||
* Lay out one group as justified rows (desktop path): tiles in each row are
|
||||
* scaled so their combined width fills the container exactly. The final row
|
||||
* keeps the target height instead of stretching to fill, which avoids the
|
||||
* "huge last row" look when there are only one or two trailing tiles.
|
||||
*
|
||||
* @returns The y position past the last tile in this group (no trailing gap).
|
||||
*/
|
||||
function layoutJustifiedGroup (containerW: number, indices: number[], startY: number, tileLayout: LayoutEntry[]): number {
|
||||
let rowItems: Array<{ idx: number, aspect: number }> = []
|
||||
let aspectSum = 0
|
||||
let y = startY
|
||||
|
||||
const applyRow = (rowItems: Array<{ idx: number, aspect: number }>, height: number, isLastRow: boolean) => {
|
||||
const intHeight = Math.floor(height)
|
||||
let x = 0
|
||||
rowItems.forEach(({ idx, aspect }, i) => {
|
||||
const isFinalInRow = i === rowItems.length - 1
|
||||
const w = (!isLastRow && isFinalInRow)
|
||||
? containerW - x
|
||||
: Math.floor(aspect * height)
|
||||
tileLayout[idx] = { index: idx, left: x, top: y, width: w, height: intHeight }
|
||||
x += w + GAP
|
||||
})
|
||||
y += intHeight + GAP
|
||||
}
|
||||
|
||||
for (const idx of indices) {
|
||||
const item = state.items[idx]
|
||||
const w = item.width || 1
|
||||
const h = item.height || 1
|
||||
const aspect = w / h
|
||||
rowItems.push({ idx, aspect })
|
||||
aspectSum += aspect
|
||||
const projectedH = (containerW - (rowItems.length - 1) * GAP) / aspectSum
|
||||
if (projectedH <= TARGET_ROW_HEIGHT) {
|
||||
applyRow(rowItems, projectedH, false)
|
||||
rowItems = []
|
||||
aspectSum = 0
|
||||
}
|
||||
}
|
||||
if (rowItems.length) applyRow(rowItems, TARGET_ROW_HEIGHT, true)
|
||||
|
||||
// y advanced past the last row's trailing gap; back off
|
||||
return y > startY ? y - GAP : y
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
// PhotoSwipe UI element registrations: back button, caption (description),
|
||||
// download button, fullscreen toggle. Each is gated by config or feature
|
||||
// detection. The info sidebar lives in `sidebar.ts`.
|
||||
|
||||
import { state, ICON_BACK, ICON_DOWNLOAD, ICON_FULLSCREEN, ICON_FULLSCREEN_EXIT } from './state.js'
|
||||
|
||||
// PhotoSwipe types are not bundled with the project. These two interfaces
|
||||
// describe just enough of the surface we touch to keep the rest of the file
|
||||
// type-checked.
|
||||
interface PswpUiElementConfig {
|
||||
name: string
|
||||
order: number
|
||||
isButton: boolean
|
||||
tagName?: string
|
||||
ariaLabel?: string
|
||||
appendTo?: string
|
||||
html?: string
|
||||
// eslint-disable-next-line no-use-before-define
|
||||
onInit?: (el: HTMLElement, pswp: PswpInstance) => void
|
||||
}
|
||||
|
||||
interface PswpInstance {
|
||||
currIndex: number
|
||||
element: HTMLElement
|
||||
ui: {
|
||||
registerElement: (config: PswpUiElementConfig) => void
|
||||
}
|
||||
on: (event: string, cb: () => void) => void
|
||||
close: () => void
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
type LightboxInstance = any
|
||||
|
||||
/**
|
||||
* Register the top-left back button that closes the lightbox and returns
|
||||
* to the gallery grid. Matches Immich's native asset-viewer affordance
|
||||
* (back arrow, no top-right X). Order 1 puts it at the leftmost slot of
|
||||
* the toolbar. The default PhotoSwipe close button is hidden via CSS in
|
||||
* `photoswipe-overrides.css`.
|
||||
*/
|
||||
export function registerBackButton (lightbox: LightboxInstance) {
|
||||
lightbox.on('uiRegister', () => {
|
||||
lightbox.pswp.ui.registerElement({
|
||||
name: 'back-button',
|
||||
order: 1,
|
||||
isButton: true,
|
||||
ariaLabel: 'Back to gallery',
|
||||
html: ICON_BACK,
|
||||
onInit: (el: HTMLElement, pswp: PswpInstance) => {
|
||||
el.addEventListener('click', () => pswp.close())
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the description-caption UI element. Content is plain text from
|
||||
* the server; the client uses `textContent` so any HTML-significant
|
||||
* characters in the description render as literal text (not markup).
|
||||
*
|
||||
* Caller is responsible for only invoking this when
|
||||
* `metadataConfig.descriptionInCaption` is true.
|
||||
*/
|
||||
export function registerCaption (lightbox: LightboxInstance) {
|
||||
lightbox.on('uiRegister', () => {
|
||||
lightbox.pswp.ui.registerElement({
|
||||
name: 'caption',
|
||||
order: 9,
|
||||
isButton: false,
|
||||
appendTo: 'root',
|
||||
onInit: (el: HTMLElement, pswp: PswpInstance) => {
|
||||
el.classList.add('pswp__caption')
|
||||
const render = () => {
|
||||
const item = state.items[pswp.currIndex]
|
||||
const text = (item && item.description) || ''
|
||||
el.textContent = text
|
||||
el.hidden = !text
|
||||
}
|
||||
render()
|
||||
pswp.on('change', render)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the download button. Only called when the share allows downloads
|
||||
* AND the config enables the lightbox button.
|
||||
*/
|
||||
export function registerDownloadButton (lightbox: LightboxInstance) {
|
||||
lightbox.on('uiRegister', () => {
|
||||
lightbox.pswp.ui.registerElement({
|
||||
name: 'download-button',
|
||||
order: 8,
|
||||
isButton: true,
|
||||
tagName: 'a',
|
||||
ariaLabel: 'Download',
|
||||
html: ICON_DOWNLOAD,
|
||||
onInit: (el: HTMLElement, pswp: PswpInstance) => {
|
||||
const link = el as HTMLAnchorElement
|
||||
link.setAttribute('target', '_blank')
|
||||
link.setAttribute('rel', 'noopener')
|
||||
const update = () => {
|
||||
const item = state.items[pswp.currIndex]
|
||||
if (item && item.downloadUrl) {
|
||||
link.href = item.downloadUrl
|
||||
link.setAttribute('download', item.downloadFilename || '')
|
||||
} else {
|
||||
link.removeAttribute('href')
|
||||
}
|
||||
}
|
||||
update()
|
||||
pswp.on('change', update)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the fullscreen toggle. Skipped on browsers without Fullscreen API
|
||||
* support for arbitrary elements (notably iOS Safari on iPhone).
|
||||
*/
|
||||
export function registerFullscreenButton (lightbox: LightboxInstance) {
|
||||
if (!document.fullscreenEnabled) return
|
||||
lightbox.on('uiRegister', () => {
|
||||
lightbox.pswp.ui.registerElement({
|
||||
name: 'fullscreen-button',
|
||||
order: 9,
|
||||
isButton: true,
|
||||
html: ICON_FULLSCREEN,
|
||||
onInit: (el: HTMLElement, pswp: PswpInstance) => {
|
||||
const update = () => {
|
||||
const active = document.fullscreenElement === pswp.element
|
||||
el.innerHTML = active ? ICON_FULLSCREEN_EXIT : ICON_FULLSCREEN
|
||||
el.setAttribute('aria-label', active ? 'Exit fullscreen' : 'Fullscreen')
|
||||
el.setAttribute('title', active ? 'Exit fullscreen' : 'Fullscreen')
|
||||
}
|
||||
update()
|
||||
el.addEventListener('click', () => {
|
||||
if (document.fullscreenElement) {
|
||||
document.exitFullscreen().catch(() => {})
|
||||
} else {
|
||||
pswp.element.requestFullscreen().catch(() => {})
|
||||
}
|
||||
})
|
||||
document.addEventListener('fullscreenchange', update)
|
||||
pswp.on('destroy', () => {
|
||||
document.removeEventListener('fullscreenchange', update)
|
||||
if (document.fullscreenElement === pswp.element) {
|
||||
document.exitFullscreen().catch(() => {})
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
// PhotoSwipe instantiation, data-source construction, history / hash
|
||||
// navigation. Individual UI elements (caption, download, fullscreen,
|
||||
// sidebar) live in lightbox-ui.ts and sidebar.ts.
|
||||
|
||||
// Runtime URL resolved by Express static, not a TS-resolvable module path.
|
||||
// @ts-expect-error - browser-only ESM URL
|
||||
import PhotoSwipeLightbox from '/share/static/photoswipe/photoswipe-lightbox.esm.js' // eslint-disable-line import/no-absolute-path
|
||||
|
||||
import { state, SIDEBAR_WIDTH, MOBILE_BREAKPOINT } from './state.js'
|
||||
import type { GalleryItem } from '../shared/types.js'
|
||||
import {
|
||||
registerBackButton,
|
||||
registerCaption,
|
||||
registerDownloadButton,
|
||||
registerFullscreenButton
|
||||
} from './lightbox-ui.js'
|
||||
import { registerSidebar } from './sidebar.js'
|
||||
|
||||
/**
|
||||
* Replace the current history entry with the same URL minus any hash.
|
||||
* No-op when there is no hash. Used by the lightbox-close paths so the
|
||||
* browser bar shows a clean gallery URL after the lightbox dismisses,
|
||||
* even when the entry we land on came from a `#assetId` deep link.
|
||||
*/
|
||||
function clearHashIfPresent () {
|
||||
if (window.location.hash) {
|
||||
history.replaceState(null, '', window.location.pathname + window.location.search)
|
||||
}
|
||||
}
|
||||
|
||||
function parseVideoData (item: GalleryItem): { src: string, type: string } {
|
||||
try {
|
||||
const data = JSON.parse(item.videoData || '{}')
|
||||
const source = (data.source && data.source[0]) || {}
|
||||
return { src: source.src || '', type: source.type || 'video/mp4' }
|
||||
} catch (e) {
|
||||
return { src: '', type: 'video/mp4' }
|
||||
}
|
||||
}
|
||||
|
||||
function escapeAttr (s: string): string {
|
||||
return String(s).replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<').replace(/>/g, '>')
|
||||
}
|
||||
|
||||
/**
|
||||
* Translate `state.items` into PhotoSwipe's dataSource array. Images use
|
||||
* `src`/`width`/`height`; videos use the `html` slide with a `<video>`
|
||||
* element so PhotoSwipe streams from the server's `/share/video/...` URL.
|
||||
*/
|
||||
function buildDataSource () {
|
||||
return state.items.map(item => {
|
||||
if (item.type === 'VIDEO') {
|
||||
const v = parseVideoData(item)
|
||||
return {
|
||||
html:
|
||||
'<div class="pswp__video-wrap">' +
|
||||
'<video controls playsinline poster="' + escapeAttr(item.thumbnailUrl) + '">' +
|
||||
'<source src="' + escapeAttr(v.src) + '" type="' + escapeAttr(v.type) + '">' +
|
||||
'</video>' +
|
||||
'</div>'
|
||||
}
|
||||
}
|
||||
return {
|
||||
src: item.previewUrl,
|
||||
width: item.width || 1600,
|
||||
height: item.height || 1200,
|
||||
msrc: item.thumbnailUrl,
|
||||
alt: item.description || ''
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Construct the PhotoSwipe lightbox, register its UI elements, set up hash
|
||||
* navigation, and call `init()`. Reads config from `state.lightboxConfig`
|
||||
* and writes the instance back to `state.lightbox`.
|
||||
*
|
||||
* Browser history is integrated so the mobile back gesture closes the
|
||||
* lightbox, and the URL hash tracks the current slide for shareable
|
||||
* deep-links.
|
||||
*/
|
||||
export function initLightbox () {
|
||||
const { options = {} } = state.lightboxConfig
|
||||
|
||||
state.lightbox = new PhotoSwipeLightbox({
|
||||
bgOpacity: 1,
|
||||
showHideAnimationType: 'fade',
|
||||
closeOnVerticalDrag: true,
|
||||
arrowKeys: true,
|
||||
loop: false,
|
||||
// paddingFn lets the sidebar shrink the slide viewport when open. On a
|
||||
// narrow viewport the sidebar overlays instead, so we leave padding
|
||||
// alone in that case.
|
||||
paddingFn: () => ({
|
||||
top: 56,
|
||||
bottom: 56,
|
||||
left: 16,
|
||||
right: state.sidebarOpen && window.innerWidth >= MOBILE_BREAKPOINT
|
||||
? SIDEBAR_WIDTH + 16
|
||||
: 16
|
||||
}),
|
||||
...options,
|
||||
dataSource: buildDataSource(),
|
||||
// @ts-expect-error - runtime URL resolved by Express static
|
||||
pswpModule: () => import('/share/static/photoswipe/photoswipe.esm.js') // eslint-disable-line import/no-absolute-path
|
||||
})
|
||||
|
||||
registerBackButton(state.lightbox)
|
||||
if (state.lightboxConfig.showDownload) registerDownloadButton(state.lightbox)
|
||||
registerFullscreenButton(state.lightbox)
|
||||
if (state.metadataConfig.descriptionInCaption) registerCaption(state.lightbox)
|
||||
if (state.metadataConfig.sidebarHasContent) registerSidebar(state.lightbox)
|
||||
|
||||
// Hash navigation + back-button handling: push a history entry on open so
|
||||
// the mobile back gesture closes the lightbox; sync the hash with the
|
||||
// current slide as the user pages through.
|
||||
state.lightbox.on('uiRegister', () => {
|
||||
const pswp = state.lightbox.pswp
|
||||
const item = state.items[pswp.currIndex]
|
||||
if (item) {
|
||||
history.pushState({ pswp: true }, '', '#' + item.id)
|
||||
state.lightboxPushedHistory = true
|
||||
}
|
||||
pswp.on('change', () => {
|
||||
const it = state.items[pswp.currIndex]
|
||||
if (it) history.replaceState({ pswp: state.lightboxPushedHistory }, '', '#' + it.id)
|
||||
})
|
||||
pswp.on('close', () => {
|
||||
scrollToCurrentSlide(pswp.currIndex)
|
||||
const wasFromHistory = state.closingFromHistory
|
||||
state.closingFromHistory = false
|
||||
if (wasFromHistory) {
|
||||
// popstate already moved us back to the prior entry. If that entry
|
||||
// still has a hash (e.g. the user arrived via a #assetId deep link
|
||||
// and we pushed on top of it), strip it now.
|
||||
state.lightboxPushedHistory = false
|
||||
clearHashIfPresent()
|
||||
} else if (state.lightboxPushedHistory) {
|
||||
// UI close (button / Esc / swipe-down): consume our pushed entry.
|
||||
// The popstate handler below clears any leftover hash on the entry
|
||||
// we land on.
|
||||
state.closingFromHistory = true
|
||||
state.lightboxPushedHistory = false
|
||||
history.back()
|
||||
} else {
|
||||
history.replaceState(null, '', window.location.pathname + window.location.search)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
window.addEventListener('popstate', () => {
|
||||
if (state.closingFromHistory) {
|
||||
// Our own history.back() during a UI-driven close. The current entry
|
||||
// (which we just navigated to) may still carry a hash from a deep
|
||||
// link; strip it for a clean exit URL.
|
||||
state.closingFromHistory = false
|
||||
clearHashIfPresent()
|
||||
return
|
||||
}
|
||||
if (state.lightbox && state.lightbox.pswp && state.lightboxPushedHistory) {
|
||||
state.closingFromHistory = true
|
||||
state.lightbox.pswp.close()
|
||||
}
|
||||
})
|
||||
|
||||
// Optional control hiding (defaults match Immich's behavior)
|
||||
const docEl = document.documentElement
|
||||
if (!state.lightboxConfig.showArrows) docEl.classList.add('pswp-no-arrows')
|
||||
if (!state.lightboxConfig.mobileArrows) docEl.classList.add('pswp-no-mobile-arrows')
|
||||
|
||||
state.lightbox.init()
|
||||
}
|
||||
|
||||
/**
|
||||
* Open the lightbox to the item at `index` (0-based into `state.items`).
|
||||
* No-op if the lightbox hasn't been initialised yet.
|
||||
*/
|
||||
export function openLightbox (index: number) {
|
||||
if (state.lightbox) state.lightbox.loadAndOpen(index)
|
||||
}
|
||||
|
||||
/**
|
||||
* Scroll the page so the tile for the given item is comfortably in view.
|
||||
* Called from the lightbox close handler - if the user navigated prev/next
|
||||
* inside the lightbox, or arrived via a #asset-id deep link, the tile they
|
||||
* end on may be far from the original scroll position. We only scroll when
|
||||
* the tile is genuinely off-screen, so closing on a still-visible tile
|
||||
* doesn't jiggle the page.
|
||||
*/
|
||||
function scrollToCurrentSlide (index: number) {
|
||||
if (!state.container || index == null || !state.layout[index]) return
|
||||
const entry = state.layout[index]
|
||||
const containerTop = state.container.getBoundingClientRect().top + window.scrollY
|
||||
const tileTop = containerTop + entry.top
|
||||
const tileBottom = tileTop + entry.height
|
||||
const viewportTop = window.scrollY
|
||||
const viewportBottom = viewportTop + window.innerHeight
|
||||
// Already mostly visible - leave the scroll alone
|
||||
if (tileTop >= viewportTop && tileBottom <= viewportBottom) return
|
||||
// Center the tile vertically in the viewport
|
||||
const targetScroll = tileTop - (window.innerHeight - entry.height) / 2
|
||||
window.scrollTo({ top: Math.max(0, targetScroll), behavior: 'instant' })
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
// Selection mode (long-press to enter, checkmarks on tiles, toolbar at the
|
||||
// bottom). Selected IDs are POSTed to /share/:key/download for a server-side
|
||||
// zip, or downloaded directly for a single selection.
|
||||
|
||||
import { state } from './state.js'
|
||||
|
||||
/**
|
||||
* Activate selection mode. Tiles show their checkmark control, the bottom
|
||||
* toolbar reveals itself, and tap on a tile toggles selection instead of
|
||||
* opening the lightbox. No-op if already active.
|
||||
*/
|
||||
export function enterSelectMode () {
|
||||
if (state.selectMode) return
|
||||
state.selectMode = true
|
||||
if (state.container) state.container.classList.add('select-mode')
|
||||
if (state.toolbarEl) state.toolbarEl.hidden = false
|
||||
}
|
||||
|
||||
/**
|
||||
* Leave selection mode and clear the selection. Removes the visual marker
|
||||
* from every tile currently in the DOM. No-op if not in select mode.
|
||||
*/
|
||||
export function exitSelectMode () {
|
||||
if (!state.selectMode) return
|
||||
state.selectMode = false
|
||||
// Clear DOM markers on the tiles currently in the DOM
|
||||
for (const a of state.renderedTiles.values()) a.classList.remove('selected')
|
||||
state.selected.clear()
|
||||
if (state.container) state.container.classList.remove('select-mode')
|
||||
if (state.toolbarEl) state.toolbarEl.hidden = true
|
||||
updateSelectionUI()
|
||||
}
|
||||
|
||||
/**
|
||||
* Add or remove an item from the selection set. Updates the matching tile's
|
||||
* visual marker if that tile is currently rendered, and exits selection
|
||||
* mode automatically when the last item is deselected.
|
||||
*/
|
||||
export function toggleSelection (id: string) {
|
||||
if (state.selected.has(id)) state.selected.delete(id)
|
||||
else state.selected.add(id)
|
||||
const idx = state.items.findIndex(it => it.id === id)
|
||||
const tile = idx >= 0 ? state.renderedTiles.get(idx) : null
|
||||
if (tile) tile.classList.toggle('selected', state.selected.has(id))
|
||||
// Auto-exit if user deselected the last item
|
||||
if (state.selected.size === 0 && state.selectMode) exitSelectMode()
|
||||
else updateSelectionUI()
|
||||
}
|
||||
|
||||
function updateSelectionUI () {
|
||||
if (state.countEl) {
|
||||
state.countEl.textContent = state.selected.size + ' selected'
|
||||
}
|
||||
if (state.downloadBtn) state.downloadBtn.disabled = state.selected.size === 0
|
||||
if (state.selectAllBtn) {
|
||||
state.selectAllBtn.textContent =
|
||||
state.selected.size === state.items.length ? 'Deselect all' : 'Select all'
|
||||
}
|
||||
}
|
||||
|
||||
function selectAllOrNone () {
|
||||
if (state.selected.size === state.items.length) {
|
||||
// Deselect all but keep select mode active
|
||||
for (const a of state.renderedTiles.values()) a.classList.remove('selected')
|
||||
state.selected.clear()
|
||||
updateSelectionUI()
|
||||
} else {
|
||||
if (!state.selectMode) enterSelectMode()
|
||||
for (const item of state.items) state.selected.add(item.id)
|
||||
for (const a of state.renderedTiles.values()) a.classList.add('selected')
|
||||
updateSelectionUI()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send the current selection to the download endpoint. A single selection
|
||||
* downloads the asset directly (no one-entry zip); two or more selections
|
||||
* POST to /share/:key/download and the server streams a zip back.
|
||||
*/
|
||||
function downloadSelected () {
|
||||
if (state.selected.size === 0) return
|
||||
// Single selection: download the file directly so the user gets the image
|
||||
// (or video) instead of a one-entry zip.
|
||||
if (state.selected.size === 1) {
|
||||
const id = state.selected.values().next().value
|
||||
const item = state.items.find(it => it.id === id)
|
||||
if (item && item.downloadUrl) {
|
||||
const a = document.createElement('a')
|
||||
a.href = item.downloadUrl
|
||||
a.download = item.downloadFilename || ''
|
||||
document.body.appendChild(a)
|
||||
a.click()
|
||||
a.remove()
|
||||
return
|
||||
}
|
||||
}
|
||||
// Form POST so the browser handles streaming the zip directly to disk.
|
||||
const form = document.createElement('form')
|
||||
form.method = 'POST'
|
||||
form.action = window.location.pathname + '/download'
|
||||
const input = document.createElement('input')
|
||||
input.type = 'hidden'
|
||||
input.name = 'assets'
|
||||
input.value = JSON.stringify(Array.from(state.selected))
|
||||
form.appendChild(input)
|
||||
document.body.appendChild(form)
|
||||
form.submit()
|
||||
form.remove()
|
||||
}
|
||||
|
||||
/**
|
||||
* Look up the selection toolbar in the DOM and wire its buttons (cancel,
|
||||
* select-all, download). Called once at init time. If the toolbar element
|
||||
* isn't on the page (the share doesn't allow downloads), this short-circuits
|
||||
* and selection-related code paths never activate.
|
||||
*/
|
||||
export function setupToolbar () {
|
||||
state.toolbarEl = document.getElementById('select-toolbar')
|
||||
// No toolbar means downloads aren't allowed for this share; nothing to wire
|
||||
if (!state.toolbarEl) return
|
||||
state.countEl = document.getElementById('select-count')
|
||||
state.selectAllBtn = document.getElementById('select-all') as HTMLButtonElement | null
|
||||
state.cancelBtn = document.getElementById('select-cancel') as HTMLButtonElement | null
|
||||
state.downloadBtn = document.getElementById('select-download') as HTMLButtonElement | null
|
||||
if (state.cancelBtn) state.cancelBtn.addEventListener('click', exitSelectMode)
|
||||
if (state.selectAllBtn) state.selectAllBtn.addEventListener('click', selectAllOrNone)
|
||||
if (state.downloadBtn) state.downloadBtn.addEventListener('click', downloadSelected)
|
||||
updateSelectionUI()
|
||||
}
|
||||
@@ -0,0 +1,372 @@
|
||||
// Info sidebar that surfaces description + EXIF + location metadata for the
|
||||
// current lightbox slide. Modelled on Immich's native DetailPanel:
|
||||
// docked to the right (image shrinks to fit), slide-in transition, close
|
||||
// button top-left, sections only render when their data is present. Toggled
|
||||
// by the toolbar info button or the `i` key, persisted via localStorage.
|
||||
|
||||
import { state, ICON_INFO, ICON_CLOSE, ICON_IMAGE, ICON_CAMERA, ICON_IRIS, ICON_MAP, SIDEBAR_STORAGE_KEY } from './state.js'
|
||||
import type { GalleryItem, GalleryExif } from '../shared/types.js'
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
type LightboxInstance = any
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
type PswpInstance = any
|
||||
|
||||
interface PswpUiElementConfig {
|
||||
name: string
|
||||
order: number
|
||||
isButton: boolean
|
||||
tagName?: string
|
||||
ariaLabel?: string
|
||||
appendTo?: string
|
||||
html?: string
|
||||
onInit?: (el: HTMLElement, pswp: PswpInstance) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the sidebar panel + toolbar toggle button + `i` keybinding.
|
||||
* Called once from initLightbox after the lightbox is constructed.
|
||||
*/
|
||||
export function registerSidebar (lightbox: LightboxInstance) {
|
||||
lightbox.on('uiRegister', () => {
|
||||
lightbox.pswp.ui.registerElement({
|
||||
name: 'sidebar',
|
||||
order: 100,
|
||||
isButton: false,
|
||||
appendTo: 'root',
|
||||
onInit: (el: HTMLElement, pswp: PswpInstance) => {
|
||||
el.classList.add('ipp-sidebar')
|
||||
el.setAttribute('aria-label', 'Photo information')
|
||||
const renderSidebar = () => renderContents(el, state.items[pswp.currIndex])
|
||||
renderSidebar()
|
||||
pswp.on('change', renderSidebar)
|
||||
pswp.on('destroy', () => {
|
||||
document.documentElement.classList.remove('ipp-sidebar-open')
|
||||
})
|
||||
applyOpenState(pswp)
|
||||
}
|
||||
} as PswpUiElementConfig)
|
||||
|
||||
lightbox.pswp.ui.registerElement({
|
||||
name: 'sidebar-toggle',
|
||||
order: 7,
|
||||
isButton: true,
|
||||
ariaLabel: 'Info',
|
||||
html: ICON_INFO,
|
||||
onInit: (el: HTMLElement, pswp: PswpInstance) => {
|
||||
el.addEventListener('click', () => toggleSidebar(pswp))
|
||||
}
|
||||
} as PswpUiElementConfig)
|
||||
|
||||
// Restore persisted state on open
|
||||
state.sidebarOpen = readPersistedState()
|
||||
applyOpenState(lightbox.pswp)
|
||||
})
|
||||
|
||||
// `i` toggles the sidebar while the lightbox is open. Escape closes the
|
||||
// sidebar first on press; PhotoSwipe handles a second Escape to close
|
||||
// the lightbox. We attach to window because PhotoSwipe doesn't expose a
|
||||
// keypress hook for arbitrary keys.
|
||||
window.addEventListener('keydown', (e) => {
|
||||
if (!state.lightbox || !state.lightbox.pswp) return
|
||||
if (e.key === 'i' || e.key === 'I') {
|
||||
// Don't steal `i` from text inputs (none exist in the lightbox today,
|
||||
// but better safe).
|
||||
const target = e.target as HTMLElement | null
|
||||
if (target && (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA')) return
|
||||
e.preventDefault()
|
||||
toggleSidebar(state.lightbox.pswp)
|
||||
} else if (e.key === 'Escape' && state.sidebarOpen) {
|
||||
// Close the sidebar but let PhotoSwipe still see the Escape on the
|
||||
// next press (we don't stopPropagation here).
|
||||
setSidebarOpen(state.lightbox.pswp, false)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function toggleSidebar (pswp: PswpInstance) {
|
||||
setSidebarOpen(pswp, !state.sidebarOpen)
|
||||
}
|
||||
|
||||
function setSidebarOpen (pswp: PswpInstance, open: boolean) {
|
||||
if (state.sidebarOpen === open) return
|
||||
state.sidebarOpen = open
|
||||
writePersistedState(open)
|
||||
applyOpenState(pswp)
|
||||
}
|
||||
|
||||
function applyOpenState (pswp: PswpInstance) {
|
||||
const root = document.documentElement
|
||||
if (state.sidebarOpen) root.classList.add('ipp-sidebar-open')
|
||||
else root.classList.remove('ipp-sidebar-open')
|
||||
// Recalculate slide size so the image fits in the new container width.
|
||||
if (pswp && typeof pswp.updateSize === 'function') {
|
||||
pswp.updateSize(true)
|
||||
}
|
||||
}
|
||||
|
||||
function readPersistedState (): boolean {
|
||||
try {
|
||||
return localStorage.getItem(SIDEBAR_STORAGE_KEY) === '1'
|
||||
} catch (e) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
function writePersistedState (open: boolean) {
|
||||
try {
|
||||
localStorage.setItem(SIDEBAR_STORAGE_KEY, open ? '1' : '0')
|
||||
} catch (e) {
|
||||
// Quota exceeded / private mode - ignore, state stays in memory only.
|
||||
}
|
||||
}
|
||||
|
||||
// ----- content rendering ---------------------------------------------------
|
||||
|
||||
function renderContents (root: HTMLElement, item: GalleryItem | undefined) {
|
||||
root.replaceChildren()
|
||||
if (!item) return
|
||||
|
||||
root.appendChild(renderHeader())
|
||||
|
||||
const showDescription = state.metadataConfig.descriptionInSidebar && !!item.description
|
||||
if (showDescription && item.description) {
|
||||
root.appendChild(renderSection('description', renderDescription(item.description)))
|
||||
}
|
||||
|
||||
const exif = item.exif
|
||||
if (exif && hasAnyExifField(exif)) {
|
||||
root.appendChild(renderSection('details', ...renderDetailRows(exif)))
|
||||
}
|
||||
|
||||
if (exif && hasAnyLocationField(exif)) {
|
||||
root.appendChild(renderSection('location', renderLocation(exif)))
|
||||
}
|
||||
|
||||
const noExifShown = !exif || (!hasAnyExifField(exif) && !hasAnyLocationField(exif))
|
||||
if (!showDescription && noExifShown) {
|
||||
const empty = document.createElement('p')
|
||||
empty.className = 'ipp-sidebar-empty'
|
||||
empty.textContent = 'No metadata available'
|
||||
root.appendChild(empty)
|
||||
}
|
||||
}
|
||||
|
||||
function renderHeader (): HTMLElement {
|
||||
const header = document.createElement('header')
|
||||
header.className = 'ipp-sidebar-header'
|
||||
const close = document.createElement('button')
|
||||
close.type = 'button'
|
||||
close.className = 'ipp-sidebar-close'
|
||||
close.setAttribute('aria-label', 'Close info')
|
||||
close.innerHTML = ICON_CLOSE
|
||||
close.addEventListener('click', () => {
|
||||
if (state.lightbox && state.lightbox.pswp) setSidebarOpen(state.lightbox.pswp, false)
|
||||
})
|
||||
header.appendChild(close)
|
||||
const title = document.createElement('span')
|
||||
title.className = 'ipp-sidebar-title'
|
||||
title.textContent = 'Info'
|
||||
header.appendChild(title)
|
||||
return header
|
||||
}
|
||||
|
||||
function renderSection (className: string, ...children: HTMLElement[]): HTMLElement {
|
||||
const section = document.createElement('section')
|
||||
section.className = 'ipp-sidebar-section ipp-sidebar-' + className
|
||||
for (const child of children) section.appendChild(child)
|
||||
return section
|
||||
}
|
||||
|
||||
function renderDescription (description: string): HTMLElement {
|
||||
const el = document.createElement('p')
|
||||
el.className = 'ipp-sidebar-description'
|
||||
el.textContent = description
|
||||
return el
|
||||
}
|
||||
|
||||
function renderDetailRows (exif: GalleryExif): HTMLElement[] {
|
||||
const heading = document.createElement('h3')
|
||||
heading.className = 'ipp-sidebar-heading'
|
||||
heading.textContent = 'Details'
|
||||
|
||||
const rows: HTMLElement[] = [heading]
|
||||
|
||||
if (exif.dateTimeOriginal) {
|
||||
rows.push(renderDateRow(exif.dateTimeOriginal))
|
||||
}
|
||||
const fileRow = renderFileRow(exif)
|
||||
if (fileRow) rows.push(fileRow)
|
||||
const cameraRow = renderCameraRow(exif)
|
||||
if (cameraRow) rows.push(cameraRow)
|
||||
const lensRow = renderLensRow(exif)
|
||||
if (lensRow) rows.push(lensRow)
|
||||
|
||||
return rows
|
||||
}
|
||||
|
||||
function renderDateRow (iso: string): HTMLElement {
|
||||
const row = document.createElement('div')
|
||||
row.className = 'ipp-sidebar-row ipp-sidebar-date'
|
||||
row.textContent = formatDate(iso)
|
||||
return row
|
||||
}
|
||||
|
||||
function renderFileRow (exif: GalleryExif): HTMLElement | null {
|
||||
if (!exif.fileName && !exif.width && !exif.fileSizeInByte) return null
|
||||
const row = makeRow(ICON_IMAGE)
|
||||
const body = row.querySelector('.ipp-sidebar-row-body') as HTMLElement
|
||||
if (exif.fileName) {
|
||||
const name = document.createElement('p')
|
||||
name.className = 'ipp-sidebar-filename'
|
||||
name.textContent = exif.fileName
|
||||
body.appendChild(name)
|
||||
}
|
||||
if (exif.width && exif.height) {
|
||||
const stats = document.createElement('div')
|
||||
stats.className = 'ipp-sidebar-stats'
|
||||
const mp = Math.round((exif.width * exif.height) / 1_000_000)
|
||||
if (mp >= 1) stats.appendChild(makeStat(mp + ' MP'))
|
||||
stats.appendChild(makeStat(exif.width + ' x ' + exif.height))
|
||||
if (exif.fileSizeInByte) stats.appendChild(makeStat(formatBytes(exif.fileSizeInByte)))
|
||||
body.appendChild(stats)
|
||||
} else if (exif.fileSizeInByte) {
|
||||
const stats = document.createElement('div')
|
||||
stats.className = 'ipp-sidebar-stats'
|
||||
stats.appendChild(makeStat(formatBytes(exif.fileSizeInByte)))
|
||||
body.appendChild(stats)
|
||||
}
|
||||
return row
|
||||
}
|
||||
|
||||
function renderCameraRow (exif: GalleryExif): HTMLElement | null {
|
||||
if (!exif.make && !exif.model && exif.exposureTime == null && exif.iso == null) return null
|
||||
const row = makeRow(ICON_CAMERA)
|
||||
const body = row.querySelector('.ipp-sidebar-row-body') as HTMLElement
|
||||
const label = [exif.make, exif.model].filter(Boolean).join(' ').trim()
|
||||
if (label) {
|
||||
const p = document.createElement('p')
|
||||
p.textContent = label
|
||||
body.appendChild(p)
|
||||
}
|
||||
const stats = document.createElement('div')
|
||||
stats.className = 'ipp-sidebar-stats'
|
||||
if (exif.exposureTime) stats.appendChild(makeStat(exif.exposureTime + ' s'))
|
||||
if (exif.iso != null) stats.appendChild(makeStat('ISO ' + exif.iso))
|
||||
if (stats.childElementCount) body.appendChild(stats)
|
||||
return row
|
||||
}
|
||||
|
||||
function renderLensRow (exif: GalleryExif): HTMLElement | null {
|
||||
if (!exif.lensModel && exif.fNumber == null && exif.focalLength == null) return null
|
||||
const row = makeRow(ICON_IRIS)
|
||||
const body = row.querySelector('.ipp-sidebar-row-body') as HTMLElement
|
||||
if (exif.lensModel) {
|
||||
const p = document.createElement('p')
|
||||
p.className = 'ipp-sidebar-lens'
|
||||
p.textContent = exif.lensModel
|
||||
body.appendChild(p)
|
||||
}
|
||||
const stats = document.createElement('div')
|
||||
stats.className = 'ipp-sidebar-stats'
|
||||
if (exif.fNumber != null) stats.appendChild(makeStat('f/' + exif.fNumber))
|
||||
if (exif.focalLength != null) stats.appendChild(makeStat(exif.focalLength + ' mm'))
|
||||
if (stats.childElementCount) body.appendChild(stats)
|
||||
return row
|
||||
}
|
||||
|
||||
function renderLocation (exif: GalleryExif): HTMLElement {
|
||||
const wrap = document.createElement('div')
|
||||
wrap.className = 'ipp-sidebar-row'
|
||||
const icon = document.createElement('div')
|
||||
icon.className = 'ipp-sidebar-row-icon'
|
||||
icon.innerHTML = ICON_MAP
|
||||
wrap.appendChild(icon)
|
||||
const body = document.createElement('div')
|
||||
body.className = 'ipp-sidebar-row-body'
|
||||
|
||||
const parts = [exif.city, exif.state, exif.country].filter(Boolean) as string[]
|
||||
if (parts.length) {
|
||||
const place = document.createElement('p')
|
||||
place.textContent = parts.join(', ')
|
||||
body.appendChild(place)
|
||||
}
|
||||
|
||||
if (exif.latitude != null && exif.longitude != null) {
|
||||
const coords = document.createElement('p')
|
||||
coords.className = 'ipp-sidebar-coords'
|
||||
coords.textContent = exif.latitude.toFixed(5) + ', ' + exif.longitude.toFixed(5)
|
||||
body.appendChild(coords)
|
||||
|
||||
const link = document.createElement('a')
|
||||
link.className = 'ipp-sidebar-osm'
|
||||
link.href = 'https://www.openstreetmap.org/?mlat=' + exif.latitude +
|
||||
'&mlon=' + exif.longitude +
|
||||
'#map=15/' + exif.latitude + '/' + exif.longitude
|
||||
link.target = '_blank'
|
||||
link.rel = 'noopener'
|
||||
link.textContent = 'Open in OpenStreetMap'
|
||||
body.appendChild(link)
|
||||
}
|
||||
|
||||
wrap.appendChild(body)
|
||||
return wrap
|
||||
}
|
||||
|
||||
// ----- helpers -------------------------------------------------------------
|
||||
|
||||
function makeRow (iconSvg: string): HTMLElement {
|
||||
const row = document.createElement('div')
|
||||
row.className = 'ipp-sidebar-row'
|
||||
const icon = document.createElement('div')
|
||||
icon.className = 'ipp-sidebar-row-icon'
|
||||
icon.innerHTML = iconSvg
|
||||
row.appendChild(icon)
|
||||
const body = document.createElement('div')
|
||||
body.className = 'ipp-sidebar-row-body'
|
||||
row.appendChild(body)
|
||||
return row
|
||||
}
|
||||
|
||||
function makeStat (text: string): HTMLElement {
|
||||
const span = document.createElement('span')
|
||||
span.textContent = text
|
||||
return span
|
||||
}
|
||||
|
||||
function hasAnyExifField (exif: GalleryExif): boolean {
|
||||
return !!(exif.dateTimeOriginal || exif.fileName || exif.width || exif.fileSizeInByte ||
|
||||
exif.make || exif.model || exif.lensModel ||
|
||||
exif.exposureTime != null || exif.iso != null ||
|
||||
exif.fNumber != null || exif.focalLength != null)
|
||||
}
|
||||
|
||||
function hasAnyLocationField (exif: GalleryExif): boolean {
|
||||
return !!(exif.city || exif.state || exif.country ||
|
||||
(exif.latitude != null && exif.longitude != null))
|
||||
}
|
||||
|
||||
function formatDate (iso: string): string {
|
||||
const d = new Date(iso)
|
||||
if (isNaN(d.getTime())) return iso
|
||||
try {
|
||||
return new Intl.DateTimeFormat(undefined, {
|
||||
year: 'numeric',
|
||||
month: 'long',
|
||||
day: 'numeric',
|
||||
hour: 'numeric',
|
||||
minute: '2-digit'
|
||||
}).format(d)
|
||||
} catch (e) {
|
||||
return iso
|
||||
}
|
||||
}
|
||||
|
||||
function formatBytes (bytes: number): string {
|
||||
if (bytes < 1024) return bytes + ' B'
|
||||
const kb = bytes / 1024
|
||||
if (kb < 1024) return kb.toFixed(1) + ' KB'
|
||||
const mb = kb / 1024
|
||||
if (mb < 1024) return mb.toFixed(1) + ' MB'
|
||||
return (mb / 1024).toFixed(2) + ' GB'
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
// Shared mutable state for the client gallery. Every module that touches
|
||||
// gallery-wide state goes through `state` rather than holding its own
|
||||
// top-level `let`s. Constants and icon strings live here too because they
|
||||
// are read by multiple modules.
|
||||
|
||||
import type { GalleryItem, LightboxConfig, MetadataConfig } from '../shared/types.js'
|
||||
|
||||
// ----- layout / scroll tuning ----------------------------------------------
|
||||
|
||||
// Justified-rows target row height (matches Immich's main view)
|
||||
export const TARGET_ROW_HEIGHT = 235
|
||||
export const GAP = 4
|
||||
export const MOBILE_BREAKPOINT = 640
|
||||
export const MOBILE_COLS = 3
|
||||
export const IMAGE_LOAD_MARGIN_PX = 300
|
||||
export const SCROLL_SETTLE_MS = 100
|
||||
export const BUFFER_VIEWPORTS = 1
|
||||
// Height reserved for each month header (must agree with .group-header CSS)
|
||||
export const HEADER_HEIGHT = 48
|
||||
// Vertical gap between groups
|
||||
export const GROUP_GAP = 16
|
||||
// Long-press threshold for entering select mode via touch/mouse
|
||||
export const LONG_PRESS_MS = 500
|
||||
|
||||
// ----- icons ----------------------------------------------------------------
|
||||
|
||||
// MDI icons (Apache 2.0). Same icon set Immich uses for its viewer.
|
||||
export const ICON_DOWNLOAD = '<svg class="pswp__icn" viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M5,20H19V18H5M19,9H15V3H9V9H5L12,16L19,9Z"/></svg>'
|
||||
export const ICON_FULLSCREEN = '<svg class="pswp__icn" viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M5,5H10V7H7V10H5V5M14,5H19V10H17V7H14V5M17,14H19V19H14V17H17V14M10,17V19H5V14H7V17H10Z"/></svg>'
|
||||
export const ICON_FULLSCREEN_EXIT = '<svg class="pswp__icn" viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M14,14H19V16H16V19H14V14M5,14H10V19H8V16H5V14M8,5H10V10H5V8H8V5M19,8V10H14V5H16V8H19Z"/></svg>'
|
||||
export const ICON_INFO = '<svg class="pswp__icn" viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M11,9H13V7H11M12,20C7.59,20 4,16.41 4,12C4,7.59 7.59,4 12,4C16.41,4 20,7.59 20,12C20,16.41 16.41,20 12,20M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2M11,17H13V11H11V17Z"/></svg>'
|
||||
export const ICON_BACK = '<svg class="pswp__icn" viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M20,11V13H8L13.5,18.5L12.08,19.92L4.16,12L12.08,4.08L13.5,5.5L8,11H20Z"/></svg>'
|
||||
export const ICON_CLOSE = '<svg viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M19,6.41L17.59,5L12,10.59L6.41,5L5,6.41L10.59,12L5,17.59L6.41,19L12,13.41L17.59,19L19,17.59L13.41,12L19,6.41Z"/></svg>'
|
||||
// MDI camera / iris / image icons for the sidebar field rows
|
||||
export const ICON_IMAGE = '<svg viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M8.5,13.5L11,16.5L14.5,12L19,18H5M21,19V5C21,3.89 20.1,3 19,3H5A2,2 0 0,0 3,5V19A2,2 0 0,0 5,21H19A2,2 0 0,0 21,19Z"/></svg>'
|
||||
export const ICON_CAMERA = '<svg viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M4,4H7L9,2H15L17,4H20A2,2 0 0,1 22,6V18A2,2 0 0,1 20,20H4A2,2 0 0,1 2,18V6A2,2 0 0,1 4,4M12,7A5,5 0 0,0 7,12A5,5 0 0,0 12,17A5,5 0 0,0 17,12A5,5 0 0,0 12,7M12,9A3,3 0 0,1 15,12A3,3 0 0,1 12,15A3,3 0 0,1 9,12A3,3 0 0,1 12,9Z"/></svg>'
|
||||
export const ICON_IRIS = '<svg viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M5,5H10.5L7.9,11H4L5,5M11.5,5H17L15.4,11H9.9L11.5,5M18,5H20.93L20.61,7H17.4L18,5M3.66,13H7.41L7,15.5L8.5,18.83L8,22L4.31,19L2.34,16.38L3.66,13M9.42,13H14.58L15.58,15.4L13.4,22H10.6L8.42,15.4L9.42,13M16.59,13H21.34L20.92,16.92L16.5,21.5L15.5,18.5L17,15.4L16.59,13Z"/></svg>'
|
||||
export const ICON_MAP = '<svg viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M12,11.5A2.5,2.5 0 0,1 9.5,9A2.5,2.5 0 0,1 12,6.5A2.5,2.5 0 0,1 14.5,9A2.5,2.5 0 0,1 12,11.5M12,2A7,7 0 0,0 5,9C5,14.25 12,22 12,22C12,22 19,14.25 19,9A7,7 0 0,0 12,2Z"/></svg>'
|
||||
// Inline SVG for the check icon shown inside selected tiles' checkmark circle
|
||||
export const CHECK_SVG = '<svg viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M21,7L9,19L3.5,13.5L4.91,12.09L9,16.17L19.59,5.59L21,7Z"/></svg>'
|
||||
|
||||
// localStorage key for sidebar open state
|
||||
export const SIDEBAR_STORAGE_KEY = 'ipp-sidebar-open'
|
||||
// Width of the sidebar when docked (must match the CSS rule)
|
||||
export const SIDEBAR_WIDTH = 360
|
||||
|
||||
// ----- mutable state -------------------------------------------------------
|
||||
|
||||
export interface LayoutEntry {
|
||||
index: number
|
||||
left: number
|
||||
top: number
|
||||
width: number
|
||||
height: number
|
||||
}
|
||||
|
||||
export interface HeaderEntry {
|
||||
label: string
|
||||
top: number
|
||||
height: number
|
||||
}
|
||||
|
||||
export interface GroupSpec {
|
||||
label: string | null
|
||||
indices: number[]
|
||||
}
|
||||
|
||||
// PhotoSwipeLightbox is an external module with no TS types in this project.
|
||||
// Typing it as `unknown` would push casts to every call site; `any` is the
|
||||
// pragmatic choice and stays scoped to this single state slot.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
type PhotoSwipeLightboxInstance = any
|
||||
|
||||
export const state = {
|
||||
items: [] as GalleryItem[],
|
||||
layout: [] as LayoutEntry[],
|
||||
headers: [] as HeaderEntry[],
|
||||
groupByDate: false,
|
||||
container: null as HTMLElement | null,
|
||||
lightbox: null as PhotoSwipeLightboxInstance,
|
||||
lightboxConfig: {} as Partial<LightboxConfig>,
|
||||
metadataConfig: {
|
||||
descriptionInCaption: false,
|
||||
descriptionInSidebar: false,
|
||||
sidebarHasContent: false
|
||||
} as MetadataConfig,
|
||||
// True while our pushed history entry is live
|
||||
lightboxPushedHistory: false,
|
||||
// Guards against re-entering the popstate handler during our own history.back()
|
||||
closingFromHistory: false,
|
||||
lastContainerW: 0,
|
||||
renderedTiles: new Map<number, HTMLAnchorElement>(),
|
||||
renderedHeaders: new Map<string, HTMLElement>(),
|
||||
// Selection mode (mode-toggle UX: hidden checkmarks until activated)
|
||||
selectMode: false,
|
||||
selected: new Set<string>(),
|
||||
toolbarEl: null as HTMLElement | null,
|
||||
countEl: null as HTMLElement | null,
|
||||
selectAllBtn: null as HTMLButtonElement | null,
|
||||
cancelBtn: null as HTMLButtonElement | null,
|
||||
downloadBtn: null as HTMLButtonElement | null,
|
||||
// Info sidebar open/closed. Persisted to localStorage so the choice
|
||||
// survives navigation between slides and gallery reloads.
|
||||
sidebarOpen: false
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
// Per-tile DOM construction: anchor, image, thumbhash blur background, video
|
||||
// play icon, selection checkmark, click + long-press handlers.
|
||||
|
||||
// Runtime URL resolved by Express static, not a TS-resolvable module path.
|
||||
// @ts-expect-error - browser-only ESM URL
|
||||
import { thumbHashToDataURL } from '/share/static/thumbhash/thumbhash.js' // eslint-disable-line import/no-absolute-path
|
||||
|
||||
import { state, CHECK_SVG, LONG_PRESS_MS } from './state.js'
|
||||
import { enterSelectMode, toggleSelection } from './selection.js'
|
||||
import { openLightbox } from './lightbox.js'
|
||||
|
||||
function onThumbError (this: HTMLImageElement) {
|
||||
this.closest('a')?.classList.add('thumb-error')
|
||||
}
|
||||
|
||||
// Cache of decoded thumbhash → PNG data URL. Same thumbhash on multiple
|
||||
// tile-creations (revisits during virtualization) reuses the same URL.
|
||||
const thumbhashCache = new Map<string, string | null>()
|
||||
|
||||
function decodeThumbhash (base64: string): string | null {
|
||||
const cached = thumbhashCache.get(base64)
|
||||
if (cached !== undefined) return cached
|
||||
try {
|
||||
const binary = atob(base64)
|
||||
const bytes = new Uint8Array(binary.length)
|
||||
for (let i = 0; i < bytes.length; i++) bytes[i] = binary.charCodeAt(i)
|
||||
const url = thumbHashToDataURL(bytes) as string
|
||||
thumbhashCache.set(base64, url)
|
||||
return url
|
||||
} catch (e) {
|
||||
thumbhashCache.set(base64, null)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the anchor element for one tile at the given index in `state.items`.
|
||||
* Positioning is taken from the precomputed `state.layout`.
|
||||
*
|
||||
* The tile shows the thumbhash blur as a background, an `<img>` whose `src`
|
||||
* is held back until the tile enters the viewport (see
|
||||
* `loadVisibleTiles`), a play overlay for videos, and a selection
|
||||
* checkmark + long-press handler if the share allows downloads.
|
||||
*
|
||||
* Click opens the lightbox unless selection mode is active, in which case
|
||||
* it toggles the item's selection.
|
||||
*/
|
||||
export function createTile (index: number): HTMLAnchorElement {
|
||||
const item = state.items[index]
|
||||
const l = state.layout[index]
|
||||
const a = document.createElement('a')
|
||||
a.dataset.index = String(index)
|
||||
if (item.type !== 'VIDEO') a.href = item.previewUrl
|
||||
a.style.left = l.left + 'px'
|
||||
a.style.top = l.top + 'px'
|
||||
a.style.width = l.width + 'px'
|
||||
a.style.height = l.height + 'px'
|
||||
|
||||
if (item.thumbhash) {
|
||||
const url = decodeThumbhash(item.thumbhash)
|
||||
if (url) a.style.backgroundImage = 'url(' + url + ')'
|
||||
}
|
||||
|
||||
const img = document.createElement('img')
|
||||
// alt left empty: browsers paint alt text over the thumbhash background
|
||||
// while the thumbnail downloads. Description (if any) is shown in the
|
||||
// lightbox caption instead.
|
||||
img.alt = ''
|
||||
img.dataset.src = item.thumbnailUrl
|
||||
img.onerror = onThumbError
|
||||
// Mark the image as drawable once its bytes are decoded; the CSS rule
|
||||
// `#gallery img.loaded` fades opacity from 0 to 1 so the thumbhash blurs
|
||||
// into the sharp image instead of snapping (and masks Chrome/Edge's brief
|
||||
// white flash between `img.src` being set and the bytes actually painting).
|
||||
img.onload = () => img.classList.add('loaded')
|
||||
a.appendChild(img)
|
||||
|
||||
if (item.type === 'VIDEO') {
|
||||
const playIcon = document.createElement('div')
|
||||
playIcon.className = 'play-icon'
|
||||
a.appendChild(playIcon)
|
||||
}
|
||||
|
||||
// Selection checkmark (rendered only when select mode is even possible -
|
||||
// i.e. when the page included the toolbar element)
|
||||
if (state.toolbarEl) {
|
||||
const check = document.createElement('div')
|
||||
check.className = 'tile-check'
|
||||
check.innerHTML = CHECK_SVG
|
||||
check.addEventListener('click', (e) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
if (!state.selectMode) enterSelectMode()
|
||||
toggleSelection(item.id)
|
||||
})
|
||||
a.appendChild(check)
|
||||
if (state.selected.has(item.id)) a.classList.add('selected')
|
||||
attachLongPress(a, item.id)
|
||||
}
|
||||
|
||||
a.addEventListener('click', (e) => {
|
||||
e.preventDefault()
|
||||
if (state.selectMode) {
|
||||
toggleSelection(item.id)
|
||||
} else {
|
||||
openLightbox(index)
|
||||
}
|
||||
})
|
||||
|
||||
return a
|
||||
}
|
||||
|
||||
/**
|
||||
* Wire press-and-hold on a tile to enter selection mode and toggle the
|
||||
* tile's item. Cancels on pointer movement above a small threshold (so a
|
||||
* scroll gesture doesn't trigger it) and suppresses the synthetic click
|
||||
* that follows a successful long-press (so the lightbox doesn't open).
|
||||
*/
|
||||
function attachLongPress (tile: HTMLAnchorElement, id: string) {
|
||||
let timer: ReturnType<typeof setTimeout> | null = null
|
||||
let pressed = false
|
||||
const cancel = () => {
|
||||
if (timer) { clearTimeout(timer); timer = null }
|
||||
}
|
||||
tile.addEventListener('pointerdown', (e) => {
|
||||
// Ignore right/middle clicks
|
||||
if (e.button !== undefined && e.button !== 0) return
|
||||
pressed = false
|
||||
timer = setTimeout(() => {
|
||||
timer = null
|
||||
pressed = true
|
||||
if (!state.selectMode) enterSelectMode()
|
||||
toggleSelection(id)
|
||||
}, LONG_PRESS_MS)
|
||||
})
|
||||
tile.addEventListener('pointerup', cancel)
|
||||
tile.addEventListener('pointercancel', cancel)
|
||||
tile.addEventListener('pointerleave', cancel)
|
||||
tile.addEventListener('pointermove', (e) => {
|
||||
// Cancel long-press if pointer moves significantly (scroll, drag)
|
||||
if (Math.abs(e.movementX) + Math.abs(e.movementY) > 6) cancel()
|
||||
})
|
||||
// Swallow the synthetic click that follows a successful long-press so it
|
||||
// doesn't open the lightbox.
|
||||
tile.addEventListener('click', (e) => {
|
||||
if (pressed) {
|
||||
pressed = false
|
||||
e.preventDefault()
|
||||
e.stopImmediatePropagation()
|
||||
}
|
||||
}, true)
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
// Viewport-based tile / header lifecycle. Only tiles within viewport ± 1
|
||||
// viewport-height buffer exist in the DOM at any moment. The image-src
|
||||
// lifecycle (lazy load / unload of `img.src`) is part of the same loop.
|
||||
|
||||
import {
|
||||
state,
|
||||
IMAGE_LOAD_MARGIN_PX,
|
||||
SCROLL_SETTLE_MS,
|
||||
BUFFER_VIEWPORTS,
|
||||
type HeaderEntry
|
||||
} from './state.js'
|
||||
import { computeLayout } from './layout.js'
|
||||
import { createTile } from './tiles.js'
|
||||
|
||||
function getVisibleRange () {
|
||||
if (!state.container) return { top: 0, bottom: 0 }
|
||||
const containerTop = state.container.getBoundingClientRect().top
|
||||
const viewportTopInContainer = -containerTop
|
||||
const viewportBottomInContainer = viewportTopInContainer + window.innerHeight
|
||||
const buffer = window.innerHeight * BUFFER_VIEWPORTS
|
||||
return {
|
||||
top: viewportTopInContainer - buffer,
|
||||
bottom: viewportBottomInContainer + buffer
|
||||
}
|
||||
}
|
||||
|
||||
function createHeader (header: HeaderEntry): HTMLElement {
|
||||
const el = document.createElement('h2')
|
||||
el.className = 'group-header'
|
||||
el.style.top = header.top + 'px'
|
||||
el.textContent = header.label
|
||||
return el
|
||||
}
|
||||
|
||||
/**
|
||||
* Bring the DOM in line with the current visible range: create tiles and
|
||||
* headers that should now be on screen, remove ones that have scrolled out.
|
||||
* Idempotent; safe to call multiple times per frame (scroll handler does).
|
||||
*/
|
||||
export function virtualize () {
|
||||
if (!state.container || !state.layout.length) return
|
||||
const { top, bottom } = getVisibleRange()
|
||||
|
||||
// Tiles
|
||||
const neededTiles = new Set<number>()
|
||||
for (const l of state.layout) {
|
||||
if (!l) continue
|
||||
if (l.top + l.height < top) continue
|
||||
if (l.top > bottom) break
|
||||
neededTiles.add(l.index)
|
||||
}
|
||||
for (const [index, el] of state.renderedTiles) {
|
||||
if (!neededTiles.has(index)) {
|
||||
el.remove()
|
||||
state.renderedTiles.delete(index)
|
||||
}
|
||||
}
|
||||
for (const index of neededTiles) {
|
||||
if (state.renderedTiles.has(index)) continue
|
||||
const tile = createTile(index)
|
||||
state.container.appendChild(tile)
|
||||
state.renderedTiles.set(index, tile)
|
||||
}
|
||||
|
||||
// Group headers (when grouping is enabled; headers is empty otherwise)
|
||||
const neededHeaders = new Set<string>()
|
||||
for (const h of state.headers) {
|
||||
if (h.top + h.height < top) continue
|
||||
if (h.top > bottom) break
|
||||
neededHeaders.add(h.label)
|
||||
}
|
||||
for (const [label, el] of state.renderedHeaders) {
|
||||
if (!neededHeaders.has(label)) {
|
||||
el.remove()
|
||||
state.renderedHeaders.delete(label)
|
||||
}
|
||||
}
|
||||
for (const label of neededHeaders) {
|
||||
if (state.renderedHeaders.has(label)) continue
|
||||
const h = state.headers.find(x => x.label === label)
|
||||
if (!h) continue
|
||||
const el = createHeader(h)
|
||||
state.container.appendChild(el)
|
||||
state.renderedHeaders.set(label, el)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Recompute the layout when the container width has actually changed, then
|
||||
* re-virtualize and load images for the visible range. If the width is the
|
||||
* same as last time (e.g. a resize fired but the gallery column is unchanged)
|
||||
* the cached layout is reused and only virtualize runs.
|
||||
*
|
||||
* Called from the ResizeObserver in init.ts.
|
||||
*/
|
||||
export function computeLayoutAndRender () {
|
||||
if (!state.container) return
|
||||
const containerW = state.container.clientWidth
|
||||
if (containerW <= 0) return
|
||||
if (containerW === state.lastContainerW) {
|
||||
virtualize()
|
||||
return
|
||||
}
|
||||
state.lastContainerW = containerW
|
||||
|
||||
const result = computeLayout(containerW)
|
||||
state.layout = result.layout
|
||||
state.headers = result.headers
|
||||
state.container.style.height = result.totalHeight + 'px'
|
||||
|
||||
for (const [, el] of state.renderedTiles) el.remove()
|
||||
state.renderedTiles.clear()
|
||||
for (const [, el] of state.renderedHeaders) el.remove()
|
||||
state.renderedHeaders.clear()
|
||||
|
||||
virtualize()
|
||||
loadVisibleTiles()
|
||||
}
|
||||
|
||||
/**
|
||||
* Walk the currently rendered tiles and toggle their `<img>` src based on
|
||||
* proximity to the viewport. Tiles within IMAGE_LOAD_MARGIN_PX get their
|
||||
* `data-src` promoted to `src` (browser fetches the thumbnail); tiles far
|
||||
* off-screen with an unfinished load have their `src` parked back into
|
||||
* `data-src` so the browser cancels the fetch.
|
||||
*
|
||||
* Run after scroll has settled, not on every scroll tick.
|
||||
*/
|
||||
export function loadVisibleTiles () {
|
||||
if (!state.container) return
|
||||
const vpHeight = window.innerHeight
|
||||
const containerTop = state.container.getBoundingClientRect().top
|
||||
for (const a of state.renderedTiles.values()) {
|
||||
const img = a.firstElementChild
|
||||
if (!(img instanceof HTMLImageElement)) continue
|
||||
const aTopInVp = containerTop + parseFloat(a.style.top || '0')
|
||||
const aHeight = parseFloat(a.style.height || '0')
|
||||
const isFar = aTopInVp + aHeight < -IMAGE_LOAD_MARGIN_PX ||
|
||||
aTopInVp > vpHeight + IMAGE_LOAD_MARGIN_PX
|
||||
if (isFar) {
|
||||
if (img.src && !img.complete) {
|
||||
img.dataset.src = img.src
|
||||
img.removeAttribute('src')
|
||||
}
|
||||
} else if (img.dataset.src) {
|
||||
img.src = img.dataset.src
|
||||
img.removeAttribute('data-src')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let scrollFrame: number | null = null
|
||||
let loadTimer: ReturnType<typeof setTimeout> | null = null
|
||||
|
||||
/**
|
||||
* Window scroll handler. Coalesces virtualize calls into the next animation
|
||||
* frame and debounces the more expensive image-src lifecycle by
|
||||
* SCROLL_SETTLE_MS so we don't thrash `img.src` during fast flings.
|
||||
*/
|
||||
export function onScroll () {
|
||||
if (scrollFrame == null) {
|
||||
scrollFrame = requestAnimationFrame(() => {
|
||||
scrollFrame = null
|
||||
virtualize()
|
||||
})
|
||||
}
|
||||
if (loadTimer) clearTimeout(loadTimer)
|
||||
loadTimer = setTimeout(() => {
|
||||
loadTimer = null
|
||||
loadVisibleTiles()
|
||||
}, SCROLL_SETTLE_MS)
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { getCurrentConfig } from './loader'
|
||||
|
||||
/**
|
||||
* Read a configuration option using dotted notation. Returns `defaultOption`
|
||||
* when the path doesn't resolve to a value.
|
||||
*
|
||||
* @example
|
||||
* getConfigOption('ipp.gallery.singleImage', false)
|
||||
*/
|
||||
export function getConfigOption (path: string, defaultOption?: unknown) {
|
||||
const value = path.split('.').reduce(
|
||||
(obj: { [key: string]: unknown }, key) => (obj || {})[key] as { [key: string]: unknown },
|
||||
getCurrentConfig() as { [key: string]: unknown }
|
||||
)
|
||||
if (value === undefined) {
|
||||
return defaultOption
|
||||
}
|
||||
return value
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { readFileSync } from 'fs'
|
||||
import { resolve } from 'path'
|
||||
import { applyMigrations } from './migrations'
|
||||
|
||||
export type Config = Record<string, unknown>
|
||||
|
||||
// Module-level cache populated by `loadConfig()`. Access through
|
||||
// `getCurrentConfig()` rather than importing directly; that gives
|
||||
// `config/access.ts` a stable read path even before `loadConfig()` has
|
||||
// been called (returning an empty object so calls fall back to defaults).
|
||||
let currentConfig: Config = {}
|
||||
|
||||
/**
|
||||
* Read the runtime configuration from `process.env.CONFIG` (an inline JSON
|
||||
* string, typically set in docker-compose) or from the config file. Applies
|
||||
* backward-compatibility migrations, caches the result, and returns it.
|
||||
*
|
||||
* Called once from `index.ts` at startup. Safe to call again in tests with
|
||||
* a fresh env to reset state.
|
||||
*/
|
||||
export function loadConfig (): Config {
|
||||
let config: Config = {}
|
||||
try {
|
||||
if (process.env.CONFIG) {
|
||||
// Attempt to parse docker-compose config string into JSON (if specified)
|
||||
config = JSON.parse(process.env.CONFIG)
|
||||
} else {
|
||||
// Default config.json sits one level above the compiled dist/ output.
|
||||
// IPP_CONFIG (if set) is taken as-is for absolute paths, or resolved
|
||||
// against the current working directory for relative paths.
|
||||
const configPath = process.env.IPP_CONFIG
|
||||
? resolve(process.env.IPP_CONFIG)
|
||||
: resolve(__dirname, '../../config.json')
|
||||
const configJson = JSON.parse(readFileSync(configPath, 'utf8'))
|
||||
if (typeof configJson === 'object') config = configJson
|
||||
}
|
||||
} catch (e) {
|
||||
console.log(e)
|
||||
}
|
||||
|
||||
applyMigrations(config)
|
||||
currentConfig = config
|
||||
return config
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the most recently loaded config, or an empty object if
|
||||
* `loadConfig()` hasn't been called yet. Used by `getConfigOption`.
|
||||
*/
|
||||
export function getCurrentConfig (): Config {
|
||||
return currentConfig
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
// Backward-compatability shims that map legacy `config.json` key shapes
|
||||
// onto their current locations. Each one only fills in values the user
|
||||
// hasn't explicitly set on the new path, and prints a one-time deprecation
|
||||
// warning to the startup log.
|
||||
//
|
||||
// Delete in v3.0.
|
||||
|
||||
type Config = Record<string, unknown>
|
||||
|
||||
/**
|
||||
* Apply every supported legacy-config shim to `config` in place.
|
||||
* Called from `loadConfig()` after reading the file or env JSON.
|
||||
*/
|
||||
export function applyMigrations (config: Config): void {
|
||||
applyLightGalleryShim(config)
|
||||
applyTopLevelGalleryShim(config)
|
||||
applyDescriptionSplitShim(config)
|
||||
}
|
||||
|
||||
/**
|
||||
* 1.x users with a legacy `lightGallery.*` config section.
|
||||
* Maps `lightGallery.controls`, `lightGallery.download`, and
|
||||
* `lightGallery.mobileSettings.controls` onto `ipp.lightbox.*`.
|
||||
*
|
||||
* Delete in v3.0.
|
||||
*/
|
||||
function applyLightGalleryShim (config: Config): void {
|
||||
if (!config.lightGallery || typeof config.lightGallery !== 'object') return
|
||||
|
||||
const lg = config.lightGallery as Record<string, unknown>
|
||||
const mobile = (lg.mobileSettings || {}) as Record<string, unknown>
|
||||
const ipp = (config.ipp || (config.ipp = {})) as Record<string, unknown>
|
||||
const lightbox = (ipp.lightbox || (ipp.lightbox = {})) as Record<string, unknown>
|
||||
|
||||
if (lightbox.showArrows === undefined && lg.controls !== undefined) {
|
||||
lightbox.showArrows = !!lg.controls
|
||||
}
|
||||
if (lightbox.showDownload === undefined && lg.download !== undefined) {
|
||||
lightbox.showDownload = !!lg.download
|
||||
}
|
||||
if (lightbox.mobileArrows === undefined && mobile.controls !== undefined) {
|
||||
lightbox.mobileArrows = !!mobile.controls
|
||||
}
|
||||
|
||||
console.log(
|
||||
'[IPP] The `lightGallery` config section is deprecated; relevant keys ' +
|
||||
'have been mapped to `ipp.lightbox.*`. See README for the current options.'
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Gallery-related keys that used to live directly on `ipp` now live under
|
||||
* `ipp.gallery`. Maps legacy keys forward, only filling in fields the user
|
||||
* hasn't already set on the new path.
|
||||
*
|
||||
* Delete in v3.0.
|
||||
*/
|
||||
function applyTopLevelGalleryShim (config: Config): void {
|
||||
const ipp = (config.ipp || (config.ipp = {})) as Record<string, unknown>
|
||||
const galleryKeyMigrations: Array<[string, string]> = [
|
||||
['singleImageGallery', 'singleImage'],
|
||||
['singleItemAutoOpen', 'singleItemAutoOpen'],
|
||||
['showGalleryTitle', 'showTitle'],
|
||||
['showGalleryDescription', 'showDescription'],
|
||||
['groupGalleryByDate', 'groupByDate']
|
||||
]
|
||||
const legacyPresent = galleryKeyMigrations.some(([oldKey]) => ipp[oldKey] !== undefined)
|
||||
if (!legacyPresent) return
|
||||
|
||||
const gallery = (ipp.gallery || (ipp.gallery = {})) as Record<string, unknown>
|
||||
for (const [oldKey, newKey] of galleryKeyMigrations) {
|
||||
if (ipp[oldKey] !== undefined && gallery[newKey] === undefined) {
|
||||
gallery[newKey] = ipp[oldKey]
|
||||
}
|
||||
}
|
||||
|
||||
console.log(
|
||||
'[IPP] Top-level gallery keys (singleImageGallery, singleItemAutoOpen, ' +
|
||||
'showGalleryTitle, showGalleryDescription, groupGalleryByDate) are ' +
|
||||
'deprecated; please move them under `ipp.gallery.*`. See README.'
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* `ipp.showMetadata.description` used to be a single boolean controlling
|
||||
* both the lightbox caption and (later) the sidebar. It is now an object
|
||||
* with separate `caption` and `sidebar` flags. A legacy boolean value is
|
||||
* migrated to `{ caption: <bool>, sidebar: <bool> }` so existing configs
|
||||
* continue to render description in both places.
|
||||
*
|
||||
* Delete in v3.0.
|
||||
*/
|
||||
function applyDescriptionSplitShim (config: Config): void {
|
||||
const ipp = (config.ipp || (config.ipp = {})) as Record<string, unknown>
|
||||
const showMetadata = ipp.showMetadata as Record<string, unknown> | undefined
|
||||
if (!showMetadata) return
|
||||
if (typeof showMetadata.description !== 'boolean') return
|
||||
|
||||
const legacy = showMetadata.description
|
||||
showMetadata.description = { caption: legacy, sidebar: legacy }
|
||||
|
||||
console.log(
|
||||
'[IPP] `ipp.showMetadata.description` as a boolean is deprecated; use ' +
|
||||
'`{ "caption": <bool>, "sidebar": <bool> }` to control each surface ' +
|
||||
'independently. See README.'
|
||||
)
|
||||
}
|
||||
@@ -1,129 +0,0 @@
|
||||
import dayjs from 'dayjs'
|
||||
import { Response } from 'express-serve-static-core'
|
||||
import { DownloadAll, SharedLink } from './types'
|
||||
|
||||
let config: { [key: string]: unknown } = {}
|
||||
try {
|
||||
if (process.env.CONFIG) {
|
||||
// Attempt to parse docker-compose config string into JSON (if specified)
|
||||
config = JSON.parse(process.env.CONFIG)
|
||||
} else {
|
||||
const configJson = require(process.env.IPP_CONFIG || '../config.json')
|
||||
if (typeof configJson === 'object') config = configJson
|
||||
}
|
||||
} catch (e) {
|
||||
console.log(e)
|
||||
}
|
||||
|
||||
// Backward-compatability shim for 1.x users with a legacy `lightGallery.*` config section
|
||||
if (config.lightGallery && typeof config.lightGallery === 'object') {
|
||||
const lg = config.lightGallery as Record<string, unknown>
|
||||
const mobile = (lg.mobileSettings || {}) as Record<string, unknown>
|
||||
const ipp = (config.ipp || (config.ipp = {})) as Record<string, unknown>
|
||||
const lightbox = (ipp.lightbox || (ipp.lightbox = {})) as Record<string, unknown>
|
||||
// Only fill in fields the user hasn't already set on ipp.lightbox.
|
||||
if (lightbox.showArrows === undefined && lg.controls !== undefined) {
|
||||
lightbox.showArrows = !!lg.controls
|
||||
}
|
||||
if (lightbox.showDownload === undefined && lg.download !== undefined) {
|
||||
lightbox.showDownload = !!lg.download
|
||||
}
|
||||
if (lightbox.mobileArrows === undefined && mobile.controls !== undefined) {
|
||||
lightbox.mobileArrows = !!mobile.controls
|
||||
}
|
||||
console.log(
|
||||
'[IPP] The `lightGallery` config section is deprecated; relevant keys ' +
|
||||
'have been mapped to `ipp.lightbox.*`. See README for the current options.'
|
||||
)
|
||||
}
|
||||
|
||||
// Backward-compat shim: gallery-related keys that used to live directly on
|
||||
// `ipp` now live under `ipp.gallery`. Map legacy keys forward, only filling
|
||||
// in fields the user hasn't already set on the new path.
|
||||
{
|
||||
const ipp = (config.ipp || (config.ipp = {})) as Record<string, unknown>
|
||||
const galleryKeyMigrations: Array<[string, string]> = [
|
||||
['singleImageGallery', 'singleImage'],
|
||||
['singleItemAutoOpen', 'singleItemAutoOpen'],
|
||||
['showGalleryTitle', 'showTitle'],
|
||||
['showGalleryDescription', 'showDescription'],
|
||||
['groupGalleryByDate', 'groupByDate']
|
||||
]
|
||||
const legacyPresent = galleryKeyMigrations.some(([oldKey]) => ipp[oldKey] !== undefined)
|
||||
if (legacyPresent) {
|
||||
const gallery = (ipp.gallery || (ipp.gallery = {})) as Record<string, unknown>
|
||||
for (const [oldKey, newKey] of galleryKeyMigrations) {
|
||||
if (ipp[oldKey] !== undefined && gallery[newKey] === undefined) {
|
||||
gallery[newKey] = ipp[oldKey]
|
||||
}
|
||||
}
|
||||
console.log(
|
||||
'[IPP] Top-level gallery keys (singleImageGallery, singleItemAutoOpen, ' +
|
||||
'showGalleryTitle, showGalleryDescription, groupGalleryByDate) are ' +
|
||||
'deprecated; please move them under `ipp.gallery.*`. See README.'
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a configuration option fron config.json using dotted notation.
|
||||
*
|
||||
* @param path
|
||||
* @param [defaultOption] - Specify a default option to return if no configuation value is found
|
||||
*
|
||||
* @example
|
||||
* getConfigOption('ipp.gallery.singleImage')
|
||||
*/
|
||||
export const getConfigOption = (path: string, defaultOption?: unknown) => {
|
||||
const value = path.split('.').reduce((obj: { [key: string]: unknown }, key) => (obj || {})[key], config)
|
||||
if (value === undefined) {
|
||||
return defaultOption
|
||||
} else {
|
||||
return value
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Output a console.log message with timestamp
|
||||
*/
|
||||
export const log = (message: string) => console.log(dayjs().format() + ' ' + message)
|
||||
|
||||
/**
|
||||
* Force a value to be a string
|
||||
*/
|
||||
export function toString (value: unknown) {
|
||||
return typeof value === 'string' ? value : ''
|
||||
}
|
||||
|
||||
/**
|
||||
* Add response headers from config.json
|
||||
*/
|
||||
export function addResponseHeaders (res: Response) {
|
||||
Object.entries(getConfigOption('ipp.responseHeaders', {}) as { [key: string]: string })
|
||||
.forEach(([header, value]) => {
|
||||
res.set(header, value)
|
||||
})
|
||||
}
|
||||
|
||||
export function canDownload (share: SharedLink) {
|
||||
const allowDownloadConfig = getConfigOption('ipp.allowDownloadAll', 0) as DownloadAll
|
||||
if (!allowDownloadConfig) {
|
||||
// Downloading is disabled in config.json
|
||||
return false
|
||||
} else if (allowDownloadConfig === DownloadAll.always) {
|
||||
// Always allowed to download in config.json
|
||||
return true
|
||||
} else {
|
||||
// Return Immich's setting for this shared link
|
||||
return !!share.allowDownload
|
||||
}
|
||||
}
|
||||
|
||||
export function escapeHtml (str: string): string {
|
||||
return str
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''')
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
import {
|
||||
getPreviewImageSize,
|
||||
getVideoContentType,
|
||||
photoUrl,
|
||||
requiresOriginal,
|
||||
videoUrl
|
||||
} from '../immich'
|
||||
import { Response } from 'express-serve-static-core'
|
||||
import { AssetType, ImageSize, SharedLink } from '../types'
|
||||
import { getConfigOption } from '../config/access'
|
||||
import { canDownload, title } from '../share'
|
||||
import { toString } from '../utils/text'
|
||||
import { h } from 'preact'
|
||||
import { renderPage } from '../view/render'
|
||||
import { Gallery, GalleryItem, GalleryProps } from '../view/gallery'
|
||||
import { getFilename } from './filename'
|
||||
import { pickExif } from './exif'
|
||||
|
||||
/**
|
||||
* Render a gallery page for a given SharedLink.
|
||||
*
|
||||
* @param res - ExpressJS Response
|
||||
* @param share - Immich `shared-link` containing the assets to show in the gallery
|
||||
* @param [openItem] - Immediately open the lightbox to the Nth item when the gallery loads
|
||||
*/
|
||||
export async function gallery (res: Response, share: SharedLink, openItem?: number) {
|
||||
// publicBaseUrl is used for the og:image, which requires a fully qualified URL.
|
||||
// You can specify this in your docker-compose file via the PUBLIC_BASE_URL env var.
|
||||
const publicBaseUrl = process.env.PUBLIC_BASE_URL || (res.req.protocol + '://' + res.req.headers.host)
|
||||
|
||||
// Date grouping needs chronological order; sort newest-first when enabled
|
||||
// (overrides any album.order the upstream applied).
|
||||
const groupByDate = !!getConfigOption('ipp.gallery.groupByDate', false)
|
||||
if (groupByDate) {
|
||||
share.assets.sort((a, b) => (b.fileCreatedAt || '').localeCompare(a.fileCreatedAt || ''))
|
||||
}
|
||||
|
||||
// Metadata display flags. Read once here and forwarded to the client via
|
||||
// `metadataConfig` in the init JSON.
|
||||
const descriptionInCaption = !!getConfigOption('ipp.showMetadata.description.caption', false)
|
||||
const descriptionInSidebar = !!getConfigOption('ipp.showMetadata.description.sidebar', false)
|
||||
const exifGroupEnabled = !!getConfigOption('ipp.showMetadata.exif.enabled', false)
|
||||
const locationGroupEnabled = !!getConfigOption('ipp.showMetadata.location.enabled', false)
|
||||
const sidebarHasContent = descriptionInSidebar || exifGroupEnabled || locationGroupEnabled
|
||||
|
||||
// Build structured items in parallel
|
||||
const items: GalleryItem[] = await Promise.all(share.assets.map(async (asset): Promise<GalleryItem> => {
|
||||
let videoData: string | undefined
|
||||
if (asset.type === AssetType.video) {
|
||||
videoData = JSON.stringify({
|
||||
source: [
|
||||
{
|
||||
src: videoUrl(share.key, asset.id),
|
||||
type: await getVideoContentType(asset)
|
||||
}
|
||||
],
|
||||
attributes: {
|
||||
playsinline: 'playsinline',
|
||||
controls: 'controls'
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Compute the filename so the client-side `<a download="...">` attribute
|
||||
// matches the bytes the server will return. Without this, a HEIC
|
||||
// original served as a preview JPEG would download as "photo.heic"
|
||||
// with JPEG bytes inside.
|
||||
const downloadUrl = photoUrl(share.key, asset.id, ImageSize.original)
|
||||
const downloadServedSize = (getConfigOption('ipp.downloadOriginalPhoto', true) || requiresOriginal(asset))
|
||||
? ImageSize.original
|
||||
: ImageSize.preview
|
||||
|
||||
const thumbnailUrl = photoUrl(share.key, asset.id, ImageSize.thumbnail)
|
||||
const previewUrl = photoUrl(share.key, asset.id, getPreviewImageSize(asset))
|
||||
// Plain text; the client uses textContent so no escaping needed here.
|
||||
// Description is included if EITHER surface (caption or sidebar) wants it.
|
||||
const descriptionEnabled = descriptionInCaption || descriptionInSidebar
|
||||
const itemDescription = descriptionEnabled && typeof asset?.exifInfo?.description === 'string'
|
||||
? asset.exifInfo.description
|
||||
: ''
|
||||
|
||||
let width = asset.exifInfo?.exifImageWidth
|
||||
let height = asset.exifInfo?.exifImageHeight
|
||||
const orientation = asset.exifInfo?.orientation
|
||||
if (orientation && ['5', '6', '7', '8'].includes(orientation) && width && height) {
|
||||
[width, height] = [height, width]
|
||||
}
|
||||
|
||||
return {
|
||||
id: asset.id,
|
||||
type: asset.type,
|
||||
previewUrl,
|
||||
thumbnailUrl,
|
||||
downloadUrl,
|
||||
videoData,
|
||||
description: itemDescription || undefined,
|
||||
downloadFilename: getFilename(asset, downloadServedSize),
|
||||
width,
|
||||
height,
|
||||
thumbhash: asset.thumbhash,
|
||||
fileCreatedAt: asset.fileCreatedAt,
|
||||
exif: pickExif(asset)
|
||||
}
|
||||
}))
|
||||
|
||||
const downloadAllowed = canDownload(share)
|
||||
// Prefer the album's owner-chosen cover for og:image; fall back to first
|
||||
// item if the cover asset has been filtered out (e.g. trashed).
|
||||
const coverId = share.album?.albumThumbnailAssetId
|
||||
const ogImageItem = (coverId && items.find(i => i.id === coverId)) || items[0]
|
||||
// Guard against an operator setting ipp.lightbox.options to a non-object;
|
||||
// a string would otherwise spread character-by-character into PhotoSwipe.
|
||||
const rawLightboxOptions = getConfigOption('ipp.lightbox.options', {})
|
||||
const lightboxOptions: Record<string, unknown> = (rawLightboxOptions && typeof rawLightboxOptions === 'object' && !Array.isArray(rawLightboxOptions))
|
||||
? rawLightboxOptions as Record<string, unknown>
|
||||
: {}
|
||||
const props: GalleryProps = {
|
||||
items,
|
||||
title: title(share),
|
||||
description: getConfigOption('ipp.gallery.showDescription', false) ? description(share) : '',
|
||||
publicBaseUrl: toString(publicBaseUrl),
|
||||
path: '/share/' + share.key,
|
||||
showDownload: downloadAllowed,
|
||||
showTitle: !!getConfigOption('ipp.gallery.showTitle', true),
|
||||
openItem,
|
||||
ogImageItem,
|
||||
lightboxConfig: {
|
||||
// Show download button only if downloading is allowed AND configured.
|
||||
showDownload: downloadAllowed && !!getConfigOption('ipp.lightbox.showDownload', true),
|
||||
showArrows: !!getConfigOption('ipp.lightbox.showArrows', true),
|
||||
mobileArrows: !!getConfigOption('ipp.lightbox.mobileArrows', false),
|
||||
options: lightboxOptions
|
||||
},
|
||||
metadataConfig: {
|
||||
descriptionInCaption,
|
||||
descriptionInSidebar,
|
||||
sidebarHasContent
|
||||
},
|
||||
groupByDate
|
||||
}
|
||||
|
||||
res.send(renderPage(h(Gallery, props)))
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the Immich shared link description (album-level, not per-asset).
|
||||
*/
|
||||
function description (share: SharedLink) {
|
||||
return share?.album?.description || ''
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import { Asset } from '../types'
|
||||
import { GalleryExif } from '../shared/types'
|
||||
import { getConfigOption } from '../config/access'
|
||||
|
||||
/**
|
||||
* Build the per-asset metadata sub-object included in the gallery JSON.
|
||||
* Reads `ipp.showMetadata.exif.*` and `ipp.showMetadata.location.*` config:
|
||||
* each group has a master `enabled` toggle, and within each group the
|
||||
* per-field flags default to `true`. A field appears in the output only
|
||||
* when both the group is enabled AND the field's own flag is true.
|
||||
*
|
||||
* Returns `undefined` when neither group is enabled, or when no fields
|
||||
* survive gating (so the client knows there's no metadata to show).
|
||||
*
|
||||
* The server never sends Immich values that the operator hasn't opted in
|
||||
* to via config; the client just renders what's present.
|
||||
*/
|
||||
export function pickExif (asset: Asset): GalleryExif | undefined {
|
||||
const exifInfo = asset?.exifInfo
|
||||
if (!exifInfo) return undefined
|
||||
|
||||
const exifEnabled = !!getConfigOption('ipp.showMetadata.exif.enabled', false)
|
||||
const locationEnabled = !!getConfigOption('ipp.showMetadata.location.enabled', false)
|
||||
if (!exifEnabled && !locationEnabled) return undefined
|
||||
|
||||
const out: GalleryExif = {}
|
||||
|
||||
if (exifEnabled) {
|
||||
if (allow('exif.dateTimeOriginal') && exifInfo.dateTimeOriginal) {
|
||||
out.dateTimeOriginal = exifInfo.dateTimeOriginal
|
||||
}
|
||||
if (allow('exif.fileName') && asset.originalFileName) {
|
||||
out.fileName = asset.originalFileName
|
||||
}
|
||||
if (allow('exif.dimensions') && exifInfo.exifImageWidth && exifInfo.exifImageHeight) {
|
||||
out.width = exifInfo.exifImageWidth
|
||||
out.height = exifInfo.exifImageHeight
|
||||
}
|
||||
if (allow('exif.fileSize') && exifInfo.fileSizeInByte) {
|
||||
out.fileSizeInByte = exifInfo.fileSizeInByte
|
||||
}
|
||||
if (allow('exif.make') && exifInfo.make) out.make = exifInfo.make
|
||||
if (allow('exif.model') && exifInfo.model) out.model = exifInfo.model
|
||||
if (allow('exif.lensModel') && exifInfo.lensModel) out.lensModel = exifInfo.lensModel
|
||||
if (allow('exif.exposureTime') && exifInfo.exposureTime) out.exposureTime = exifInfo.exposureTime
|
||||
if (allow('exif.iso') && exifInfo.iso) out.iso = exifInfo.iso
|
||||
if (allow('exif.fNumber') && exifInfo.fNumber) out.fNumber = exifInfo.fNumber
|
||||
if (allow('exif.focalLength') && exifInfo.focalLength) out.focalLength = exifInfo.focalLength
|
||||
}
|
||||
|
||||
if (locationEnabled) {
|
||||
if (allow('location.city') && exifInfo.city) out.city = exifInfo.city
|
||||
if (allow('location.state') && exifInfo.state) out.state = exifInfo.state
|
||||
if (allow('location.country') && exifInfo.country) out.country = exifInfo.country
|
||||
if (allow('location.gps') && exifInfo.latitude != null && exifInfo.longitude != null) {
|
||||
out.latitude = exifInfo.latitude
|
||||
out.longitude = exifInfo.longitude
|
||||
}
|
||||
}
|
||||
|
||||
return Object.keys(out).length ? out : undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-field gate. Defaults to `true` so that turning on a group exposes
|
||||
* every field unless the operator explicitly opts out of one.
|
||||
*/
|
||||
function allow (field: string): boolean {
|
||||
return !!getConfigOption(`ipp.showMetadata.${field}`, true)
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import { Asset, ImageSize } from '../types'
|
||||
import { getConfigOption } from '../config/access'
|
||||
import { sanitize } from '../utils/sanitize'
|
||||
|
||||
/**
|
||||
* Map an Immich asset MIME type to a file extension (including the dot).
|
||||
* Returns '' for unknown types; obscure RAW types fall through to '' so
|
||||
* the original filename (which usually has the correct extension) is
|
||||
* preserved by `withMimeExtension`.
|
||||
*/
|
||||
function mimeToExt (mime: string | undefined): string {
|
||||
if (!mime) return ''
|
||||
const map: Record<string, string> = {
|
||||
'image/jpeg': '.jpg',
|
||||
'image/png': '.png',
|
||||
'image/webp': '.webp',
|
||||
'image/gif': '.gif',
|
||||
'image/heic': '.heic',
|
||||
'image/heif': '.heif',
|
||||
'image/avif': '.avif',
|
||||
'image/tiff': '.tiff',
|
||||
'image/svg+xml': '.svg',
|
||||
'image/x-adobe-dng': '.dng',
|
||||
'video/mp4': '.mp4',
|
||||
'video/quicktime': '.mov',
|
||||
'video/webm': '.webm',
|
||||
'video/x-msvideo': '.avi',
|
||||
'video/x-matroska': '.mkv'
|
||||
}
|
||||
return map[mime] || ''
|
||||
}
|
||||
|
||||
/**
|
||||
* Append the MIME-derived extension to `filename` if it isn't already
|
||||
* present (case-insensitive). Returns the filename unchanged when the
|
||||
* MIME isn't in our map. Aliases that share a MIME type (`.jpg`/`.jpeg`,
|
||||
* `.tif`/`.tiff`) are accepted as already-present so we don't produce
|
||||
* `IMG.jpeg.jpg` for an `image/jpeg` asset.
|
||||
*/
|
||||
function withMimeExtension (filename: string, mime: string | undefined): string {
|
||||
const ext = mimeToExt(mime)
|
||||
if (!ext) return filename
|
||||
const aliases: Record<string, string[]> = {
|
||||
'.jpg': ['.jpg', '.jpeg'],
|
||||
'.tiff': ['.tif', '.tiff']
|
||||
}
|
||||
const acceptable = aliases[ext] ?? [ext]
|
||||
const lower = filename.toLowerCase()
|
||||
return acceptable.some(a => lower.endsWith(a)) ? filename : filename + ext
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a filename for the downloaded asset based on the configuration option chosen.
|
||||
*
|
||||
* The extension reflects what bytes the user will receive, not what the
|
||||
* original was - when Immich downgrades an image-original to preview (see
|
||||
* resolveImageEndpoint), the served bytes are JPEG even if the original is
|
||||
* HEIC/DNG/RAW, and the filename must match the bytes.
|
||||
*
|
||||
* @param asset
|
||||
* @param [servedSize] - what size Immich will actually serve. Defaults to
|
||||
* ImageSize.original (the bytes match the original asset).
|
||||
*/
|
||||
export function getFilename (asset: Asset, servedSize: ImageSize = ImageSize.original): string {
|
||||
let servedMime: string | undefined
|
||||
if (servedSize === ImageSize.original) {
|
||||
servedMime = asset.originalMimeType
|
||||
} else if (servedSize === ImageSize.thumbnail) {
|
||||
servedMime = 'image/webp'
|
||||
} else {
|
||||
servedMime = 'image/jpeg'
|
||||
}
|
||||
|
||||
switch (getConfigOption('ipp.downloadedFilename')) {
|
||||
case 1:
|
||||
// Immich's ID number for this asset
|
||||
return withMimeExtension(asset.id, servedMime)
|
||||
case 2:
|
||||
// A sanitised version of the ID number
|
||||
return withMimeExtension('img_' + asset.id.slice(0, 8), servedMime)
|
||||
default: {
|
||||
// By default, use the asset's original filename
|
||||
const cleanName = asset.originalFileName ? sanitize(asset.originalFileName) : ''
|
||||
if (!cleanName) return withMimeExtension(asset.id, servedMime)
|
||||
const stem = servedSize === ImageSize.original
|
||||
? cleanName
|
||||
: cleanName.replace(/\.[a-zA-Z0-9]{2,5}$/, '')
|
||||
return withMimeExtension(stem, servedMime)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { Response } from 'express-serve-static-core'
|
||||
import { getConfigOption } from './config/access'
|
||||
|
||||
/**
|
||||
* Apply the response headers configured under `ipp.responseHeaders` to the
|
||||
* given Response. Used by route handlers to attach the default Cache-Control
|
||||
* and CORS values from `config.json`.
|
||||
*/
|
||||
export function addResponseHeaders (res: Response): void {
|
||||
Object.entries(getConfigOption('ipp.responseHeaders', {}) as { [key: string]: string })
|
||||
.forEach(([header, value]) => {
|
||||
res.set(header, value)
|
||||
})
|
||||
}
|
||||
+118
-110
@@ -10,12 +10,17 @@ import {
|
||||
SharedLinkResult
|
||||
} from './types'
|
||||
import dayjs from 'dayjs'
|
||||
import { addResponseHeaders, canDownload, getConfigOption, log } from './functions'
|
||||
import render from './render'
|
||||
import { getConfigOption } from './config/access'
|
||||
import { addResponseHeaders } from './http'
|
||||
import { canDownload } from './share'
|
||||
import { log } from './utils/log'
|
||||
import { assetBuffer } from './stream/asset'
|
||||
import { downloadAll } from './stream/download'
|
||||
import { gallery } from './gallery/builder'
|
||||
import { Response } from 'express-serve-static-core'
|
||||
import { h } from 'preact'
|
||||
import { renderPage } from './views/_render'
|
||||
import { Password } from './views/password'
|
||||
import { renderPage } from './view/render'
|
||||
import { Password } from './view/password'
|
||||
import { respondToInvalidRequest } from './invalidRequestHandler'
|
||||
import { encrypt } from './encrypt'
|
||||
|
||||
@@ -53,21 +58,20 @@ const shareCacheMax = 100
|
||||
requests reuse a single login round-trip. Keying by password is load-bearing
|
||||
for security: a request without the correct password produces a different
|
||||
cache key (often empty) and falls through to a fresh login that Immich will
|
||||
reject — IPP never serves cached tokens to unauthenticated visitors.
|
||||
reject - IPP never serves cached tokens to unauthenticated visitors.
|
||||
*/
|
||||
type TokenCacheEntry = { promise: Promise<string | null>; expiresAt: number }
|
||||
const tokenCache = new Map<string, TokenCacheEntry>()
|
||||
const tokenCacheTtlMs = 120_000
|
||||
const tokenCacheMax = 100
|
||||
|
||||
class Immich {
|
||||
/**
|
||||
/**
|
||||
* Make a request to Immich API. We're not using the SDK to limit
|
||||
* the possible attack surface of this app.
|
||||
*/
|
||||
async request (endpoint: string, init?: RequestInit) {
|
||||
export async function request (endpoint: string, init?: RequestInit) {
|
||||
try {
|
||||
const res = await fetch(this.apiUrl() + endpoint, init)
|
||||
const res = await fetch(apiUrl() + endpoint, init)
|
||||
if (res.status === 200) {
|
||||
const contentType = res.headers.get('Content-Type') || ''
|
||||
if (contentType.includes('application/json')) {
|
||||
@@ -81,15 +85,15 @@ class Immich {
|
||||
}
|
||||
} catch (e) {
|
||||
log('Unable to reach Immich on ' + process.env.IMMICH_URL)
|
||||
log(`From the server IPP is running on, see if you can curl to ${this.apiUrl()}/server/ping and receive a JSON result.`)
|
||||
}
|
||||
log(`From the server IPP is running on, see if you can curl to ${apiUrl()}/server/ping and receive a JSON result.`)
|
||||
}
|
||||
}
|
||||
|
||||
apiUrl () {
|
||||
export function apiUrl () {
|
||||
return (process.env.IMMICH_URL || '').replace(/\/*$/, '') + '/api'
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
/**
|
||||
* Handle an incoming request for a shared link `key`. This is the main function which
|
||||
* communicates with Immich and returns the output back to the visitor.
|
||||
*
|
||||
@@ -99,17 +103,17 @@ class Immich {
|
||||
* 401 - the visitor provided a password but it was invalid.
|
||||
* 404 - any other failed request. Check console.log for details.
|
||||
*/
|
||||
async handleShareRequest (request: IncomingShareRequest, res: Response) {
|
||||
export async function handleShareRequest (req: IncomingShareRequest, res: Response) {
|
||||
addResponseHeaders(res)
|
||||
|
||||
// Check that the key is a valid format
|
||||
if (!immich.isKey(request.key)) {
|
||||
respondToInvalidRequest(res, 404, 'Wrong key format ' + request.key)
|
||||
if (!isKey(req.key)) {
|
||||
respondToInvalidRequest(res, 404, 'Wrong key format ' + req.key)
|
||||
return
|
||||
}
|
||||
|
||||
// Get information about the shared link via Immich API
|
||||
const sharedLinkRes = await immich.getShareByKey(request.key, request.password, request.keyType || KeyType.key)
|
||||
const sharedLinkRes = await getShareByKey(req.key, req.password, req.keyType || KeyType.key)
|
||||
if (!sharedLinkRes.valid) {
|
||||
// This isn't a valid request - check the console for more information
|
||||
respondToInvalidRequest(res, 404, 'Invalid request')
|
||||
@@ -117,15 +121,15 @@ class Immich {
|
||||
}
|
||||
|
||||
// A password is required, but the visitor-provided one doesn't match
|
||||
if (sharedLinkRes.passwordRequired && request.password) {
|
||||
log('Invalid password for key ' + request.key)
|
||||
if (sharedLinkRes.passwordRequired && req.password) {
|
||||
log('Invalid password for key ' + req.key)
|
||||
res.status(401)
|
||||
// Delete the cookie-session data, so that it doesn't keep saying "Invalid password"
|
||||
if (request.req?.session) delete request.req.session[request.key]
|
||||
if (req.req?.session) delete req.req.session[req.key]
|
||||
}
|
||||
|
||||
// Don't cache password-protected albums
|
||||
if (sharedLinkRes.passwordRequired || request.password) {
|
||||
if (sharedLinkRes.passwordRequired || req.password) {
|
||||
res.header('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate')
|
||||
res.header('Pragma', 'no-cache')
|
||||
res.header('Expires', '0')
|
||||
@@ -133,55 +137,55 @@ class Immich {
|
||||
|
||||
// Password required - show the visitor the password page
|
||||
if (sharedLinkRes.passwordRequired) {
|
||||
// `request.key` is already sanitised at this point, but it never hurts to be explicit
|
||||
const shareKey = request.key.replace(/[^\w-]/g, '')
|
||||
// `req.key` is already sanitised at this point, but it never hurts to be explicit
|
||||
const shareKey = req.key.replace(/[^\w-]/g, '')
|
||||
res.send(renderPage(h(Password, {
|
||||
shareKey,
|
||||
notifyInvalidPassword: !!request.password
|
||||
notifyInvalidPassword: !!req.password
|
||||
})))
|
||||
return
|
||||
}
|
||||
|
||||
if (!sharedLinkRes.link) {
|
||||
respondToInvalidRequest(res, 404, 'Unknown error with key ' + request.key)
|
||||
respondToInvalidRequest(res, 404, 'Unknown error with key ' + req.key)
|
||||
return
|
||||
}
|
||||
const link = sharedLinkRes.link
|
||||
|
||||
// If this was a password-protected slug link, we need to also store session information for the ID-based key
|
||||
if (request.password && request.req.session && !request.req.session[link.key]) {
|
||||
request.req.session[link.key] = encrypt(JSON.stringify({
|
||||
password: request.password,
|
||||
if (req.password && req.req.session && !req.req.session[link.key]) {
|
||||
req.req.session[link.key] = encrypt(JSON.stringify({
|
||||
password: req.password,
|
||||
expires: dayjs().add(1, 'hour').format()
|
||||
}))
|
||||
}
|
||||
|
||||
// Everything is ok - output the shared link data
|
||||
|
||||
if (request.mode === 'download' && canDownload(link)) {
|
||||
if (req.mode === 'download' && canDownload(link)) {
|
||||
// Download all assets as a zip file
|
||||
await render.downloadAll(res, link)
|
||||
await downloadAll(res, link)
|
||||
} else if (link.assets.length === 1) {
|
||||
// This is an individual item (not a gallery)
|
||||
log('Serving link ' + request.key)
|
||||
log('Serving link ' + req.key)
|
||||
const asset = link.assets[0]
|
||||
if (asset.type === AssetType.image && !getConfigOption('ipp.gallery.singleImage') && !request.password) {
|
||||
if (asset.type === AssetType.image && !getConfigOption('ipp.gallery.singleImage') && !req.password) {
|
||||
// For photos, output the image directly unless configured to show a gallery,
|
||||
// or unless it's a password-protected link
|
||||
await render.assetBuffer(request, res, link.assets[0], ImageSize.preview)
|
||||
await assetBuffer(req, res, link.assets[0], ImageSize.preview)
|
||||
} else {
|
||||
// Show a gallery page
|
||||
const openItem = getConfigOption('ipp.gallery.singleItemAutoOpen', true) ? 1 : 0
|
||||
await render.gallery(res, link, openItem)
|
||||
await gallery(res, link, openItem)
|
||||
}
|
||||
} else {
|
||||
// Multiple images - render as a gallery
|
||||
log('Serving link ' + request.key)
|
||||
await render.gallery(res, link)
|
||||
}
|
||||
log('Serving link ' + req.key)
|
||||
await gallery(res, link)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
/**
|
||||
* Query Immich for the SharedLink metadata for a given key, with a short
|
||||
* in-process cache + in-flight de-duplication. See the cache notes at the
|
||||
* top of this file for the why.
|
||||
@@ -191,7 +195,7 @@ class Immich {
|
||||
* Negative results (`valid: false`) and rejections are dropped from the
|
||||
* cache immediately so a transient Immich blip doesn't poison the cache.
|
||||
*/
|
||||
async getShareByKey (key: string, password?: string, keyType: KeyType = KeyType.key): Promise<SharedLinkResult> {
|
||||
export async function getShareByKey (key: string, password?: string, keyType: KeyType = KeyType.key): Promise<SharedLinkResult> {
|
||||
const cacheKey = `${keyType}:${key}:${password ?? ''}`
|
||||
const now = Date.now()
|
||||
const cached = shareCache.get(cacheKey)
|
||||
@@ -202,7 +206,7 @@ class Immich {
|
||||
return cached.promise
|
||||
}
|
||||
|
||||
const promise = this.fetchShareByKey(key, password, keyType)
|
||||
const promise = fetchShareByKey(key, password, keyType)
|
||||
shareCache.set(cacheKey, {
|
||||
promise,
|
||||
expiresAt: now + shareCacheTtlMs
|
||||
@@ -216,20 +220,20 @@ class Immich {
|
||||
() => { shareCache.delete(cacheKey) }
|
||||
)
|
||||
return promise
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
/**
|
||||
* Underlying fetch for getShareByKey. Always hits Immich; the public
|
||||
* getShareByKey wraps this with the cache. Don't call this directly from
|
||||
* outside the class — going through getShareByKey is what gives us the
|
||||
* outside the module - going through getShareByKey is what gives us the
|
||||
* coalescing on cold misses.
|
||||
*/
|
||||
private async fetchShareByKey (key: string, password?: string, keyType: KeyType = KeyType.key): Promise<SharedLinkResult> {
|
||||
async function fetchShareByKey (key: string, password?: string, keyType: KeyType = KeyType.key): Promise<SharedLinkResult> {
|
||||
let link
|
||||
const url = this.buildUrl(this.apiUrl() + '/shared-links/me', {
|
||||
const url = buildUrl(apiUrl() + '/shared-links/me', {
|
||||
[keyType]: key
|
||||
})
|
||||
const headers = await this.authHeaders(keyType, key, password)
|
||||
const headers = await authHeaders(keyType, key, password)
|
||||
const res = await fetch(url, { headers })
|
||||
if ((res.headers.get('Content-Type') || '').toLowerCase().includes('application/json')) {
|
||||
const jsonBody = await res.json()
|
||||
@@ -242,7 +246,7 @@ class Immich {
|
||||
// For an album, we need to make a second request to Immich to populate
|
||||
// the array of assets
|
||||
if (link.type === AlbumType.album) {
|
||||
const albumRes = await fetch(this.buildUrl(this.apiUrl() + '/albums/' + link?.album?.id, {
|
||||
const albumRes = await fetch(buildUrl(apiUrl() + '/albums/' + link?.album?.id, {
|
||||
[keyType]: key
|
||||
}), { headers })
|
||||
const album = await albumRes.json() as Album
|
||||
@@ -305,7 +309,7 @@ class Immich {
|
||||
try {
|
||||
console.log(res.headers.get('Content-Type'))
|
||||
console.log((await res.text()).slice(0, 500))
|
||||
log('Unexpected response from Immich API at ' + this.apiUrl())
|
||||
log('Unexpected response from Immich API at ' + apiUrl())
|
||||
log('Please make sure the IPP container is able to reach this path.')
|
||||
} catch (e) {
|
||||
console.log(e)
|
||||
@@ -314,39 +318,39 @@ class Immich {
|
||||
return {
|
||||
valid: false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
/**
|
||||
* Get the content-type of a video, for the lightbox <video> element
|
||||
*/
|
||||
async getVideoContentType (asset: Asset) {
|
||||
const headers = await this.authHeaders(asset.keyType, asset.key, asset.password)
|
||||
const data = await this.request(this.buildUrl('/assets/' + encodeURIComponent(asset.id) + '/video/playback', {
|
||||
export async function getVideoContentType (asset: Asset) {
|
||||
const headers = await authHeaders(asset.keyType, asset.key, asset.password)
|
||||
const data = await request(buildUrl('/assets/' + encodeURIComponent(asset.id) + '/video/playback', {
|
||||
[asset.keyType]: asset.key
|
||||
}), { headers })
|
||||
return data.headers.get('Content-Type')
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
/**
|
||||
* Build the `Cookie` header that authenticates to Immich for a
|
||||
* password-protected share. Returns `{}` (no Cookie header) when the share
|
||||
* has no password or login failed; in those cases Immich will respond 401
|
||||
* for protected resources, which the caller handles as "password required".
|
||||
*/
|
||||
async authHeaders (keyType: KeyType, key: string, password?: string): Promise<Record<string, string>> {
|
||||
export async function authHeaders (keyType: KeyType, key: string, password?: string): Promise<Record<string, string>> {
|
||||
if (!password) return {}
|
||||
const token = await this.getSharedLinkToken(key, password, keyType)
|
||||
const token = await getSharedLinkToken(key, password, keyType)
|
||||
return token ? { Cookie: `immich_shared_link_token=${token}` } : {}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
/**
|
||||
* Cached login: fetch an `immich_shared_link_token` for the given password,
|
||||
* or return null on failure. The cache is per (keyType, key, password) so
|
||||
* that a request without the correct password can't reuse another visitor's
|
||||
* authenticated session. See `tokenCache` doc-comment for the security
|
||||
* argument.
|
||||
*/
|
||||
private async getSharedLinkToken (key: string, password: string, keyType: KeyType): Promise<string | null> {
|
||||
async function getSharedLinkToken (key: string, password: string, keyType: KeyType): Promise<string | null> {
|
||||
const cacheKey = `${keyType}:${key}:${password}`
|
||||
const now = Date.now()
|
||||
const cached = tokenCache.get(cacheKey)
|
||||
@@ -355,7 +359,7 @@ class Immich {
|
||||
tokenCache.set(cacheKey, cached)
|
||||
return cached.promise
|
||||
}
|
||||
const promise = this.sharedLinkLogin(key, password, keyType)
|
||||
const promise = sharedLinkLogin(key, password, keyType)
|
||||
tokenCache.set(cacheKey, {
|
||||
promise,
|
||||
expiresAt: now + tokenCacheTtlMs
|
||||
@@ -369,15 +373,14 @@ class Immich {
|
||||
() => { tokenCache.delete(cacheKey) }
|
||||
)
|
||||
return promise
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
/**
|
||||
* `POST /shared-links/login`. Replaces the deprecated `?password=...` query
|
||||
* param.
|
||||
* Returns the cookie value on success, null on any failure.
|
||||
* param. Returns the cookie value on success, null on any failure.
|
||||
*/
|
||||
private async sharedLinkLogin (key: string, password: string, keyType: KeyType): Promise<string | null> {
|
||||
const url = this.buildUrl(this.apiUrl() + '/shared-links/login', { [keyType]: key })
|
||||
async function sharedLinkLogin (key: string, password: string, keyType: KeyType): Promise<string | null> {
|
||||
const url = buildUrl(apiUrl() + '/shared-links/login', { [keyType]: key })
|
||||
try {
|
||||
const res = await fetch(url, {
|
||||
method: 'POST',
|
||||
@@ -391,12 +394,12 @@ class Immich {
|
||||
} catch (e) {
|
||||
return null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build safely-encoded URL string
|
||||
/**
|
||||
* Build safely-encoded URL string.
|
||||
*/
|
||||
buildUrl (baseUrl: string, params: { [key: string]: string | undefined } = {}) {
|
||||
export function buildUrl (baseUrl: string, params: { [key: string]: string | undefined } = {}) {
|
||||
// Remove empty properties
|
||||
params = Object.fromEntries(Object.entries(params).filter(([_, value]) => !!value))
|
||||
let query = ''
|
||||
@@ -407,9 +410,9 @@ class Immich {
|
||||
})).toString()
|
||||
}
|
||||
return baseUrl + query
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
/**
|
||||
* Whether this asset must be served from `/original` to remain useful, bypassing
|
||||
* the `ipp.downloadOriginalPhoto` downgrade.
|
||||
*
|
||||
@@ -417,14 +420,14 @@ class Immich {
|
||||
* video, so the downgrade would replace a video file with a still image.
|
||||
* - Animated images (currently just GIF): Immich's preview is a static JPEG,
|
||||
* so the downgrade silently strips the animation. APNG/animated-WebP aren't
|
||||
* listed because Immich doesn't expose a distinct MIME type for them — they
|
||||
* listed because Immich doesn't expose a distinct MIME type for them - they
|
||||
* share `image/png` / `image/webp` with their static counterparts.
|
||||
*
|
||||
* Used by both the display path (lightbox preview URL) and the download path
|
||||
* (single-asset download + zip), so the lightbox shows the same bytes the
|
||||
* user gets when they hit "download".
|
||||
*/
|
||||
requiresOriginal (asset: Asset): boolean {
|
||||
export function requiresOriginal (asset: Asset): boolean {
|
||||
if (asset.type === AssetType.video) {
|
||||
return true
|
||||
} else if (asset.originalMimeType?.startsWith('video/')) {
|
||||
@@ -433,66 +436,71 @@ class Immich {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the correct preview size, depending on the image MIME type
|
||||
/**
|
||||
* Return the correct preview size, depending on the image MIME type.
|
||||
* For animated formats, use the original file rather than the preview so
|
||||
* animation is preserved (Immich's preview is a static JPEG frame).
|
||||
*/
|
||||
getPreviewImageSize (asset: Asset) {
|
||||
// For animated formats, use the original file rather than the preview so
|
||||
// animation is preserved (Immich's preview is a static JPEG frame).
|
||||
return this.requiresOriginal(asset) ? ImageSize.original : ImageSize.preview
|
||||
}
|
||||
export function getPreviewImageSize (asset: Asset) {
|
||||
return requiresOriginal(asset) ? ImageSize.original : ImageSize.preview
|
||||
}
|
||||
|
||||
/**
|
||||
/**
|
||||
* Return the image data URL for a photo
|
||||
*/
|
||||
photoUrl (key: string, id: string, size?: ImageSize) {
|
||||
export function photoUrl (key: string, id: string, size?: ImageSize) {
|
||||
const path = ['photo', key, id]
|
||||
if (size) path.push(size)
|
||||
return this.buildUrl('/share/' + path.join('/'))
|
||||
}
|
||||
return buildUrl('/share/' + path.join('/'))
|
||||
}
|
||||
|
||||
/**
|
||||
/**
|
||||
* Return the video data URL for a video
|
||||
*/
|
||||
videoUrl (key: string, id: string) {
|
||||
return this.buildUrl(`/share/video/${key}/${id}`)
|
||||
}
|
||||
export function videoUrl (key: string, id: string) {
|
||||
return buildUrl(`/share/video/${key}/${id}`)
|
||||
}
|
||||
|
||||
/**
|
||||
/**
|
||||
* Check if a provided ID matches the Immich ID format
|
||||
*/
|
||||
isId (id: string) {
|
||||
export function isId (id: string) {
|
||||
return !!id.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
/**
|
||||
* Check if a provided key matches the Immich shared-link key format.
|
||||
* It appears that the key is always 67 chars long, but since I don't know that this
|
||||
* will always be the case, I've left it open-ended.
|
||||
*/
|
||||
isKey (key: string) {
|
||||
export function isKey (key: string) {
|
||||
return !!key.match(/^[\w-]+$/)
|
||||
}
|
||||
}
|
||||
|
||||
async accessible () {
|
||||
return !!(await immich.request('/server/ping'))
|
||||
}
|
||||
/**
|
||||
* Reachability ping for the `/share/healthcheck` route.
|
||||
*/
|
||||
export async function accessible () {
|
||||
return !!(await request('/server/ping'))
|
||||
}
|
||||
|
||||
validateImageSize (size: unknown) {
|
||||
/**
|
||||
* Coerce an unknown `size` parameter from a URL into a valid ImageSize,
|
||||
* defaulting to preview when the input is missing or unrecognised.
|
||||
*/
|
||||
export function validateImageSize (size: unknown) {
|
||||
if (!size || !Object.values(ImageSize).includes(size as ImageSize)) {
|
||||
return ImageSize.preview
|
||||
} else {
|
||||
return size as ImageSize
|
||||
}
|
||||
}
|
||||
|
||||
getKeyTypeFromShare (shareType: string) {
|
||||
return shareType === 's' ? KeyType.slug : KeyType.key
|
||||
}
|
||||
}
|
||||
|
||||
const immich = new Immich()
|
||||
|
||||
export default immich
|
||||
/**
|
||||
* Map the URL path prefix (`share` or `s`) to the corresponding `KeyType`.
|
||||
*/
|
||||
export function getKeyTypeFromShare (shareType: string) {
|
||||
return shareType === 's' ? KeyType.slug : KeyType.key
|
||||
}
|
||||
|
||||
+31
-16
@@ -1,19 +1,32 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import 'dotenv/config'
|
||||
import express from 'express'
|
||||
import cookieSession from 'cookie-session'
|
||||
import immich from './immich'
|
||||
import {
|
||||
accessible,
|
||||
getKeyTypeFromShare,
|
||||
getShareByKey,
|
||||
handleShareRequest,
|
||||
isId,
|
||||
isKey
|
||||
} from './immich'
|
||||
import crypto from 'crypto'
|
||||
import render from './render'
|
||||
import { assetBuffer } from './stream/asset'
|
||||
import { downloadAssets } from './stream/download'
|
||||
import dayjs from 'dayjs'
|
||||
import { NextFunction, Request, Response } from 'express-serve-static-core'
|
||||
import { Asset, AssetType, ImageSize, KeyType } from './types'
|
||||
import { addResponseHeaders, canDownload, getConfigOption, toString } from './functions'
|
||||
import { getConfigOption } from './config/access'
|
||||
import { loadConfig } from './config/loader'
|
||||
import { addResponseHeaders } from './http'
|
||||
import { canDownload } from './share'
|
||||
import { toString } from './utils/text'
|
||||
import { decrypt, encrypt } from './encrypt'
|
||||
import { respondToInvalidRequest } from './invalidRequestHandler'
|
||||
import { h } from 'preact'
|
||||
import { renderPage } from './views/_render'
|
||||
import { Home } from './views/home'
|
||||
import { renderPage } from './view/render'
|
||||
import { Home } from './view/home'
|
||||
|
||||
// Extend the Request type with a `password` property
|
||||
declare module 'express-serve-static-core' {
|
||||
@@ -22,7 +35,9 @@ declare module 'express-serve-static-core' {
|
||||
}
|
||||
}
|
||||
|
||||
require('dotenv').config()
|
||||
// Read config.json (or the inline CONFIG env var) and apply backward-compat
|
||||
// migrations. Must run before any code that calls getConfigOption.
|
||||
loadConfig()
|
||||
|
||||
const app = express()
|
||||
app.use(cookieSession({
|
||||
@@ -67,7 +82,7 @@ const decodeCookie = (req: Request, _res: Response, next: NextFunction) => {
|
||||
* The path matches for /share/healthcheck, and also the legacy /healthcheck
|
||||
*/
|
||||
app.get(/^(|\/share)\/healthcheck$/, async (_req, res) => {
|
||||
if (await immich.accessible()) {
|
||||
if (await accessible()) {
|
||||
res.send('ok')
|
||||
} else {
|
||||
res.status(503).send()
|
||||
@@ -78,13 +93,13 @@ app.get(/^(|\/share)\/healthcheck$/, async (_req, res) => {
|
||||
* [ROUTE] This is the main URL that someone would visit if they are opening a shared link
|
||||
*/
|
||||
app.get('/:shareType(share|s)/:key/:mode(download)?', decodeCookie, async (req, res) => {
|
||||
const keyType = immich.getKeyTypeFromShare(req.params.shareType)
|
||||
const keyType = getKeyTypeFromShare(req.params.shareType)
|
||||
|
||||
if (keyType === KeyType.slug && !getConfigOption('ipp.allowSlugLinks', true)) {
|
||||
// Slug type links are not allowed
|
||||
respondToInvalidRequest(res, 404, 'Slug links are disabled in config.json')
|
||||
} else {
|
||||
await immich.handleShareRequest({
|
||||
await handleShareRequest({
|
||||
req,
|
||||
key: req.params.key,
|
||||
keyType,
|
||||
@@ -120,7 +135,7 @@ app.post('/share/unlock', async (req, res) => {
|
||||
* outside the share.
|
||||
*/
|
||||
app.post('/:shareType(share|s)/:key/download', decodeCookie, async (req, res) => {
|
||||
const keyType = immich.getKeyTypeFromShare(req.params.shareType)
|
||||
const keyType = getKeyTypeFromShare(req.params.shareType)
|
||||
let requestedIds: unknown
|
||||
try {
|
||||
requestedIds = JSON.parse(String(req.body?.assets ?? '[]'))
|
||||
@@ -133,7 +148,7 @@ app.post('/:shareType(share|s)/:key/download', decodeCookie, async (req, res) =>
|
||||
return
|
||||
}
|
||||
|
||||
const result = await immich.getShareByKey(req.params.key, req.password, keyType)
|
||||
const result = await getShareByKey(req.params.key, req.password, keyType)
|
||||
if (!result?.valid || !result.link) {
|
||||
respondToInvalidRequest(res, 404, 'Invalid share link')
|
||||
return
|
||||
@@ -154,7 +169,7 @@ app.post('/:shareType(share|s)/:key/download', decodeCookie, async (req, res) =>
|
||||
return
|
||||
}
|
||||
|
||||
await render.downloadAssets(res, result.link, validAssets)
|
||||
await downloadAssets(res, result.link, validAssets)
|
||||
})
|
||||
|
||||
/*
|
||||
@@ -174,7 +189,7 @@ app.get('/share/:type(photo|video)/:key/:id/:size?', decodeCookie, async (req, r
|
||||
addResponseHeaders(res)
|
||||
|
||||
// Check for valid key and ID
|
||||
if (!immich.isKey(req.params.key) || !immich.isId(req.params.id)) {
|
||||
if (!isKey(req.params.key) || !isId(req.params.id)) {
|
||||
respondToInvalidRequest(res, 404, 'Invalid key or ID for ' + req.path)
|
||||
return
|
||||
}
|
||||
@@ -188,7 +203,7 @@ app.get('/share/:type(photo|video)/:key/:id/:size?', decodeCookie, async (req, r
|
||||
// Validate share link and check password before serving assets
|
||||
// This prevents direct URL access from bypassing password protection
|
||||
// The password is provided from the encrypted session cookie (if set)
|
||||
const share = await immich.getShareByKey(req.params.key, req.password)
|
||||
const share = await getShareByKey(req.params.key, req.password)
|
||||
if (!share) {
|
||||
respondToInvalidRequest(res, 404, 'Invalid share link')
|
||||
return
|
||||
@@ -219,7 +234,7 @@ app.get('/share/:type(photo|video)/:key/:id/:size?', decodeCookie, async (req, r
|
||||
key: req.params.key,
|
||||
range: req.headers.range || ''
|
||||
}
|
||||
render.assetBuffer(request, res, asset, req.params.size).then()
|
||||
assetBuffer(request, res, asset, req.params.size).then()
|
||||
})
|
||||
|
||||
/*
|
||||
@@ -264,7 +279,7 @@ process.on('SIGTERM', () => {
|
||||
})
|
||||
|
||||
// Start the ExpressJS server
|
||||
const port = process.env.IPP_PORT || 3000
|
||||
const port = Number(process.env.IPP_PORT) || 3000
|
||||
const server = app.listen(port, () => {
|
||||
console.log(dayjs().format() + ' Server started on port ' + port)
|
||||
})
|
||||
|
||||
@@ -5,7 +5,8 @@ through a Docker volume mount.
|
||||
*/
|
||||
|
||||
import { Response } from 'express-serve-static-core'
|
||||
import { getConfigOption, log } from './functions'
|
||||
import { getConfigOption } from './config/access'
|
||||
import { log } from './utils/log'
|
||||
|
||||
export function respondToInvalidRequest (res: Response, defaultResponse: number | string | null, logMessage = '') {
|
||||
let method = getConfigOption('ipp.customInvalidResponse', false)
|
||||
|
||||
@@ -1,544 +0,0 @@
|
||||
import immich from './immich'
|
||||
import { Response } from 'express-serve-static-core'
|
||||
import { Asset, AssetType, ImageSize, IncomingShareRequest, KeyType, SharedLink } from './types'
|
||||
import { canDownload, escapeHtml, getConfigOption, log, toString } from './functions'
|
||||
import archiver from 'archiver'
|
||||
import { respondToInvalidRequest } from './invalidRequestHandler'
|
||||
import { sanitize } from './includes/sanitize'
|
||||
import { h } from 'preact'
|
||||
import { renderPage } from './views/_render'
|
||||
import { Gallery, GalleryItem, GalleryProps } from './views/gallery'
|
||||
import { Readable, Transform } from 'stream'
|
||||
import { pipeline } from 'stream/promises'
|
||||
import { promises as fs, createWriteStream } from 'fs'
|
||||
import { tmpdir } from 'os'
|
||||
import { join } from 'path'
|
||||
|
||||
/**
|
||||
* A pass-through Transform that destroys itself if no data flows through for
|
||||
* `idleMs`. The timer is set when the transform is created and reset on every
|
||||
* chunk, so a slow-but-steady download (large video over a slow link) keeps
|
||||
* going, while a genuinely stalled connection still fails fast.
|
||||
*/
|
||||
function createIdleTimeoutStream (idleMs: number): Transform {
|
||||
let timer: NodeJS.Timeout | undefined
|
||||
const transform: Transform = new Transform({
|
||||
transform (chunk, _, cb) {
|
||||
if (timer) clearTimeout(timer)
|
||||
timer = setTimeout(() => transform.destroy(new Error(`No data received for ${idleMs}ms`)), idleMs)
|
||||
cb(null, chunk)
|
||||
},
|
||||
flush (cb) {
|
||||
if (timer) clearTimeout(timer)
|
||||
cb()
|
||||
}
|
||||
})
|
||||
// Arm the timer immediately so a response that returns headers but never
|
||||
// sends a body also times out.
|
||||
timer = setTimeout(() => transform.destroy(new Error(`No data received for ${idleMs}ms`)), idleMs)
|
||||
return transform
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a function that runs at most `limit` async tasks concurrently.
|
||||
* Tasks queue when the limit is reached and resume in FIFO order.
|
||||
*/
|
||||
function createLimiter (limit: number) {
|
||||
let active = 0
|
||||
const queue: Array<() => void> = []
|
||||
return async function run<T> (fn: () => Promise<T>): Promise<T> {
|
||||
if (active >= limit) {
|
||||
await new Promise<void>(resolve => queue.push(resolve))
|
||||
}
|
||||
active++
|
||||
try {
|
||||
return await fn()
|
||||
} finally {
|
||||
active--
|
||||
const next = queue.shift()
|
||||
if (next) next()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class Render {
|
||||
/**
|
||||
* Stream an asset from Immich back to the client.
|
||||
*
|
||||
* Errors from Immich are always reported to the client as 404 — see
|
||||
* invalidRequestHandler. Upstream status codes are never surfaced. Trashed
|
||||
* or locked assets are handled implicitly: Immich's own endpoints refuse
|
||||
* to serve them, and the upstream failure surfaces as a client 404.
|
||||
*/
|
||||
async assetBuffer (req: IncomingShareRequest, res: Response, asset: Asset, size?: ImageSize | string) {
|
||||
const headerList = ['content-type', 'content-length', 'last-modified', 'etag']
|
||||
const fetchHeaders: Record<string, string> = {}
|
||||
let subpath: string
|
||||
let sizeQueryParam: string | undefined
|
||||
let attachment = false
|
||||
let servedSize: ImageSize | undefined
|
||||
|
||||
if (asset.type === AssetType.video) {
|
||||
subpath = '/video/playback'
|
||||
res.setHeader('accept-ranges', 'bytes')
|
||||
// Only chunk when the client sent a Range header. A browser <video>
|
||||
// element does, so playback still streams in 2.5 MB chunks. Clients
|
||||
// that don't (wget, right-click "Save As", link unfurlers) get the
|
||||
// full file with 200 OK; otherwise they'd save a truncated 2.5 MB
|
||||
// partial response as the whole video.
|
||||
if (req.range) {
|
||||
const range = req.range.replace(/bytes=/, '').split('-')
|
||||
const start = parseInt(range[0], 10) || 0
|
||||
const end = parseInt(range[1], 10) || start + 2499999
|
||||
fetchHeaders.range = `bytes=${start}-${end}`
|
||||
headerList.push('cache-control', 'content-range')
|
||||
res.status(206) // Partial Content
|
||||
}
|
||||
} else {
|
||||
const endpoint = this.resolveImageEndpoint(immich.validateImageSize(size), asset)
|
||||
subpath = endpoint.subpath
|
||||
sizeQueryParam = endpoint.sizeQueryParam
|
||||
attachment = endpoint.attachment
|
||||
servedSize = endpoint.servedSize
|
||||
}
|
||||
|
||||
const url = immich.buildUrl(immich.apiUrl() + '/assets/' + encodeURIComponent(asset.id) + subpath, {
|
||||
[asset.keyType || 'key']: asset.key,
|
||||
size: sizeQueryParam
|
||||
})
|
||||
const authHeaders = await immich.authHeaders(asset.keyType || KeyType.key, asset.key, asset.password)
|
||||
const data = await fetch(url, { headers: { ...fetchHeaders, ...authHeaders } })
|
||||
|
||||
if (data.status < 200 || data.status >= 300) {
|
||||
let immichMessage = ''
|
||||
try {
|
||||
const json = await data.json()
|
||||
if (json.message) immichMessage = '\nResponse from Immich: ' + json.message
|
||||
} catch (e) { }
|
||||
respondToInvalidRequest(res, 404, 'Failed response from Immich for asset ' + asset.id + ' on this URL:\n' + url + immichMessage)
|
||||
return
|
||||
}
|
||||
|
||||
if (attachment && asset.originalFileName) {
|
||||
const filename = encodeURI(this.getFilename(asset, servedSize))
|
||||
res.setHeader('Content-Disposition', `attachment; filename*=UTF-8''${filename}`)
|
||||
}
|
||||
headerList.forEach(header => {
|
||||
const value = data.headers.get(header)
|
||||
if (value) res.setHeader(header, value)
|
||||
})
|
||||
await data.body?.pipeTo(
|
||||
new WritableStream({
|
||||
write (chunk) { res.write(chunk) }
|
||||
})
|
||||
)
|
||||
res.end()
|
||||
}
|
||||
|
||||
/**
|
||||
* Map an ImageSize to the Immich endpoint that serves it.
|
||||
*
|
||||
* Policy: when `ipp.downloadOriginalPhoto` is off, requests for the original
|
||||
* image are silently downgraded to preview — the operator has opted out of
|
||||
* serving full-resolution files. (The original may also be a RAW/HEIC file
|
||||
* the browser can't render.)
|
||||
*
|
||||
* The downgrade is bypassed for assets where `immich.requiresOriginal` is
|
||||
* true (videos, animated images), because for those formats the preview is
|
||||
* an entirely different artifact (still poster / static JPEG) rather than a
|
||||
* lower-res version of the same content.
|
||||
*
|
||||
* `servedSize` reflects what Immich will actually return after the downgrade,
|
||||
* which may differ from the requested `size`. Callers use it to derive a
|
||||
* filename whose extension matches the bytes (see getFilename).
|
||||
*/
|
||||
private resolveImageEndpoint (size: ImageSize, asset: Asset): { subpath: string; sizeQueryParam?: string; attachment: boolean; servedSize: ImageSize } {
|
||||
const allowOriginal = getConfigOption('ipp.downloadOriginalPhoto', true) || immich.requiresOriginal(asset)
|
||||
if (size === ImageSize.original && allowOriginal) {
|
||||
return { subpath: '/original', attachment: true, servedSize: ImageSize.original }
|
||||
}
|
||||
if (size === ImageSize.thumbnail) {
|
||||
return { subpath: '/thumbnail', attachment: false, servedSize: ImageSize.thumbnail }
|
||||
}
|
||||
// preview, or original downgraded because downloadOriginalPhoto is off
|
||||
return { subpath: '/thumbnail', sizeQueryParam: 'preview', attachment: false, servedSize: ImageSize.preview }
|
||||
}
|
||||
|
||||
/**
|
||||
* Map an Immich asset MIME type to a file extension (including the dot).
|
||||
* Returns '' for unknown types; obscure RAW types fall through to '' so
|
||||
* the original filename (which usually has the correct extension) is
|
||||
* preserved by `withMimeExtension`.
|
||||
*/
|
||||
private mimeToExt (mime: string | undefined): string {
|
||||
if (!mime) return ''
|
||||
const map: Record<string, string> = {
|
||||
'image/jpeg': '.jpg',
|
||||
'image/png': '.png',
|
||||
'image/webp': '.webp',
|
||||
'image/gif': '.gif',
|
||||
'image/heic': '.heic',
|
||||
'image/heif': '.heif',
|
||||
'image/avif': '.avif',
|
||||
'image/tiff': '.tiff',
|
||||
'image/svg+xml': '.svg',
|
||||
'image/x-adobe-dng': '.dng',
|
||||
'video/mp4': '.mp4',
|
||||
'video/quicktime': '.mov',
|
||||
'video/webm': '.webm',
|
||||
'video/x-msvideo': '.avi',
|
||||
'video/x-matroska': '.mkv'
|
||||
}
|
||||
return map[mime] || ''
|
||||
}
|
||||
|
||||
/**
|
||||
* Append the MIME-derived extension to `filename` if it isn't already
|
||||
* present (case-insensitive). Returns the filename unchanged when the
|
||||
* MIME isn't in our map. Aliases that share a MIME type (`.jpg`/`.jpeg`,
|
||||
* `.tif`/`.tiff`) are accepted as already-present so we don't produce
|
||||
* `IMG.jpeg.jpg` for an `image/jpeg` asset.
|
||||
*/
|
||||
private withMimeExtension (filename: string, mime: string | undefined): string {
|
||||
const ext = this.mimeToExt(mime)
|
||||
if (!ext) return filename
|
||||
const aliases: Record<string, string[]> = {
|
||||
'.jpg': ['.jpg', '.jpeg'],
|
||||
'.tiff': ['.tif', '.tiff']
|
||||
}
|
||||
const acceptable = aliases[ext] ?? [ext]
|
||||
const lower = filename.toLowerCase()
|
||||
return acceptable.some(a => lower.endsWith(a)) ? filename : filename + ext
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a gallery page for a given SharedLink.
|
||||
*
|
||||
* @param res - ExpressJS Response
|
||||
* @param share - Immich `shared-link` containing the assets to show in the gallery
|
||||
* @param [openItem] - Immediately open the lightbox to the Nth item when the gallery loads
|
||||
*/
|
||||
async gallery (res: Response, share: SharedLink, openItem?: number) {
|
||||
// publicBaseUrl is used for the og:image, which requires a fully qualified URL.
|
||||
// You can specify this in your docker-compose file via the PUBLIC_BASE_URL env var.
|
||||
const publicBaseUrl = process.env.PUBLIC_BASE_URL || (res.req.protocol + '://' + res.req.headers.host)
|
||||
|
||||
// Date grouping needs chronological order; sort newest-first when enabled
|
||||
// (overrides any album.order the upstream applied).
|
||||
const groupByDate = !!getConfigOption('ipp.gallery.groupByDate', false)
|
||||
if (groupByDate) {
|
||||
share.assets.sort((a, b) => (b.fileCreatedAt || '').localeCompare(a.fileCreatedAt || ''))
|
||||
}
|
||||
|
||||
// Build structured items in parallel
|
||||
const items: GalleryItem[] = await Promise.all(share.assets.map(async (asset): Promise<GalleryItem> => {
|
||||
let videoData: string | undefined
|
||||
if (asset.type === AssetType.video) {
|
||||
videoData = JSON.stringify({
|
||||
source: [
|
||||
{
|
||||
src: immich.videoUrl(share.key, asset.id),
|
||||
type: await immich.getVideoContentType(asset)
|
||||
}
|
||||
],
|
||||
attributes: {
|
||||
playsinline: 'playsinline',
|
||||
controls: 'controls'
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Compute the filename so the client-side `<a download="...">` attribute
|
||||
// matches the bytes the server will return. Without this, a HEIC
|
||||
// original served as a preview JPEG would download as "photo.heic"
|
||||
// with JPEG bytes inside.
|
||||
const downloadUrl = immich.photoUrl(share.key, asset.id, ImageSize.original)
|
||||
const downloadServedSize = (getConfigOption('ipp.downloadOriginalPhoto', true) || immich.requiresOriginal(asset))
|
||||
? ImageSize.original
|
||||
: ImageSize.preview
|
||||
|
||||
const thumbnailUrl = immich.photoUrl(share.key, asset.id, ImageSize.thumbnail)
|
||||
const previewUrl = immich.photoUrl(share.key, asset.id, immich.getPreviewImageSize(asset))
|
||||
const description = getConfigOption('ipp.showMetadata.description', false) && typeof asset?.exifInfo?.description === 'string'
|
||||
? escapeHtml(asset.exifInfo.description)
|
||||
: ''
|
||||
|
||||
let width = asset.exifInfo?.exifImageWidth
|
||||
let height = asset.exifInfo?.exifImageHeight
|
||||
const orientation = asset.exifInfo?.orientation
|
||||
if (orientation && ['5', '6', '7', '8'].includes(orientation) && width && height) {
|
||||
[width, height] = [height, width]
|
||||
}
|
||||
|
||||
return {
|
||||
id: asset.id,
|
||||
type: asset.type,
|
||||
previewUrl,
|
||||
thumbnailUrl,
|
||||
downloadUrl,
|
||||
videoData,
|
||||
description: description || undefined,
|
||||
downloadFilename: this.getFilename(asset, downloadServedSize),
|
||||
width,
|
||||
height,
|
||||
thumbhash: asset.thumbhash,
|
||||
fileCreatedAt: asset.fileCreatedAt
|
||||
}
|
||||
}))
|
||||
|
||||
const downloadAllowed = canDownload(share)
|
||||
// Prefer the album's owner-chosen cover for og:image; fall back to first
|
||||
// item if the cover asset has been filtered out (e.g. trashed).
|
||||
const coverId = share.album?.albumThumbnailAssetId
|
||||
const ogImageItem = (coverId && items.find(i => i.id === coverId)) || items[0]
|
||||
// Guard against an operator setting ipp.lightbox.options to a non-object;
|
||||
// a string would otherwise spread character-by-character into PhotoSwipe.
|
||||
const rawLightboxOptions = getConfigOption('ipp.lightbox.options', {})
|
||||
const lightboxOptions: Record<string, unknown> = (rawLightboxOptions && typeof rawLightboxOptions === 'object' && !Array.isArray(rawLightboxOptions))
|
||||
? rawLightboxOptions as Record<string, unknown>
|
||||
: {}
|
||||
const props: GalleryProps = {
|
||||
items,
|
||||
title: this.title(share),
|
||||
description: getConfigOption('ipp.gallery.showDescription', false) ? this.description(share) : '',
|
||||
publicBaseUrl: toString(publicBaseUrl),
|
||||
path: '/share/' + share.key,
|
||||
showDownload: downloadAllowed,
|
||||
showTitle: !!getConfigOption('ipp.gallery.showTitle', true),
|
||||
openItem,
|
||||
ogImageItem,
|
||||
lightboxConfig: {
|
||||
// Show download button only if downloading is allowed AND configured.
|
||||
showDownload: downloadAllowed && !!getConfigOption('ipp.lightbox.showDownload', true),
|
||||
showArrows: !!getConfigOption('ipp.lightbox.showArrows', true),
|
||||
mobileArrows: !!getConfigOption('ipp.lightbox.mobileArrows', false),
|
||||
options: lightboxOptions
|
||||
},
|
||||
groupByDate
|
||||
}
|
||||
|
||||
res.send(renderPage(h(Gallery, props)))
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempt to get a title from the link description or the album title
|
||||
*/
|
||||
title (share: SharedLink) {
|
||||
return share.description || share?.album?.albumName || 'Gallery'
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the Immich shared link description
|
||||
*/
|
||||
description (share: SharedLink) {
|
||||
return share?.album?.description || ''
|
||||
}
|
||||
|
||||
/**
|
||||
* Download all assets in a share as a zip file.
|
||||
*/
|
||||
async downloadAll (res: Response, share: SharedLink) {
|
||||
await this.downloadAssets(res, share, share.assets)
|
||||
}
|
||||
|
||||
/**
|
||||
* Stream the given assets back as a zip file.
|
||||
*
|
||||
* Pattern adapted from Immich's own download service:
|
||||
* https://github.com/immich-app/immich/blob/main/server/src/services/download.service.ts
|
||||
*
|
||||
* Per asset, the upstream fetch is two phases:
|
||||
* 1. Get the response headers (retried up to 3 times with linear backoff,
|
||||
* bounded by a 20s header-receipt timeout).
|
||||
* 2. Stream the body to a temp file, guarded by an idle timeout that
|
||||
* resets on every chunk. A genuinely stalled connection fails fast; a
|
||||
* slow-but-steady transfer (large video over a slow link) completes.
|
||||
*
|
||||
* If any asset ultimately fails, the in-flight download is aborted mid-stream:
|
||||
* the archive is aborted, the HTTP response socket is destroyed, and the
|
||||
* failure is logged. We do this (rather than silently omitting the asset)
|
||||
* because by the time we know the asset failed we've already sent a 200
|
||||
* response to the client, so the only way to signal "your zip is incomplete"
|
||||
* is to terminate the response — leaving the user with a visibly broken/
|
||||
* truncated download instead of a zip that's quietly missing files.
|
||||
*/
|
||||
async downloadAssets (res: Response, share: SharedLink, assets: Asset[]) {
|
||||
res.setHeader('Content-Type', 'application/zip')
|
||||
let filename = (sanitize(this.title(share)) || 'photos') + '.zip'
|
||||
filename = encodeURI(filename)
|
||||
res.setHeader('Content-Disposition', `attachment; filename*=UTF-8''${filename}`)
|
||||
// Hint to intermediate proxies (Nginx, etc.) not to buffer this response.
|
||||
res.setHeader('X-Accel-Buffering', 'no')
|
||||
// STORE rather than deflate — photos and videos are already compressed,
|
||||
// this is the same as Immich does
|
||||
const archive = archiver('zip', { store: true })
|
||||
archive.pipe(res)
|
||||
|
||||
const maxAttempts = 3
|
||||
const headerTimeoutMs = 20_000
|
||||
const idleTimeoutMs = 20_000
|
||||
const concurrency = Math.max(1, getConfigOption('ipp.downloadFromImmichConcurrencyLimit', 8) as number)
|
||||
|
||||
const stagingDir = await fs.mkdtemp(join(tmpdir(), 'ipp-zip-'))
|
||||
let aborted = false
|
||||
|
||||
type StagedAsset = { tempfile: string, asset: Asset, endpoint: ReturnType<Render['resolveImageEndpoint']> }
|
||||
type Failure = { asset: Asset, url: string, status?: number, error?: unknown }
|
||||
|
||||
const stageOne = async (asset: Asset, index: number): Promise<StagedAsset | { failure: Failure } | null> => {
|
||||
// Skip work if another stage has already triggered an abort.
|
||||
if (aborted) return null
|
||||
|
||||
const endpoint = this.resolveImageEndpoint(ImageSize.original, asset)
|
||||
const url = immich.buildUrl(immich.apiUrl() + '/assets/' + encodeURIComponent(asset.id) + endpoint.subpath, {
|
||||
[asset.keyType || 'key']: asset.key,
|
||||
size: endpoint.sizeQueryParam
|
||||
})
|
||||
const authHeaders = await immich.authHeaders(asset.keyType || KeyType.key, asset.key, asset.password)
|
||||
|
||||
// Phase 1: get response headers, retrying on transient failure.
|
||||
// We use AbortController + a clearable timer rather than
|
||||
// `AbortSignal.timeout` because the signal we pass to fetch stays bound
|
||||
// to the response body — if the timeout fires after headers arrive but
|
||||
// while the body is still streaming, the body read errors out. The
|
||||
// header timer is cleared as soon as we have a response; from there the
|
||||
// idle-timeout transform downstream guards against stalled bodies.
|
||||
let response: globalThis.Response | undefined
|
||||
let lastStatus: number | undefined
|
||||
let lastError: unknown
|
||||
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
||||
if (aborted) return null
|
||||
const controller = new AbortController()
|
||||
const headerTimer = setTimeout(() => controller.abort(new Error(`No response headers within ${headerTimeoutMs}ms`)), headerTimeoutMs)
|
||||
try {
|
||||
const data = await fetch(url, { signal: controller.signal, headers: authHeaders })
|
||||
clearTimeout(headerTimer)
|
||||
if (data.ok) {
|
||||
response = data
|
||||
break
|
||||
}
|
||||
await data.body?.cancel()
|
||||
lastStatus = data.status
|
||||
lastError = undefined
|
||||
} catch (e) {
|
||||
clearTimeout(headerTimer)
|
||||
lastError = e
|
||||
lastStatus = undefined
|
||||
}
|
||||
if (attempt < maxAttempts) {
|
||||
const reason = lastStatus !== undefined
|
||||
? `HTTP ${lastStatus}`
|
||||
: (lastError instanceof Error ? lastError.message : String(lastError))
|
||||
log(`Retrying asset ${asset.id} (attempt ${attempt + 1}/${maxAttempts}) after ${reason}`)
|
||||
// Linear backoff between attempts to avoid hammering a struggling server.
|
||||
await new Promise(resolve => setTimeout(resolve, 500 * attempt))
|
||||
}
|
||||
}
|
||||
|
||||
if (!response || !response.body) {
|
||||
return { failure: { asset, url, status: lastStatus, error: lastError } }
|
||||
}
|
||||
|
||||
// Phase 2: stream body to a temp file, guarded by an idle timeout.
|
||||
// Use the array index in the path so we never collide on duplicate IDs.
|
||||
const tempfile = join(stagingDir, `${index}-${asset.id}`)
|
||||
// @types/node 16 predates the typed Readable.fromWeb signature; the
|
||||
// runtime (Node 22+ via the Dockerfile's node:lts-alpine) has it.
|
||||
const body = (Readable as unknown as { fromWeb: (s: unknown) => Readable }).fromWeb(response.body)
|
||||
try {
|
||||
await pipeline(body, createIdleTimeoutStream(idleTimeoutMs), createWriteStream(tempfile))
|
||||
} catch (e) {
|
||||
return { failure: { asset, url, error: e } }
|
||||
}
|
||||
|
||||
return { tempfile, asset, endpoint }
|
||||
}
|
||||
|
||||
try {
|
||||
const limit = createLimiter(concurrency)
|
||||
// Kick off every stage at once; the limiter caps how many run concurrently.
|
||||
// The map preserves input order so the consumer below archives in order.
|
||||
const stages = assets.map((asset, index) => limit(() => stageOne(asset, index)))
|
||||
|
||||
let failure: Failure | null = null
|
||||
for (const stage of stages) {
|
||||
const result = await stage
|
||||
if (result === null) break // aborted by an earlier stage
|
||||
if ('failure' in result) {
|
||||
aborted = true
|
||||
failure = result.failure
|
||||
break
|
||||
}
|
||||
// archive.file queues the entry; archiver lazily opens and reads it.
|
||||
archive.file(result.tempfile, { name: this.getFilename(result.asset, result.endpoint.servedSize) })
|
||||
}
|
||||
|
||||
// After abort, wait for any in-flight stages to settle before we delete
|
||||
// the staging dir. stageOne never rejects (errors become failure objects),
|
||||
// so a plain Promise.all is safe.
|
||||
if (aborted) await Promise.all(stages)
|
||||
|
||||
if (failure) {
|
||||
const f = failure as Failure
|
||||
const detail = f.status !== undefined
|
||||
? `HTTP ${f.status}`
|
||||
: (f.error instanceof Error ? f.error.message : String(f.error))
|
||||
log(`Aborting zip download for share ${share.key}: failed to fetch asset ${f.asset.id} from ${f.url} (${detail})`)
|
||||
archive.abort()
|
||||
res.destroy()
|
||||
return
|
||||
}
|
||||
|
||||
// finalize() resolves when archiver has finished writing the zip output,
|
||||
// which means every queued tempfile has been read. Safe to delete after.
|
||||
await archive.finalize()
|
||||
} finally {
|
||||
await fs.rm(stagingDir, { recursive: true, force: true }).catch(() => { /* best effort */ })
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a filename for the downloaded asset based on the configuration option chosen.
|
||||
*
|
||||
* The extension reflects what bytes the user will receive, not what the
|
||||
* original was — when Immich downgrades an image-original to preview (see
|
||||
* resolveImageEndpoint), the served bytes are JPEG even if the original is
|
||||
* HEIC/DNG/RAW, and the filename must match the bytes.
|
||||
*
|
||||
* @param asset
|
||||
* @param [servedSize] - what size Immich will actually serve. Defaults to
|
||||
* ImageSize.original (the bytes match the original asset).
|
||||
*/
|
||||
getFilename (asset: Asset, servedSize: ImageSize = ImageSize.original): string {
|
||||
let servedMime: string | undefined
|
||||
if (servedSize === ImageSize.original) {
|
||||
servedMime = asset.originalMimeType
|
||||
} else if (servedSize === ImageSize.thumbnail) {
|
||||
servedMime = 'image/webp'
|
||||
} else {
|
||||
servedMime = 'image/jpeg'
|
||||
}
|
||||
|
||||
switch (getConfigOption('ipp.downloadedFilename')) {
|
||||
case 1:
|
||||
// Immich's ID number for this asset
|
||||
return this.withMimeExtension(asset.id, servedMime)
|
||||
case 2:
|
||||
// A sanitised version of the ID number
|
||||
return this.withMimeExtension('img_' + asset.id.slice(0, 8), servedMime)
|
||||
default: {
|
||||
// By default, use the asset's original filename
|
||||
const cleanName = asset.originalFileName ? sanitize(asset.originalFileName) : ''
|
||||
if (!cleanName) return this.withMimeExtension(asset.id, servedMime)
|
||||
const stem = servedSize === ImageSize.original
|
||||
? cleanName
|
||||
: cleanName.replace(/\.[a-zA-Z0-9]{2,5}$/, '')
|
||||
return this.withMimeExtension(stem, servedMime)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const render = new Render()
|
||||
|
||||
export default render
|
||||
@@ -0,0 +1,31 @@
|
||||
import { DownloadAll, SharedLink } from './types'
|
||||
import { getConfigOption } from './config/access'
|
||||
|
||||
/**
|
||||
* Display title for a shared link. Prefers the user-set link description,
|
||||
* falls back to the album name (for album shares), or a generic placeholder.
|
||||
* Used by the gallery view-model and as the zip filename in the download
|
||||
* pipeline.
|
||||
*/
|
||||
export function title (share: SharedLink): string {
|
||||
return share.description || share?.album?.albumName || 'Gallery'
|
||||
}
|
||||
|
||||
/**
|
||||
* Decide whether the given shared link is downloadable. The `ipp.allowDownloadAll`
|
||||
* config controls the policy: disabled, follow the per-share Immich setting,
|
||||
* or always allowed.
|
||||
*/
|
||||
export function canDownload (share: SharedLink): boolean {
|
||||
const allowDownloadConfig = getConfigOption('ipp.allowDownloadAll', 0) as DownloadAll
|
||||
if (!allowDownloadConfig) {
|
||||
// Downloading is disabled in config.json
|
||||
return false
|
||||
} else if (allowDownloadConfig === DownloadAll.always) {
|
||||
// Always allowed to download in config.json
|
||||
return true
|
||||
} else {
|
||||
// Return Immich's setting for this shared link
|
||||
return !!share.allowDownload
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
/**
|
||||
* Types shared between the server (Preact SSR) and the client (gallery).
|
||||
* Only put a type here if it crosses the server/client boundary - i.e. it
|
||||
* describes data the server serialises into the gallery's init JSON block.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Per-asset EXIF / location metadata shown in the info sidebar. Each field
|
||||
* is optional - the server only includes a field if both the group is
|
||||
* enabled (`ipp.showMetadata.exif.enabled` or `.location.enabled`) and the
|
||||
* per-field flag is true. Strings are plain text (the client uses
|
||||
* `textContent`, not `innerHTML`).
|
||||
*/
|
||||
export interface GalleryExif {
|
||||
dateTimeOriginal?: string // ISO date string; client formats with Intl.DateTimeFormat
|
||||
fileName?: string
|
||||
width?: number
|
||||
height?: number
|
||||
fileSizeInByte?: number // raw bytes; client formats for display
|
||||
make?: string
|
||||
model?: string
|
||||
lensModel?: string
|
||||
exposureTime?: string
|
||||
iso?: number
|
||||
fNumber?: number
|
||||
focalLength?: number
|
||||
city?: string
|
||||
state?: string
|
||||
country?: string
|
||||
latitude?: number
|
||||
longitude?: number
|
||||
}
|
||||
|
||||
export interface GalleryItem {
|
||||
id: string
|
||||
type: 'IMAGE' | 'VIDEO'
|
||||
previewUrl: string
|
||||
thumbnailUrl: string
|
||||
downloadUrl?: string
|
||||
// Pre-stringified JSON describing the video source (used to build a <video>
|
||||
// element for video slides in the PhotoSwipe lightbox)
|
||||
videoData?: string
|
||||
// Plain-text caption shown below the image in the lightbox and at the top
|
||||
// of the info sidebar. Rendered with `textContent` on the client.
|
||||
description?: string
|
||||
downloadFilename: string
|
||||
// Display dimensions after EXIF orientation correction; needed for the
|
||||
// pre-computed justified-rows layout that virtualization depends on.
|
||||
width?: number
|
||||
height?: number
|
||||
// Base64-encoded thumbhash for an optional blur placeholder behind each tile
|
||||
thumbhash?: string
|
||||
// ISO date string from Immich; used to group tiles by month when enabled.
|
||||
fileCreatedAt?: string
|
||||
// Per-field gated EXIF / location metadata for the sidebar (see GalleryExif).
|
||||
exif?: GalleryExif
|
||||
}
|
||||
|
||||
export interface LightboxConfig {
|
||||
showArrows: boolean
|
||||
showDownload: boolean
|
||||
mobileArrows: boolean
|
||||
options?: Record<string, unknown>
|
||||
}
|
||||
|
||||
/**
|
||||
* Metadata-rendering decisions made server-side and forwarded to the client.
|
||||
* Whether to render description in each surface, and whether the sidebar
|
||||
* has any content the operator wants surfaced (when false, the client skips
|
||||
* registering the sidebar + its toolbar toggle entirely).
|
||||
*/
|
||||
export interface MetadataConfig {
|
||||
descriptionInCaption: boolean
|
||||
descriptionInSidebar: boolean
|
||||
sidebarHasContent: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Shape of the JSON init block embedded in `gallery.tsx` and consumed by
|
||||
* `client/init.ts`. The server writes it via `JSON.stringify`; the client
|
||||
* reads it via `readInitParams()`.
|
||||
*/
|
||||
export interface InitParams {
|
||||
items?: GalleryItem[]
|
||||
openItem?: number
|
||||
lightboxConfig?: LightboxConfig
|
||||
metadataConfig?: MetadataConfig
|
||||
groupByDate?: boolean
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
import {
|
||||
apiUrl,
|
||||
authHeaders,
|
||||
buildUrl,
|
||||
requiresOriginal,
|
||||
validateImageSize
|
||||
} from '../immich'
|
||||
import { Response } from 'express-serve-static-core'
|
||||
import { Asset, AssetType, ImageSize, IncomingShareRequest, KeyType } from '../types'
|
||||
import { getConfigOption } from '../config/access'
|
||||
import { respondToInvalidRequest } from '../invalidRequestHandler'
|
||||
import { getFilename } from '../gallery/filename'
|
||||
|
||||
export interface ImageEndpoint {
|
||||
subpath: string
|
||||
sizeQueryParam?: string
|
||||
attachment: boolean
|
||||
servedSize: ImageSize
|
||||
}
|
||||
|
||||
/**
|
||||
* Stream an asset from Immich back to the client.
|
||||
*
|
||||
* Errors from Immich are always reported to the client as 404 - see
|
||||
* invalidRequestHandler. Upstream status codes are never surfaced. Trashed
|
||||
* or locked assets are handled implicitly: Immich's own endpoints refuse
|
||||
* to serve them, and the upstream failure surfaces as a client 404.
|
||||
*/
|
||||
export async function assetBuffer (req: IncomingShareRequest, res: Response, asset: Asset, size?: ImageSize | string) {
|
||||
const headerList = ['content-type', 'content-length', 'last-modified', 'etag']
|
||||
const fetchHeaders: Record<string, string> = {}
|
||||
let subpath: string
|
||||
let sizeQueryParam: string | undefined
|
||||
let attachment = false
|
||||
let servedSize: ImageSize | undefined
|
||||
|
||||
if (asset.type === AssetType.video) {
|
||||
subpath = '/video/playback'
|
||||
res.setHeader('accept-ranges', 'bytes')
|
||||
// Only chunk when the client sent a Range header. A browser <video>
|
||||
// element does, so playback still streams in 2.5 MB chunks. Clients
|
||||
// that don't (wget, right-click "Save As", link unfurlers) get the
|
||||
// full file with 200 OK; otherwise they'd save a truncated 2.5 MB
|
||||
// partial response as the whole video.
|
||||
if (req.range) {
|
||||
const range = req.range.replace(/bytes=/, '').split('-')
|
||||
const start = parseInt(range[0], 10) || 0
|
||||
const end = parseInt(range[1], 10) || start + 2499999
|
||||
fetchHeaders.range = `bytes=${start}-${end}`
|
||||
headerList.push('cache-control', 'content-range')
|
||||
res.status(206) // Partial Content
|
||||
}
|
||||
} else {
|
||||
const endpoint = resolveImageEndpoint(validateImageSize(size), asset)
|
||||
subpath = endpoint.subpath
|
||||
sizeQueryParam = endpoint.sizeQueryParam
|
||||
attachment = endpoint.attachment
|
||||
servedSize = endpoint.servedSize
|
||||
}
|
||||
|
||||
const url = buildUrl(apiUrl() + '/assets/' + encodeURIComponent(asset.id) + subpath, {
|
||||
[asset.keyType || 'key']: asset.key,
|
||||
size: sizeQueryParam
|
||||
})
|
||||
const reqHeaders = await authHeaders(asset.keyType || KeyType.key, asset.key, asset.password)
|
||||
const data = await fetch(url, { headers: { ...fetchHeaders, ...reqHeaders } })
|
||||
|
||||
if (data.status < 200 || data.status >= 300) {
|
||||
let immichMessage = ''
|
||||
try {
|
||||
const json = await data.json()
|
||||
if (json.message) immichMessage = '\nResponse from Immich: ' + json.message
|
||||
} catch (e) { }
|
||||
respondToInvalidRequest(res, 404, 'Failed response from Immich for asset ' + asset.id + ' on this URL:\n' + url + immichMessage)
|
||||
return
|
||||
}
|
||||
|
||||
if (attachment && asset.originalFileName) {
|
||||
const filename = encodeURI(getFilename(asset, servedSize))
|
||||
res.setHeader('Content-Disposition', `attachment; filename*=UTF-8''${filename}`)
|
||||
}
|
||||
headerList.forEach(header => {
|
||||
const value = data.headers.get(header)
|
||||
if (value) res.setHeader(header, value)
|
||||
})
|
||||
await data.body?.pipeTo(
|
||||
new WritableStream({
|
||||
write (chunk) { res.write(chunk) }
|
||||
})
|
||||
)
|
||||
res.end()
|
||||
}
|
||||
|
||||
/**
|
||||
* Map an ImageSize to the Immich endpoint that serves it.
|
||||
*
|
||||
* Policy: when `ipp.downloadOriginalPhoto` is off, requests for the original
|
||||
* image are silently downgraded to preview - the operator has opted out of
|
||||
* serving full-resolution files. (The original may also be a RAW/HEIC file
|
||||
* the browser can't render.)
|
||||
*
|
||||
* The downgrade is bypassed for assets where `requiresOriginal` is true
|
||||
* (videos, animated images), because for those formats the preview is an
|
||||
* entirely different artifact (still poster / static JPEG) rather than a
|
||||
* lower-res version of the same content.
|
||||
*
|
||||
* `servedSize` reflects what Immich will actually return after the downgrade,
|
||||
* which may differ from the requested `size`. Callers use it to derive a
|
||||
* filename whose extension matches the bytes (see getFilename).
|
||||
*/
|
||||
export function resolveImageEndpoint (size: ImageSize, asset: Asset): ImageEndpoint {
|
||||
const allowOriginal = getConfigOption('ipp.downloadOriginalPhoto', true) || requiresOriginal(asset)
|
||||
if (size === ImageSize.original && allowOriginal) {
|
||||
return { subpath: '/original', attachment: true, servedSize: ImageSize.original }
|
||||
}
|
||||
if (size === ImageSize.thumbnail) {
|
||||
return { subpath: '/thumbnail', attachment: false, servedSize: ImageSize.thumbnail }
|
||||
}
|
||||
// preview, or original downgraded because downloadOriginalPhoto is off
|
||||
return { subpath: '/thumbnail', sizeQueryParam: 'preview', attachment: false, servedSize: ImageSize.preview }
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
import { apiUrl, authHeaders, buildUrl } from '../immich'
|
||||
import { Response } from 'express-serve-static-core'
|
||||
import { Asset, ImageSize, KeyType, SharedLink } from '../types'
|
||||
import { getConfigOption } from '../config/access'
|
||||
import { log } from '../utils/log'
|
||||
import archiver from 'archiver'
|
||||
import { sanitize } from '../utils/sanitize'
|
||||
import { Readable, Transform } from 'stream'
|
||||
import { pipeline } from 'stream/promises'
|
||||
import { promises as fs, createWriteStream } from 'fs'
|
||||
import { tmpdir } from 'os'
|
||||
import { join } from 'path'
|
||||
import { resolveImageEndpoint, ImageEndpoint } from './asset'
|
||||
import { title } from '../share'
|
||||
import { getFilename } from '../gallery/filename'
|
||||
|
||||
/**
|
||||
* A pass-through Transform that destroys itself if no data flows through for
|
||||
* `idleMs`. The timer is set when the transform is created and reset on every
|
||||
* chunk, so a slow-but-steady download (large video over a slow link) keeps
|
||||
* going, while a genuinely stalled connection still fails fast.
|
||||
*/
|
||||
function createIdleTimeoutStream (idleMs: number): Transform {
|
||||
let timer: NodeJS.Timeout | undefined
|
||||
const transform: Transform = new Transform({
|
||||
transform (chunk, _, cb) {
|
||||
if (timer) clearTimeout(timer)
|
||||
timer = setTimeout(() => transform.destroy(new Error(`No data received for ${idleMs}ms`)), idleMs)
|
||||
cb(null, chunk)
|
||||
},
|
||||
flush (cb) {
|
||||
if (timer) clearTimeout(timer)
|
||||
cb()
|
||||
}
|
||||
})
|
||||
// Arm the timer immediately so a response that returns headers but never
|
||||
// sends a body also times out.
|
||||
timer = setTimeout(() => transform.destroy(new Error(`No data received for ${idleMs}ms`)), idleMs)
|
||||
return transform
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a function that runs at most `limit` async tasks concurrently.
|
||||
* Tasks queue when the limit is reached and resume in FIFO order.
|
||||
*/
|
||||
function createLimiter (limit: number) {
|
||||
let active = 0
|
||||
const queue: Array<() => void> = []
|
||||
return async function run<T> (fn: () => Promise<T>): Promise<T> {
|
||||
if (active >= limit) {
|
||||
await new Promise<void>(resolve => queue.push(resolve))
|
||||
}
|
||||
active++
|
||||
try {
|
||||
return await fn()
|
||||
} finally {
|
||||
active--
|
||||
const next = queue.shift()
|
||||
if (next) next()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Download all assets in a share as a zip file.
|
||||
*/
|
||||
export async function downloadAll (res: Response, share: SharedLink) {
|
||||
await downloadAssets(res, share, share.assets)
|
||||
}
|
||||
|
||||
/**
|
||||
* Stream the given assets back as a zip file.
|
||||
*
|
||||
* Pattern adapted from Immich's own download service:
|
||||
* https://github.com/immich-app/immich/blob/main/server/src/services/download.service.ts
|
||||
*
|
||||
* Per asset, the upstream fetch is two phases:
|
||||
* 1. Get the response headers (retried up to 3 times with linear backoff,
|
||||
* bounded by a 20s header-receipt timeout).
|
||||
* 2. Stream the body to a temp file, guarded by an idle timeout that
|
||||
* resets on every chunk. A genuinely stalled connection fails fast; a
|
||||
* slow-but-steady transfer (large video over a slow link) completes.
|
||||
*
|
||||
* If any asset ultimately fails, the in-flight download is aborted mid-stream:
|
||||
* the archive is aborted, the HTTP response socket is destroyed, and the
|
||||
* failure is logged. We do this (rather than silently omitting the asset)
|
||||
* because by the time we know the asset failed we've already sent a 200
|
||||
* response to the client, so the only way to signal "your zip is incomplete"
|
||||
* is to terminate the response - leaving the user with a visibly broken/
|
||||
* truncated download instead of a zip that's quietly missing files.
|
||||
*/
|
||||
export async function downloadAssets (res: Response, share: SharedLink, assets: Asset[]) {
|
||||
res.setHeader('Content-Type', 'application/zip')
|
||||
let filename = (sanitize(title(share)) || 'photos') + '.zip'
|
||||
filename = encodeURI(filename)
|
||||
res.setHeader('Content-Disposition', `attachment; filename*=UTF-8''${filename}`)
|
||||
// Hint to intermediate proxies (Nginx, etc.) not to buffer this response.
|
||||
res.setHeader('X-Accel-Buffering', 'no')
|
||||
// STORE rather than deflate - photos and videos are already compressed,
|
||||
// this is the same as Immich does
|
||||
const archive = archiver('zip', { store: true })
|
||||
archive.pipe(res)
|
||||
|
||||
const maxAttempts = 3
|
||||
const headerTimeoutMs = 20_000
|
||||
const idleTimeoutMs = 20_000
|
||||
const concurrency = Math.max(1, getConfigOption('ipp.downloadFromImmichConcurrencyLimit', 8) as number)
|
||||
|
||||
const stagingDir = await fs.mkdtemp(join(tmpdir(), 'ipp-zip-'))
|
||||
let aborted = false
|
||||
|
||||
type StagedAsset = { tempfile: string, asset: Asset, endpoint: ImageEndpoint }
|
||||
type Failure = { asset: Asset, url: string, status?: number, error?: unknown }
|
||||
|
||||
const stageOne = async (asset: Asset, index: number): Promise<StagedAsset | { failure: Failure } | null> => {
|
||||
// Skip work if another stage has already triggered an abort.
|
||||
if (aborted) return null
|
||||
|
||||
const endpoint = resolveImageEndpoint(ImageSize.original, asset)
|
||||
const url = buildUrl(apiUrl() + '/assets/' + encodeURIComponent(asset.id) + endpoint.subpath, {
|
||||
[asset.keyType || 'key']: asset.key,
|
||||
size: endpoint.sizeQueryParam
|
||||
})
|
||||
const reqAuthHeaders = await authHeaders(asset.keyType || KeyType.key, asset.key, asset.password)
|
||||
|
||||
// Phase 1: get response headers, retrying on transient failure.
|
||||
// We use AbortController + a clearable timer rather than
|
||||
// `AbortSignal.timeout` because the signal we pass to fetch stays bound
|
||||
// to the response body - if the timeout fires after headers arrive but
|
||||
// while the body is still streaming, the body read errors out. The
|
||||
// header timer is cleared as soon as we have a response; from there the
|
||||
// idle-timeout transform downstream guards against stalled bodies.
|
||||
let response: globalThis.Response | undefined
|
||||
let lastStatus: number | undefined
|
||||
let lastError: unknown
|
||||
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
||||
if (aborted) return null
|
||||
const controller = new AbortController()
|
||||
const headerTimer = setTimeout(() => controller.abort(new Error(`No response headers within ${headerTimeoutMs}ms`)), headerTimeoutMs)
|
||||
try {
|
||||
const data = await fetch(url, { signal: controller.signal, headers: reqAuthHeaders })
|
||||
clearTimeout(headerTimer)
|
||||
if (data.ok) {
|
||||
response = data
|
||||
break
|
||||
}
|
||||
await data.body?.cancel()
|
||||
lastStatus = data.status
|
||||
lastError = undefined
|
||||
} catch (e) {
|
||||
clearTimeout(headerTimer)
|
||||
lastError = e
|
||||
lastStatus = undefined
|
||||
}
|
||||
if (attempt < maxAttempts) {
|
||||
const reason = lastStatus !== undefined
|
||||
? `HTTP ${lastStatus}`
|
||||
: (lastError instanceof Error ? lastError.message : String(lastError))
|
||||
log(`Retrying asset ${asset.id} (attempt ${attempt + 1}/${maxAttempts}) after ${reason}`)
|
||||
// Linear backoff between attempts to avoid hammering a struggling server.
|
||||
await new Promise(resolve => setTimeout(resolve, 500 * attempt))
|
||||
}
|
||||
}
|
||||
|
||||
if (!response || !response.body) {
|
||||
return { failure: { asset, url, status: lastStatus, error: lastError } }
|
||||
}
|
||||
|
||||
// Phase 2: stream body to a temp file, guarded by an idle timeout.
|
||||
// Use the array index in the path so we never collide on duplicate IDs.
|
||||
const tempfile = join(stagingDir, `${index}-${asset.id}`)
|
||||
// `response.body` is the global/undici ReadableStream<Uint8Array>;
|
||||
// Readable.fromWeb expects node:stream/web's ReadableStream<any>. The
|
||||
// two are structurally compatible at runtime but TS sees them as
|
||||
// distinct nominal types, so a cast is needed.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const body = Readable.fromWeb(response.body as any)
|
||||
try {
|
||||
await pipeline(body, createIdleTimeoutStream(idleTimeoutMs), createWriteStream(tempfile))
|
||||
} catch (e) {
|
||||
return { failure: { asset, url, error: e } }
|
||||
}
|
||||
|
||||
return { tempfile, asset, endpoint }
|
||||
}
|
||||
|
||||
try {
|
||||
const limit = createLimiter(concurrency)
|
||||
// Kick off every stage at once; the limiter caps how many run concurrently.
|
||||
// The map preserves input order so the consumer below archives in order.
|
||||
const stages = assets.map((asset, index) => limit(() => stageOne(asset, index)))
|
||||
|
||||
let failure: Failure | null = null
|
||||
for (const stage of stages) {
|
||||
const result = await stage
|
||||
if (result === null) break // aborted by an earlier stage
|
||||
if ('failure' in result) {
|
||||
aborted = true
|
||||
failure = result.failure
|
||||
break
|
||||
}
|
||||
// archive.file queues the entry; archiver lazily opens and reads it.
|
||||
archive.file(result.tempfile, { name: getFilename(result.asset, result.endpoint.servedSize) })
|
||||
}
|
||||
|
||||
// After abort, wait for any in-flight stages to settle before we delete
|
||||
// the staging dir. stageOne never rejects (errors become failure objects),
|
||||
// so a plain Promise.all is safe.
|
||||
if (aborted) await Promise.all(stages)
|
||||
|
||||
if (failure) {
|
||||
const f = failure as Failure
|
||||
const detail = f.status !== undefined
|
||||
? `HTTP ${f.status}`
|
||||
: (f.error instanceof Error ? f.error.message : String(f.error))
|
||||
log(`Aborting zip download for share ${share.key}: failed to fetch asset ${f.asset.id} from ${f.url} (${detail})`)
|
||||
archive.abort()
|
||||
res.destroy()
|
||||
return
|
||||
}
|
||||
|
||||
// finalize() resolves when archiver has finished writing the zip output,
|
||||
// which means every queued tempfile has been read. Safe to delete after.
|
||||
await archive.finalize()
|
||||
} finally {
|
||||
await fs.rm(stagingDir, { recursive: true, force: true }).catch(() => { /* best effort */ })
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,22 @@ export interface ExifInfo {
|
||||
// EXIF orientation string ("1".."8") or null. Values 5-8 indicate the image
|
||||
// is rotated 90°/270°, so the displayed aspect ratio swaps width/height.
|
||||
orientation?: string | null;
|
||||
// Additional EXIF fields surfaced by Immich for the metadata sidebar
|
||||
// (gated server-side by ipp.showMetadata.exif.* and .location.* config).
|
||||
dateTimeOriginal?: string | null;
|
||||
fileSizeInByte?: number | null;
|
||||
make?: string | null;
|
||||
model?: string | null;
|
||||
lensModel?: string | null;
|
||||
exposureTime?: string | null;
|
||||
iso?: number | null;
|
||||
fNumber?: number | null;
|
||||
focalLength?: number | null;
|
||||
city?: string | null;
|
||||
state?: string | null;
|
||||
country?: string | null;
|
||||
latitude?: number | null;
|
||||
longitude?: number | null;
|
||||
}
|
||||
|
||||
export enum AlbumType {
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import dayjs from 'dayjs'
|
||||
|
||||
/**
|
||||
* Output a timestamped log message. Calling `log(...)` is equivalent to
|
||||
* `log.info(...)` and stays available for existing call sites.
|
||||
*
|
||||
* log.info('...') informational, goes to stdout
|
||||
* log.warn('...') non-fatal anomaly, goes to stderr with WARN prefix
|
||||
* log.error('...') failure / unexpected error, goes to stderr with ERROR prefix
|
||||
*/
|
||||
const timestamp = () => dayjs().format()
|
||||
|
||||
type LogFn = ((message: string) => void) & {
|
||||
info: (message: string) => void
|
||||
warn: (message: string) => void
|
||||
error: (message: string) => void
|
||||
}
|
||||
|
||||
const logImpl: LogFn = ((message: string) => console.log(timestamp() + ' ' + message)) as LogFn
|
||||
logImpl.info = (message: string) => console.log(timestamp() + ' ' + message)
|
||||
logImpl.warn = (message: string) => console.warn(timestamp() + ' WARN ' + message)
|
||||
logImpl.error = (message: string) => console.error(timestamp() + ' ERROR ' + message)
|
||||
|
||||
export const log = logImpl
|
||||
@@ -1,9 +1,9 @@
|
||||
/**
|
||||
* From https://www.npmjs.com/package/sanitize-filename
|
||||
* Adapted from https://www.npmjs.com/package/sanitize-filename
|
||||
*
|
||||
* Replaces characters in strings that are illegal/unsafe for filenames.
|
||||
* Unsafe characters are either removed or replaced by a substitute set
|
||||
* in the optional `options` object.
|
||||
* in the optional second argument.
|
||||
*
|
||||
* Illegal Characters on Various Operating Systems
|
||||
* / ? < > \ : * | "
|
||||
@@ -13,18 +13,11 @@
|
||||
* C0 0x00-0x1f & C1 (0x80-0x9f)
|
||||
* http://en.wikipedia.org/wiki/C0_and_C1_control_codes
|
||||
*
|
||||
* Reserved filenames on Unix-based systems (".", "..")
|
||||
* Reserved filenames in Windows ("CON", "PRN", "AUX", "NUL", "COM1",
|
||||
* "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9",
|
||||
* "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", and
|
||||
* "LPT9") case-insesitively and with or without filename extensions.
|
||||
* Reserved filenames on Unix-based systems (".", "..").
|
||||
* Reserved filenames in Windows ("CON", "PRN", "AUX", "NUL", "COM1"-"COM9",
|
||||
* "LPT1"-"LPT9") case-insensitively and with or without filename extensions.
|
||||
*
|
||||
* Capped at 255 characters in length.
|
||||
* http://unix.stackexchange.com/questions/32795/what-is-the-maximum-allowed-filename-and-folder-size-with-ecryptfs
|
||||
*
|
||||
* @param {String} input Original filename
|
||||
* @param {Object} options {replacement: String | Function }
|
||||
* @return {String} Sanitized filename
|
||||
* Capped at 254 characters in length.
|
||||
*/
|
||||
|
||||
const illegalRe = /[/?<>\\:*|"]/g
|
||||
@@ -34,7 +27,7 @@ const reservedRe = /^\.+$/
|
||||
const windowsReservedRe = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i
|
||||
const windowsTrailingRe = /[. ]+$/
|
||||
|
||||
export function sanitize (input, replacement = '') {
|
||||
export function sanitize (input: string, replacement = ''): string {
|
||||
if (typeof input !== 'string') {
|
||||
throw new Error('Input must be string')
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* Escape the five HTML-significant characters so that user-controlled text
|
||||
* can be embedded in HTML without injecting markup. Ampersand is escaped
|
||||
* first so the other replacements aren't double-escaped.
|
||||
*/
|
||||
export function escapeHtml (str: string): string {
|
||||
return str
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''')
|
||||
}
|
||||
|
||||
/**
|
||||
* Narrow an `unknown` to `string`, returning an empty string for any other
|
||||
* type. Used at boundaries where the input shape isn't statically known
|
||||
* (cookie session payloads, etc.).
|
||||
*/
|
||||
export function toString (value: unknown): string {
|
||||
return typeof value === 'string' ? value : ''
|
||||
}
|
||||
@@ -1,34 +1,8 @@
|
||||
import { AssetType } from '../types'
|
||||
import { ThemeScript } from './_theme'
|
||||
import { ThemeScript } from './theme'
|
||||
import { GalleryItem, LightboxConfig, MetadataConfig } from '../shared/types'
|
||||
|
||||
export interface GalleryItem {
|
||||
id: string
|
||||
type: AssetType
|
||||
previewUrl: string
|
||||
thumbnailUrl: string
|
||||
downloadUrl?: string
|
||||
// pre-stringified JSON describing the video source (used to build a <video>
|
||||
// element for video slides in the PhotoSwipe lightbox)
|
||||
videoData?: string
|
||||
// already-escaped HTML fragment used as a caption in the lightbox
|
||||
description?: string
|
||||
downloadFilename: string
|
||||
// Display dimensions after EXIF orientation correction; needed for the
|
||||
// pre-computed justified-rows layout that virtualization depends on.
|
||||
width?: number
|
||||
height?: number
|
||||
// Base64-encoded thumbhash for an optional blur placeholder behind each tile
|
||||
thumbhash?: string
|
||||
// ISO date string from Immich; used to group tiles by month when enabled.
|
||||
fileCreatedAt?: string
|
||||
}
|
||||
|
||||
export interface LightboxConfig {
|
||||
showArrows: boolean
|
||||
showDownload: boolean
|
||||
mobileArrows: boolean
|
||||
options?: Record<string, unknown>
|
||||
}
|
||||
export type { GalleryItem, LightboxConfig, MetadataConfig }
|
||||
|
||||
export interface GalleryProps {
|
||||
items: GalleryItem[]
|
||||
@@ -41,6 +15,7 @@ export interface GalleryProps {
|
||||
openItem?: number
|
||||
ogImageItem?: GalleryItem
|
||||
lightboxConfig: LightboxConfig
|
||||
metadataConfig: MetadataConfig
|
||||
groupByDate: boolean
|
||||
}
|
||||
|
||||
@@ -49,6 +24,7 @@ export function Gallery (props: GalleryProps) {
|
||||
items: props.items,
|
||||
openItem: props.openItem,
|
||||
lightboxConfig: props.lightboxConfig,
|
||||
metadataConfig: props.metadataConfig,
|
||||
groupByDate: props.groupByDate
|
||||
})
|
||||
const firstItem = props.items[0]
|
||||
@@ -134,7 +110,7 @@ export function Gallery (props: GalleryProps) {
|
||||
id="ipp-init"
|
||||
dangerouslySetInnerHTML={{ __html: initJson }}
|
||||
/>
|
||||
<script type="module" src="/share/static/web.js"></script>
|
||||
<script type="module" src="/share/static/js/client/init.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
)
|
||||
@@ -0,0 +1,26 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { escapeHtml } from '../src/utils/text'
|
||||
|
||||
describe('escapeHtml', () => {
|
||||
it('escapes the five HTML-significant characters', () => {
|
||||
expect(escapeHtml('<script>alert("xss")</script>')).toBe(
|
||||
'<script>alert("xss")</script>'
|
||||
)
|
||||
})
|
||||
|
||||
it('escapes ampersand first so other escapes are not re-escaped', () => {
|
||||
expect(escapeHtml('&')).toBe('&amp;')
|
||||
})
|
||||
|
||||
it('escapes single quotes', () => {
|
||||
expect(escapeHtml("it's")).toBe('it's')
|
||||
})
|
||||
|
||||
it('returns empty string unchanged', () => {
|
||||
expect(escapeHtml('')).toBe('')
|
||||
})
|
||||
|
||||
it('passes through strings with no special characters', () => {
|
||||
expect(escapeHtml('plain text 123')).toBe('plain text 123')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"rootDir": "src",
|
||||
"outDir": "public/js",
|
||||
"module": "esnext",
|
||||
"moduleResolution": "bundler",
|
||||
"target": "ES2022",
|
||||
"lib": [
|
||||
"DOM",
|
||||
"DOM.Iterable",
|
||||
"ES2022"
|
||||
],
|
||||
"strict": true,
|
||||
"noImplicitAny": true,
|
||||
"strictNullChecks": true,
|
||||
"isolatedModules": true,
|
||||
"esModuleInterop": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"skipLibCheck": true,
|
||||
"inlineSourceMap": true,
|
||||
"inlineSources": true
|
||||
},
|
||||
"include": [
|
||||
"src/client/**/*.ts",
|
||||
"src/shared/**/*.ts"
|
||||
]
|
||||
}
|
||||
@@ -20,11 +20,19 @@
|
||||
"ES7"
|
||||
],
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"skipLibCheck": true,
|
||||
"jsx": "react-jsx",
|
||||
"jsxImportSource": "preact"
|
||||
},
|
||||
"include": [
|
||||
"**/*.ts",
|
||||
"**/*.tsx"
|
||||
],
|
||||
"exclude": [
|
||||
"node_modules",
|
||||
"dist",
|
||||
"tests",
|
||||
"vitest.config.ts",
|
||||
"src/client"
|
||||
]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
import { defineConfig } from 'vitest/config'
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
include: ['tests/**/*.test.ts'],
|
||||
environment: 'node'
|
||||
}
|
||||
})
|
||||
Reference in New Issue
Block a user