Compare commits

..
5 Commits
Author SHA1 Message Date
Guoliang ChenandClaude Opus 5.5 4cdbd66fcf Sharper first view and smoke loader sign-off
The loader now measures throughput from whole tile batches, not just the
two probe tiles, and after a session settles inside its deadline it tops
up in the background: the needed level if the budget cut it short, then
one level above it on capable devices with a fast connection (drawn
downscaled), within time and memory caps and never under Save-Data.

The chop in the album end card and the page footer is replaced by the
LUCIO loader in smoke from lucioIP, falling back to the SVG loader
without WebGL. sync-brand.sh now copies lucio-loaders.js and defaults to
../lucioIP.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 01:47:44 -08:00
lucioandClaude Opus 5.5 e48a1eacf4 Keep hotlink 403s out of CDN and browser caches
The tile hotlink refusal is sent with Cache-Control: no-store from
LuPhoto, Caddy and nginx instead of inheriting the one-year immutable
header. cloudflare.md explains that edge-cached tiles bypass the
origin Referer check, recommends a WAF rule for /t/, and notes that
tile URLs depend only on the photo, the settings and the site key.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 22:49:45 -08:00
lucioandClaude Opus 5.5 c87aad0254 Risk-based robot check with server-issued photo keys
The main page and direct photo links open without a prompt. Each
photo's pool is sealed with its own key, handed out by POST /k
(served by the daemon in serve and export mode). The hold-and-solve
card appears only for low-entropy clicks into a collection, too many
low-entropy landings from one IP, or more than photo_limit photos per
window, with escalating proof-of-work and a 429 cap. Build ids now
sort chronologically within the same second.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 22:45:50 -08:00
lucioandClaude Opus 5.5 f5152fb709 Anti-scraping: 3x3 grids, decoy pools, robot check
Every pyramid level is cut into at least min_grid x min_grid tiles.
Each photo's tile pool mixes real tiles with hard-linked decoys from
other photos; the grid-to-pool map, byte sizes, seed and scramble seed
are sealed per build and unlocked by a press-and-hold check backed by
a static proof of work. Cell scrambling is on by default, and
robots.txt disallows tiles and pool files.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 21:39:30 -08:00
lucioandClaude Opus 5.5 aaf7cafdf9 Viewer zoom and sharper tiles
Mouse wheel, trackpad and two-finger pinch zoom in the album viewer,
up to one image pixel per device pixel; drag pans while zoomed and
only the visible tiles of the needed level are loaded.

Default WebP quality raised to top 90, mid 88, low 88, with
smart_subsample for WebP tiles and the seed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 20:56:12 -08:00
45 changed files with 5070 additions and 292 deletions

No files matched your search

+45 -13
View File
@@ -1,6 +1,6 @@
# LuPhoto
LuPhoto serves photos.luciochen.com. It is one Go program that reads album folders, cuts every photo into 512 px WebP tiles at several resolutions with libvips, and publishes a static site in which the browser stitches the visible tiles back together on a canvas. Design: [docs/DESIGN.md](docs/DESIGN.md).
LuPhoto serves photos.luciochen.com. It is one Go program that reads album folders, cuts every photo into WebP tiles at several resolutions with libvips (at most 512 px, at least a 3 × 3 grid per level), and publishes a static site in which the browser stitches the visible tiles back together on a canvas. Covers are always open; photo tile maps are unlocked per photo by keys the daemon hands out at `/k`, with a press-and-hold check only for visitors who look automated; see [Protection](#protection). Design: [docs/DESIGN.md](docs/DESIGN.md).
## Commands
@@ -12,7 +12,7 @@ luphoto [-config /etc/luphoto/config.toml] <command>
|---|---|
| `build` | Process the albums once, publish a new build, exit. |
| `serve` | Build, watch the albums folder, rebuild after changes, and serve the site over HTTP on `server.listen`. |
| `export` | Build, watch and rebuild; no HTTP. Point Caddy or nginx at `<output>/current`. |
| `export` | Build, watch and rebuild. Point Caddy or nginx at `<output>/current`. With `protection.gate = "server"` it also listens on `server.listen`, serving only the key endpoint `/k`, which the web server must proxy. |
| `run` | `serve` or `export`, whichever `server.mode` says. The systemd unit uses this. |
| `version` | Print the version. |
@@ -75,30 +75,59 @@ Unknown fields are errors, so typos are caught.
|---|---|---|
| `server.mode` | `"export"` | What `luphoto run` does: `"serve"` or `"export"`. |
| `server.listen` | `"127.0.0.1:8080"` | Address of the built-in HTTP server. |
| `server.base_url` | `"https://photos.luciochen.com"` | Used for canonical and Open Graph URLs. |
| `server.base_url` | `"https://photos.luciochen.com"` | Used for canonical and Open Graph URLs; its host is also accepted as `Origin` on `/k`. |
| `server.trusted_proxies` | `["127.0.0.1/32", "::1/128"]` | CIDRs (or single addresses) of reverse proxies whose `client_ip_header` is believed. |
| `server.client_ip_header` | `"X-Forwarded-For"` | Header carrying the visitor's address, read only when the direct peer is in `trusted_proxies` (the right-most untrusted address wins). Behind a Cloudflare Tunnel use `"CF-Connecting-IP"`. Empty: always use the peer address. |
| `paths.albums` | `"/srv/luphoto/albums"` | Album folders. Read only. |
| `paths.output` | root or systemd: `/var/lib/luphoto/site`, else `$XDG_DATA_HOME/luphoto/site` | Builds, tiles, `current`. The site key and per-photo records go to `state/` next to it. |
| `paths.cache` | root or systemd: `/var/cache/luphoto`, else the user cache dir | Temporary vips files. |
| `images.tile_size` | `512` | Tile edge in pixels. |
| `images.overlap` | `1` | Tile overlap in pixels. |
| `images.tile_size` | `512` | Largest tile edge in pixels. Each level uses min(`tile_size`, short edge ÷ `min_grid`), at least 1 px. |
| `images.min_grid` | `3` | Minimum tile columns and rows per level (1–8). Levels whose short edge would drop below it are not made. Changing it reprocesses everything. |
| `images.overlap` | `1` | Tile overlap in pixels; 0 on levels whose tile is at most twice as wide, and always 0 while `scramble_cells` is on. |
| `images.format` | `"webp"` | `"webp"` or `"avif"` (AVIF needs a libheif AV1 encoder). |
| `images.quality` | `{ top = 82, mid = 85, low = 88 }` | Top two levels, levels above 1100 px, levels up to 1100 px. |
| `images.quality` | `{ top = 90, mid = 88, low = 88 }` | Top two levels, levels above 1100 px, levels up to 1100 px. |
| `images.min_levels` | `6` | Minimum pyramid depth. |
| `images.seed_px` | `48` | Long edge of the blurred placeholder. |
| `images.tile_names` | `"hashed"` | Only `"hashed"` in v1. |
| `images.scramble_cells` | `false` | Shuffle the 64 px cells inside each tile with a per-photo key; the browser restores them when it decodes a tile. Forces tile overlap 0. Changing it reprocesses everything. |
| `images.scramble_cells` | `true` | Shuffle the 64 px cells inside each tile with a per-photo key; the browser restores them when it decodes a tile. Tiles under two cells wide or high are left alone. Forces tile overlap 0. Changing it reprocesses everything. |
| `loading.budget_ms` | `3000` | Time budget per photo in the browser. |
| `loading.max_dpr` | `2.0` | Highest device pixel ratio the loader honours. |
| `loading.concurrency` | `6` | Parallel tile requests. |
| `build.watch` | `true` | Watch the albums folder in `serve` and `export`. |
| `build.debounce` | `"30s"` | Quiet time after the last change before rebuilding. |
| `build.workers` | `2` | Photos processed in parallel. vips threads per photo = CPUs ÷ workers. |
| `build.keep_builds` | `3` | Builds kept; tiles no kept build uses are deleted. |
| `build.keep_builds` | `3` | Builds kept; tile folders and decoys no kept build uses are deleted. |
| `protection.block_context_menu` | `true` | Disable the context menu on photos. |
| `protection.hotlink_allow` | `["photos.luciochen.com"]` | Hosts allowed as `Referer` for `/t/*`; empty Referers and the site's own host are always allowed. |
| `protection.hotlink_allow` | `["photos.luciochen.com"]` | Hosts allowed as `Referer` for `/t/*` and as `Origin` for `/k`; empty Referers on `/t/*` and the site's own host are always allowed. |
| `protection.decoys` | `4` | Decoy tiles per real tile in each photo folder (0–16); 0 turns decoys off. |
| `protection.gate` | `"server"` | `"server"`: photo keys come from the daemon's `/k`, with the risk checks below. `"off"`: every photo key is published in the album manifest and `/k` is never called (pure static hosting). The old `true`/`false` still read as `"server"`/`"off"`. |
| `protection.pow_bits` | `20` | Base proof-of-work size of a challenge (10–26); each extra bit doubles the average work. |
| `protection.photo_limit` | `400` | Photo keys one address may unlock per `window` before it is challenged again; more than 4 × this in a window is answered 429. |
| `protection.min_entropy` | `20` | Interaction score (0–100) below which a visitor counts as low-entropy. |
| `protection.landing_limit` | `5` | Low-entropy direct landings per address per `window` before every request without a pass is challenged (1–10000). |
| `protection.window` | `"10m"` | Sliding window of the per-address counters (1m–24h). |
| `protection.pass_ttl` | `"12h"` | Lifetime of the pass a solved challenge earns (1m–720h). |
The watcher ignores dotfiles (including rsync's `.name.XXXXXX` temp files), `*.part`, `*.tmp` and editor backups. vips runs at `nice +5` so processing does not starve the web server.
## Protection
Everything except the small key endpoint `/k` stays static files, so export mode, Caddy, nginx and Cloudflare caching of `/t/` keep working. What a build adds on top of hashed tile names:
- **Small tiles.** Every level of every photo and cover is cut into at least a 3 × 3 grid (`images.min_grid`), so no single file is a usable picture, not even the small levels.
- **Decoys.** Each photo folder `/t/<hash>/` also holds `protection.decoys` × as many decoy files as it has real tiles: hard links (copies if linking fails) to real tiles of other photos, from other albums first, with tile sizes as close as possible. A decoy name is an HMAC of the photo, level, slot and source tile, so a name never changes its bytes and `/t/` stays immutable. Decoys are chosen after all photos are processed; unchanged photos keep their decoys from build to build.
- **Sealed maps.** The album manifest and index carry only layout (sizes, tile grid, captions, EXIF). Which file sits where lives in one small JSON per photo and cover, `/a/<slug>/p/<hash>.<build>.json`, fetched when that photo is near: per level the shuffled pool of real and decoy ids, plus a `sealed` payload (the blurred seed, the cell-scramble seed, the grid→pool map and tile byte sizes) encrypted with a SHA-256 counter-mode keystream.
- **Keys.** Each build gets a random 32-byte secret in `builds/<id>/.secret` (mode 0600, never served). Every photo's pool is sealed with its own key, HMAC-SHA-256(secret, "photo|" + photo hash). Covers are sealed with one public cover key per build, HMAC(secret, "cover|"), published in the index JSON and every manifest, so the index and the next-album strip always draw without a check. With `gate = "off"` the manifest also lists every photo key.
- **Key endpoint.** The album page asks `POST /k` for the keys of the current photo and its neighbours, at most 8 per request: one request when the page loads, then one more only when the visitor moves past the photos it covers, never for photos far away. The first grant also returns a page token (30 minutes, bound to the address, build and album); later requests from that page send it, so one page load counts as at most one landing. The daemon answers it in serve mode and, in export mode, on `server.listen` (proxy `/k` there; it must never be cached). It accepts only requests whose `Origin` (or `Referer`) is the site's host, `server.base_url`'s host or a `hotlink_allow` host, for the current build or any kept build, and grants only hashes of the album named in the request.
- **When the prompt appears.** The main page never asks. Following a link to an album or straight to a photo (`/a/<slug>/#7`) does not ask either, as long as the address behaves. The press-and-hold card (0.9 s, while a Web Worker solves a proof of work) is shown when:
- a collection is opened from the index or the next-album card and the visitor's interaction score is below `min_entropy` and no pass is stored (the score counts mouse path, direction changes and distinct 8 px cells, touch gestures that move, scrolling and key presses, summed over the tab's session);
- an address has made `landing_limit` low-entropy landings (album page loads, a new tab or a reload each counting once, opened without a recent click from the site) within `window`, after which every request from it without a pass is challenged;
- an address has unlocked more than `photo_limit` photos since its last solved challenge within `window`.
- **Per-address limits.** IPv4 addresses are counted per /32, IPv6 per /64, in memory (per-minute counters over `window`, at most 200 000 addresses, least recently seen dropped first). A solved challenge earns a pass bound to that address for `pass_ttl`, which skips the entropy checks but not `photo_limit`; it resets the address's landing and photo counters. Each challenge solved within the window adds one bit of work (up to +6 over `pow_bits`), and more than 4 × `photo_limit` photos in a window are refused with 429 and `Retry-After` regardless of passes.
- **Cell scrambling** (`images.scramble_cells`, on by default), the hotlink rule on `/t/*`, no context menu, and `robots.txt` with `Disallow: /t/` and `Disallow: /a/*/p/`.
Limits: this raises the cost of bulk downloading; it does not prevent it. The interaction score is reported by the browser, so a bot can fake it; such a bot is bounded only by `photo_limit` per address and the escalating proof of work (about 0.25 s at 20 bits and 15 s at 26 bits in desktop V8, phones several times slower), and by the 429 cap. Many addresses multiply its budget. A determined scraper that drives a real browser, or reimplements the client, can still decrypt the maps and stitch the tiles; and decoys are byte-identical copies of other photos' tiles, so a crawler that downloads every folder can tell which files are shared. Every visitor's browser must be able to draw the photos, so it always has everything needed to do so.
## Install
### Ubuntu 22.04 / 24.04, Debian 12
@@ -135,7 +164,7 @@ rsync writes to dotted temp names and renames at the end, which the watcher igno
## Web server
- **Serve mode**: LuPhoto serves `current` itself with the right headers (immutable caching for `/t/`, `/og/`, `/assets/`; one minute for HTML and JSON; CSP; hotlink 403 on `/t/*`; precompressed gzip; no directory listings; `404.html` for missing paths). Put Caddy (`packaging/Caddyfile.serve`), nginx (`packaging/nginx.serve.conf`) or a Cloudflare Tunnel in front.
- **Export mode**: serve `/var/lib/luphoto/site/current` with `packaging/Caddyfile` or `packaging/nginx.conf`. Each build writes `.gz` files next to HTML, JSON, JS, CSS and SVG for `precompressed gzip` / `gzip_static`.
- **Export mode**: serve `/var/lib/luphoto/site/current` with `packaging/Caddyfile` or `packaging/nginx.conf`, and proxy `/k` to `luphoto run` on `server.listen` (both examples do; the daemon serves nothing else there). Without that proxy, photos stay jumbled unless `protection.gate = "off"`. Each build writes `.gz` files next to HTML, JSON, JS, CSS and SVG for `precompressed gzip` / `gzip_static`. Each build also writes `robots.txt`; serve mode serves the same file.
- **Cloudflare**: `packaging/cloudflared.yml` and `packaging/cloudflare.md` (cache rules).
## Building from source
@@ -165,7 +194,7 @@ This type-checks with `tsc --noEmit` (strict) and bundles with esbuild. Fonts ar
### Brand
`scripts/sync-brand.sh` copies the tokens, `lucio-morph.js`, the favicon and the chop from `../LUCIO_ip` (or `$LUCIO_IP_DIR`) into `web/brand/`, stripping comments. The copies are committed; rebuild the front-end afterwards.
`scripts/sync-brand.sh` copies the tokens, `lucio-morph.js`, `lucio-loaders.js`, the favicon and the chop from `../lucioIP` (or `$LUCIO_IP_DIR`) into `web/brand/`, stripping comments. The copies are committed; rebuild the front-end afterwards.
## Output layout
@@ -173,8 +202,11 @@ This type-checks with `tsc --noEmit` (strict) and bundles with esbuild. Fonts ar
/var/lib/luphoto/
site/
current -> builds/<id>
builds/<id>/index.html, 404.html, index.<id>.json, a/<slug>/index.html, a/<slug>/manifest.<id>.json, assets/, t -> ../../t, og -> ../../og (plus .gz copies)
t/<photo-hash>/<tile-id>.webp
builds/<id>/index.html, 404.html, robots.txt, index.<id>.json, a/<slug>/index.html, a/<slug>/manifest.<id>.json,
a/<slug>/p/<hash>.<id>.json, assets/, t -> ../../t, og -> ../../og (plus .gz copies)
builds/<id>/.refs every pool id per photo folder, read by the cleanup to find stale decoys (never served)
builds/<id>/.secret the build's 32-byte key secret, mode 0600, read by /k (never served)
t/<photo-hash>/<tile-id>.webp real tiles and decoys (hard links), unordered
og/<hash>.jpg
state/
site.key
+67 -22
View File
@@ -1,8 +1,8 @@
# LuPhoto design
LuPhoto serves photos.luciochen.com. It is one Go program that reads album folders from disk, cuts every photo into fixed 512 px tiles at several resolutions, and publishes a fully static, Lucio-branded site that a browser stitches back together on a canvas. No editing, comments, likes, themes, templating or camera RAW support.
LuPhoto serves photos.luciochen.com. It is one Go program that reads album folders from disk, cuts every photo into tiles of at most 512 px (at least 3 × 3 per level) at several resolutions, and publishes a fully static, Lucio-branded site that a browser stitches back together on a canvas. No editing, comments, likes, themes, templating or camera RAW support.
Decisions: name LuPhoto (binary, user and paths lowercase `luphoto`), Go, no resolution cap, hashed tile names in v1, cell scrambling optional and off, JPEGs not listed in album.json are hidden.
Decisions: name LuPhoto (binary, user and paths lowercase `luphoto`), Go, no resolution cap, hashed tile names in v1, cell scrambling on by default, decoy tiles and per-photo sealed tile maps whose keys a risk-based key endpoint hands out (covers always open, a press-and-hold check only for visitors who look automated), JPEGs not listed in album.json are hidden.
## Architecture
@@ -11,7 +11,7 @@ uploads (rsync/SFTP) -> /srv/luphoto/albums -> watcher (debounce) -> processor (
-> serve mode (built-in HTTP) or export mode (folder for Caddy/nginx) -> Cloudflare Tunnel + cache -> browser canvas stitches visible tiles
```
- Commands: `luphoto build` runs once; `luphoto serve` builds, watches and serves; `luphoto export` builds into the output folder and keeps watching; `luphoto run` does `serve` or `export` as `server.mode` says (the systemd unit uses it); `luphoto version`. `-config` flag, default `/etc/luphoto/config.toml`. Rebuilds never overlap: changes during a build cause one follow-up build.
- Commands: `luphoto build` runs once; `luphoto serve` builds, watches and serves; `luphoto export` builds into the output folder and keeps watching, and with `gate = "server"` listens on `server.listen` for `/k` only; `luphoto run` does `serve` or `export` as `server.mode` says (the systemd unit uses it); `luphoto version`. `-config` flag, default `/etc/luphoto/config.toml`. Rebuilds never overlap: changes during a build cause one follow-up build.
- Tiling with libvips CLI (`vips`), installed by `apt install libvips-tools`. Support libvips 8.12 (Ubuntu 22.04) and 8.15 (Ubuntu 24.04): metadata stripping is `strip` on 8.12 and `keep=none` on 8.15+.
- Front-end: plain TypeScript, no framework, bundled with esbuild, embedded in the binary with `go:embed`. Fixed Lucio brand.
- Speed and memory matter: photos are processed in parallel by a bounded worker pool; hashing, EXIF reading and tile renaming run concurrently; the browser fetches tiles concurrently and decodes off the main thread.
@@ -53,49 +53,85 @@ uploads (rsync/SFTP) -> /srv/luphoto/albums -> watcher (debounce) -> processor (
1. Autorotate by EXIF orientation, convert to sRGB from the embedded profile.
2. Read camera, lens, focal length, aperture, shutter, ISO and date into the manifest. Drop everything else, including GPS. Tiles carry no metadata.
3. Pyramid: tiles 512 px, 1 px overlap; each level halves the previous one until the long edge is under 100 px. Level 0 is the smallest.
4. WebP by default (AVIF optional). Quality per level: `top` for the top two levels, `low` for levels whose long edge is at most 1100 px, `mid` otherwise.
5. Seed: a 48 px (long edge) WebP, base64 inside the album manifest.
3. Pyramid: each level halves the previous one until the long edge is under 100 px (at least `min_levels` levels), but never below a short edge of `min_grid` px. Level 0 is the smallest. Each level has its own tile size, min(`tile_size` 512, ⌊short edge ÷ `min_grid` 3⌋), at least 1 px, so every level is a grid of at least 3 × 3 tiles; covers (32:9) are usually 11 × 3 at every level. Overlap 1 px, 0 when the tile is at most twice the overlap and always 0 with cell scrambling. `dzsave` cuts one level at a time with that level's tile size.
4. WebP by default (AVIF optional); WebP tiles and the seed are saved with `smart_subsample` so chroma stays sharp. Quality per level: `top` for the top two levels, `low` for levels whose long edge is at most 1100 px, `mid` otherwise.
5. Seed: a 48 px (long edge) WebP, kept in the per-photo record and published only inside the sealed payload.
6. No resolution cap: the full-resolution level is stored; the loader never fetches beyond screen size × max_dpr.
7. Tile paths: `/t/<photo-hash>/<tile-id>.webp`. photo-hash = first 16 hex of SHA-256 over the original bytes + a processing-settings fingerprint. tile-id = first 16 hex of HMAC-SHA-256(site key, photo-hash|level|x|y). The site key is generated once and kept in the state folder. On disk and in developer tools the tiles are an unordered pile of patches; only the manifest maps them back.
8. Album manifest `/a/<slug>/manifest.<build>.json`: per photo width, height, level sizes, tile grid per level, tile ids in row-major order per level, byte size of every tile, caption, title, alt, EXIF, slides, seed. Covers are pyramids too and are described in `/index.<build>.json`.
7. Tile paths: `/t/<photo-hash>/<tile-id>.webp`. photo-hash = first 16 hex of SHA-256 over the original bytes + a processing-settings fingerprint (which includes `min_grid` and `scramble_cells`). tile-id = first 16 hex of HMAC-SHA-256(site key, photo-hash|level|x|y). The site key is generated once and kept in the state folder. Each folder also holds decoys (below), so on disk and in developer tools a folder is an unordered pile of patches from many photos.
8. Album manifest `/a/<slug>/manifest.<build>.json`: layout only. Per photo width, height, per level width, height, tile size, cols, rows (and overlap when not 0), caption, title, alt, EXIF, slides, plus the build's `gate` record `{build, mode, cover, min_entropy}` (and `keys` when the gate is off). Covers are pyramids too and are described in `/index.<build>.json`. Tile ids, byte sizes, the seed and the scramble seed are not in it.
Incremental: a photo is reprocessed only when its photo-hash is new. Each build writes `builds/<id>/` (HTML, manifests, assets, `404.html`, and a `.gz` copy of every HTML, JSON, JS, CSS and SVG file for precompressed serving) next to a shared `t/` tile folder and a shared `og/` folder of 1200×630 Open Graph JPEGs cut around each album cover (the only non-tiled images; derived, small, metadata stripped); the `current` symlink flips only when the build is complete. Keep the last `keep_builds` builds; delete tile folders no kept build references. Write everything to temporary names and rename, so readers never see partial files.
Incremental: a photo is reprocessed only when its photo-hash is new. Build ids are `YYYYMMDD-HHMMSS-micro-random` and always sort after every existing build, even within one second (keep_builds and the key endpoint rely on it). Each build writes `builds/<id>/` (HTML, manifests, per-photo pool files, assets, `404.html`, `robots.txt`, `.refs`, `.secret`, and a `.gz` copy of every HTML, JSON, JS, CSS and SVG file for precompressed serving) next to a shared `t/` tile folder and a shared `og/` folder of 1200×630 Open Graph JPEGs cut around each album cover (the only non-tiled images; derived, small, metadata stripped); the `current` symlink flips only when the build is complete. Keep the last `keep_builds` builds; delete tile folders no kept build references, and inside live folders delete files no kept build's `.refs` lists. Write everything to temporary names and rename, so readers never see partial files (pool files are written straight into the unpublished stage folder).
Storage: about 1.33× the top level, roughly 6–10 MB of tiles per Z8 photo.
Storage: about 1.33× the top level, roughly 6–10 MB of tiles per Z8 photo. Decoys are hard links and cost directory entries, not bytes; small low-level tiles cost some filesystem block overhead.
## Protection step (per build, after all photos are processed)
1. Keys: a random 32-byte build secret, written to `builds/<id>/.secret` (0600; dotfiles are never served). Photo key = HMAC-SHA-256(secret, "photo|" + photo-hash); cover key = HMAC-SHA-256(secret, "cover|"), one per build, public. The index and every manifest carry `{build, mode, cover, min_entropy}`; with `gate = "off"` each manifest also carries `keys: {hash: hex}` for its photos, so a purely static host works with the same code path.
2. Decoys: all live pyramids (photos and covers of every published album, carried albums included) are indexed by tile size; each pyramid's primary album is the first album, in index order, that uses it. For each level with R real tiles, `decoys` × R slots are filled from the bucket whose tile size is closest to the level's, taking candidates from other albums first, then other photos of the same album, then (single-pyramid site only) the photo itself. A slot's source is the next tile on a ring ordered by tile id after a target drawn from a PRNG keyed by HMAC(site key, "pick"|hash|level), skipping ineligible or already used tiles, so selections are stable while the site does not change. Decoy name = first 16 hex of HMAC-SHA-256(site key, "decoy"|photo-hash|level|slot|source tile id). The file is a hard link to the source tile (a copy if linking fails); names already present in the folder are reused (one `ReadDir` per folder).
3. Pool: per level the real ids and decoy names, shuffled with a PRNG keyed by HMAC(site key, "pool"|hash|level), written as one string of 16-hex ids.
4. Seal: plaintext = "luphoto-sealed-1" (16 bytes) + JSON `{seed, scramble, levels: [{map, bytes}]}` where `map` turns a row-major grid index into a pool index. Ciphertext = plaintext XOR keystream, block i = SHA-256(key | nonce | i as 4 bytes big-endian), 12-byte random nonce in front, base64; key = the photo key, or the cover key for covers.
5. `/a/<slug>/p/<hash>.<build>.json` = `{levels: [pool strings], sealed}` for every photo and the cover of each album; build-named like the manifests, so a new build never pairs with a cached pool. `builds/<id>/.refs` lists every pool id per folder (8-byte binary) for the cleanup.
## Key endpoint `POST /k`
Served by the daemon in serve mode, and in export mode on `server.listen` (nothing else is served there; the web server proxies `/k`). `Cache-Control: no-store`, JSON, body at most 4 KB, POST only. Rejected with 403 unless `Origin` (or `Referer` when `Origin` is absent) names the request's host, `base_url`'s host or a `hotlink_allow` host. 404 when the gate is off.
- Request: `{build, album, photos: [≤ 8 photo hashes], context: "nav" | "land", entropy: 0..100, pass?, page?, challenge?: {token, nonce}}`. Unknown or GC'd build, unknown album, a bad context or entropy: 400. Hashes not in that album of that build are dropped. Builds are found by their `.secret`, cached in memory, re-read after every build the daemon runs and at most every 2 s on a miss (so builds made by a separate `luphoto build` are found too); album membership is read from the build's manifest once per album.
- Responses: `{keys: {hash: hex}, pass?, page?, stale?}`; `{challenge: {token, bits}, stale?}`; 429 `{error}` with `Retry-After`. `stale: true` means the pass sent is not valid for this address and should be dropped.
- Client address: the TCP peer, unless the peer is in `trusted_proxies`, then the right-most address in `client_ip_header` that is not itself a trusted proxy. Bucket: IPv4 /32, IPv6 /64.
- State per bucket, in memory: 16 slots of `{photos, low-entropy landings, challenges solved}` over `window` (one slot per minute up to 16 minutes, wider beyond), plus the slot and count at the last solve. 16 shards, each a map into a slice with an intrusive LRU list, 200 000 buckets in all; the oldest bucket is reused when full. No allocation per request beyond a new bucket.
- Tokens: 24 bytes, base64url (32 characters): 4-byte time, 1 byte, 19 bytes of HMAC-SHA-256 over kind | bucket | the first 5 bytes, keyed by the site key. Challenge token: issue time and bits; valid 5 minutes, once (a ring of the last 32 768 solved tokens). Pass: expiry and version. Page token: expiry 30 minutes ahead, the MAC also covering build and album; returned with every grant that did not carry a valid one for the same album.
- Proof of work: SHA-256(token as 32 ASCII bytes | nonce as 8 bytes big-endian) has at least `bits` leading zero bits. One 64-byte block, so the browser precomputes the state after the 8 constant words.
- Decision, in order:
1. More than 4 × `photo_limit` photos unlocked in the window: 429.
2. A valid, unused, solved challenge: reset the bucket's landing count and restart its photo count, count one solve, grant, and issue a pass for `pass_ttl`.
3. Challenge, with `pow_bits` + min(6, solves in the window) bits, when photos unlocked since the last solve in the window exceed `photo_limit`; or, without a valid pass or page token for this album, when the context is `nav` and entropy < `min_entropy`, or when the window holds `landing_limit` low-entropy landings.
4. Grant keys for the requested photos and count them; a `land` request without a pass or page token and with entropy < `min_entropy` counts as a low-entropy landing, so each page load counts once.
## Loading in the browser
1. Seed (≈0 ms): the manifest is loaded; draw the seed scaled and blurred.
0. Keys. Covers open with the public cover key at once. On an album page the viewer asks `/k` for the current photo and its neighbours (`context` "nav" when the page was opened by a guarded click within the last 30 s, else "land"; the session's interaction score; the stored pass) in one request of up to 8 (one behind to six ahead), and waits for it; it asks again, with one more batch of up to 8 looking at most nine ahead, only when a photo within one behind or three ahead of the current one has no key. At most one request is in flight and nothing is queued beyond the latest batch. The page token from the first grant is kept in memory and sent with every later request; a returned pass goes to `localStorage`; a `stale` one is dropped. If the answer is a challenge, the hold card is shown over the album while a Web Worker (the tile worker script, a separate instance) solves it with an allocation-free SHA-256; after the hold and the solution the request is repeated with the answer. Each photo's pool file is fetched when the photo is near. While its key is on the way the photo draws nothing for up to 400 ms; after that, or while a challenge is up, it shows its probe level filled with random pool entries drawn into the grid cells (one fetch per cell at most). When the key arrives, the pool is decrypted on the main thread (a few hundred SHA-256 blocks), the seed fades in over the jumble, and the real tiles follow as below. With the gate off the keys come from the manifest and `/k` is never called.
1. Seed: draw the seed scaled and blurred.
2. Needed level: smallest level whose width ≥ displayed width × min(devicePixelRatio, max_dpr).
3. Probe: fetch 1–2 tiles of the level about 1/8 of the needed one; measure throughput; blend with earlier measurements kept in sessionStorage.
4. Final level: highest level up to the needed one whose visible-tile bytes ÷ throughput ≤ (budget − elapsed) × 0.8. If it is 2+ levels above the probe, fetch one intermediate level first.
5. Fetch only visible tiles, centre outwards, `concurrency` at a time; each tile fades in over the lower layer as it decodes.
6. Deadline `budget_ms` (3000): abort unfinished upgrades and keep what is on screen.
7. Top-up (album viewer, un-zoomed, only when steps 3–5 finished inside the deadline; never with Save-Data or on 2g/3g): each level batch also measures throughput (bytes ÷ wall time). If the final level stopped short of the needed one, fetch the needed level when its bytes ÷ throughput ≤ 6 s. Then, on a capable device (≥ 4 cores, `deviceMemory` ≥ 4 GB where reported) with throughput ≥ 1.5 MB/s, fetch one level above the needed one when it fits in 4 s and its decoded visible pixels stay under 35 % of the tile cache; it is drawn downscaled with high-quality smoothing. These fetches run at prefetch priority, show no loader and stop when the photo is left or zoomed.
Moving to another photo aborts that photo's requests. Prefetch the next photo's seed and probe level and, for multi-slide photos, the next slide's tiles. Decoded tiles live in an LRU cache capped at about 250 MB on desktop and 120 MB on phones. Decode with `createImageBitmap` (in a worker where supported). The canvas is always viewport-sized. Pixel density capped at `max_dpr` (2).
## Screens
Album index: full-width strips, 8 px apart on phones, 16 px on desktop. Header with the Lucio wordmark (Guoliang → Lucio morph on hover, the only animation on this screen); footer with the chop. Closed strip 32:6 showing the `collapsed_focus_y` band of the 32:9 cover, height `min(100vw*6/32, 28vh)`; open 32:9, height `min(100vw*9/32, 62vh)`; the cover is drawn cover-fit, never stretched (under the height caps a very wide screen crops top and bottom). Desktop: hover opens. Touch: the strip nearest the vertical centre opens while scrolling; tap enters. On open the height animates 240 ms, then the title fades in (light-on): mono date line, then the title in Bricolage Grotesque, bottom-left. Covers use the tile loader; closed strips load only the visible band; only strips near the viewport load.
Album index: full-width strips, 8 px apart on phones, 16 px on desktop. Header with the Lucio wordmark (Guoliang → Lucio morph on hover, the only animation on this screen); footer with the LUCIO loader in smoke (bottom-right; the plain SVG loader without WebGL; the chop until the script runs). Closed strip 32:6 showing the `collapsed_focus_y` band of the 32:9 cover, height `min(100vw*6/32, 28vh)`; open 32:9, height `min(100vw*9/32, 62vh)`; the cover is drawn cover-fit, never stretched (under the height caps a very wide screen crops top and bottom). Desktop: hover opens. Touch: the strip nearest the vertical centre opens while scrolling; tap enters. On open the height animates 240 ms, then the title fades in (light-on): mono date line, then the title in Bricolage Grotesque, bottom-left. Covers use the tile loader; closed strips load only the visible band; only strips near the viewport load.
Album viewer: one photo at a time, contained in the viewport (fills height or width, never stretched), centred on graphite. Swipe right-to-left, ←/→, click-and-drag; one pointer-events handler for mouse and touch with flick velocity and rubber-band ends; Home/End; Esc returns to the index. `slides: N`: the photo is scaled so a 1/N-wide section fits the viewport; moving between its slides is a continuous pan. `/a/<slug>/#7` opens photo 7. End card: chop, "— Lucio", the next album's strip. Reduced motion: crossfades.
Album viewer: one photo at a time, contained in the viewport (fills height or width, never stretched), centred on graphite. Swipe right-to-left, ←/→, click-and-drag; one pointer-events handler for mouse and touch with flick velocity and rubber-band ends; Home/End; Esc returns to the index. `slides: N`: the photo is scaled so a 1/N-wide section fits the viewport; moving between its slides is a continuous pan. `/a/<slug>/#7` opens photo 7. End card: the LUCIO loader in smoke, "— Lucio", the next album's strip. Reduced motion: crossfades.
Captions: hidden by default; shown while the pointer is in the bottom 20% of the photo; click or tap pins/unpins; `i` toggles. A tap is < 10 px movement and < 300 ms. Panel: mono line `03 / 12 · Z8 · 24-70 f/2.8 · 35mm · f/8 · 1/250 · ISO 64` (EXIF only when `show_exif`), then the caption in IBM Plex Sans over a graphite fade. Captions are real DOM text.
Lucio brand (source of truth: ../LUCIO_ip): graphite #111114 ground, paper #F3F1EC text, beam #FFF3CF only on focus and a thin progress line, steel for secondary text, cinnabar only in the chop. Bricolage Grotesque display, IBM Plex Sans body, IBM Plex Mono eyebrows (uppercase, +0.08em). Fonts self-hosted woff2, nothing from Google. If a photo has nothing sharp after 400 ms, the L→U→C→I→O loader (LucioMorph.loader) appears on the right edge, vertically centred, inset ≥ 32 px. One animated element per screen. Motion: 120 ms hover, 240 ms reveals, 900 ms light-on with cubic-bezier(0.16, 1, 0.3, 1). Brand files are copied from LUCIO_ip by `scripts/sync-brand.sh`.
Lucio brand (source of truth: ../lucioIP): graphite #111114 ground, paper #F3F1EC text, beam #FFF3CF only on focus and a thin progress line, steel for secondary text, cinnabar only in the chop. Bricolage Grotesque display, IBM Plex Sans body, IBM Plex Mono eyebrows (uppercase, +0.08em). Fonts self-hosted woff2, nothing from Google. If a photo has nothing sharp after 400 ms, the L→U→C→I→O loader (LucioMorph.loader) appears on the right edge, vertically centred, inset ≥ 32 px. One animated element per screen. Motion: 120 ms hover, 240 ms reveals, 900 ms light-on with cubic-bezier(0.16, 1, 0.3, 1). Brand files are copied from lucioIP by `scripts/sync-brand.sh`.
## Discouraging saves
No `<img>` for photos, only canvas. Output never contains an original. Right-click, drag, selection and long-press callouts are disabled. Hashed tile names (above). Optional `scramble_cells` (off): shuffle the full 64 px cells inside each tile with a per-photo key (HMAC of the site key and photo-hash, then a seeded Fisher–Yates per tile; tile overlap is 0 when on); the client restores each tile once when it decodes it, before it is cached and drawn. Hotlink: Referer check on `/t/*` in the built-in server and the Caddy/nginx examples; an empty Referer and the site's own host are allowed.
No `<img>` for photos, only canvas. Output never contains an original. Right-click, drag, selection and long-press callouts are disabled. Hashed tile names, at least 3 × 3 tiles per level, decoys and per-photo sealed maps whose keys come from `/k` (above). `scramble_cells` (on by default): shuffle the full 64 px cells inside each tile with a per-photo key (HMAC of the site key and photo-hash, then a seeded Fisher–Yates per tile; tiles under two cells wide or high are left alone; tile overlap is 0 when on); the scramble seed travels only inside the sealed payload, and the client restores each tile once when it decodes it, before it is cached and drawn. Hotlink: Referer check on `/t/*` in the built-in server and the Caddy/nginx examples; an empty Referer and the site's own host are allowed. `robots.txt` disallows `/t/` and `/a/*/p/`.
Interaction score: passive listeners on every page count mouse path length, direction changes over 30° between 8 px segments, distinct 8 px cells (a 4096-bit hashed set), touch gestures that move (or that the browser turns into a pan), wheel and scroll events (at most one per 100 ms) and key presses, trusted events only, with no allocation per event. Score = min(25, path ÷ 120) + min(35, 2.5 × turns) + min(20, cells ÷ 6) + min(45, 8 × gestures) + min(15, 1.5 × scrolls) + min(20, 2 × keys), capped at 100, kept for the tab's session in `sessionStorage` (memory if blocked).
Guarded links: the index strips and the album end card's next-album link. A plain click with a score ≥ `min_entropy`, or with a stored pass, navigates normally and leaves a "nav" flag (slug and time) in `sessionStorage`. Otherwise the click is held back, the card is shown on the current page, a challenge for that album is requested at once (`photos: []`, context "nav") and solved while the visitor holds; then the pass is stored and the page navigates with the flag. Esc closes the card on these pages. Modified clicks (new tab) are not guarded; the new tab lands as "land".
Hold card: graphite-2 card, mono eyebrow "Photos · Lucio", the line "Press and hold to see the photos" in Bricolage Grotesque, and an 88 px round button with a beam progress ring. Holding for 900 ms (pointer, or Space/Enter while focused) completes it; releasing early resets the ring. Then the ring turns indeterminate until the worker has a solution and the server has answered. A pointer that cannot be captured still works. The rest of the page is `inert` while the card is up; focus starts on the button and returns to the page afterwards. The pass is kept in `localStorage` (memory if storage is blocked). It is never shown on load of the index. Reduced motion: no spin, no fade.
Limits: this raises the cost of bulk downloading; it cannot stop a scraper that drives a real browser or reimplements the client. The score is self-reported, so a bot that fakes it is bounded only by `photo_limit` per address, the escalating proof of work and the 429 cap; and decoys are byte-identical to tiles of other photos, so crawling every folder reveals which files are shared.
## Config `/etc/luphoto/config.toml`
```toml
[server]
mode = "export"
listen = "127.0.0.1:8080"
base_url = "https://photos.luciochen.com"
mode = "export"
listen = "127.0.0.1:8080"
base_url = "https://photos.luciochen.com"
trusted_proxies = ["127.0.0.1/32", "::1/128"]
client_ip_header = "X-Forwarded-For"
[paths]
albums = "/srv/luphoto/albums"
@@ -106,11 +142,12 @@ cache = "/var/cache/luphoto"
tile_size = 512
overlap = 1
format = "webp"
quality = { top = 82, mid = 85, low = 88 }
quality = { top = 90, mid = 88, low = 88 }
min_levels = 6
seed_px = 48
tile_names = "hashed"
scramble_cells = false
scramble_cells = true
min_grid = 3
[loading]
budget_ms = 3000
@@ -126,6 +163,14 @@ keep_builds = 3
[protection]
block_context_menu = true
hotlink_allow = ["photos.luciochen.com"]
decoys = 4
gate = "server"
pow_bits = 20
photo_limit = 400
min_entropy = 20
landing_limit = 5
window = "10m"
pass_ttl = "12h"
```
Defaults when a path is missing: running as root or under systemd uses `/var/lib/luphoto/site` and `/var/cache/luphoto`; otherwise `$XDG_DATA_HOME/luphoto/site` and `$XDG_CACHE_HOME/luphoto` (Go `os.UserCacheDir` equivalents). The site key and the per-photo processing records live in the state folder (`state/`) next to the output. SIGHUP re-reads the config and rebuilds. The watcher ignores `.part`, `.tmp`, dotfiles and rsync temp names.
@@ -134,8 +179,8 @@ Defaults when a path is missing: running as root or under systemd uses `/var/lib
- `.deb` via nfpm: binary, `/etc/luphoto/config.toml`, systemd unit, `luphoto` user, `/srv/luphoto/albums`. Depends on `libvips-tools`. Ubuntu 22.04/24.04, Debian 12; other distros: tarball + unit file.
- systemd: read-only albums, read-write output and cache only, NoNewPrivileges, ProtectSystem=strict.
- Cloudflare Tunnel; cache rule `/t/*` for a month; HTML and manifests short TTL; manifests are build-named, so no purging.
- Caddy (export): root `/var/lib/luphoto/site/current`, `/t/*` `public, max-age=31536000, immutable`, `/a/*` `max-age=60`, `/og/*` and `/assets/*` immutable too, HTML and index JSON `max-age=60`, CSP `default-src 'self'; img-src 'self' blob: data:; font-src 'self'; worker-src 'self'; frame-ancestors 'none'`, `nosniff`, `Referrer-Policy: strict-origin-when-cross-origin`, hotlink 403 on `/t/*`, precompressed gzip, no directory listings, `404.html` for missing paths, GET/HEAD only. Serve mode: `reverse_proxy 127.0.0.1:8080`, the built-in server sends the same headers. nginx equivalent provided.
- Cloudflare Tunnel; cache rule `/t/*` for a month; HTML and manifests short TTL; manifests are build-named, so no purging; `/k` bypasses the cache. Set `client_ip_header = "CF-Connecting-IP"` and keep the tunnel's source (loopback) in `trusted_proxies`.
- Caddy (export): root `/var/lib/luphoto/site/current`, `/t/*` `public, max-age=31536000, immutable`, `/a/*` `max-age=60`, `/og/*` and `/assets/*` immutable too, HTML and index JSON `max-age=60`, CSP `default-src 'self'; img-src 'self' blob: data:; font-src 'self'; worker-src 'self'; frame-ancestors 'none'`, `nosniff`, `Referrer-Policy: strict-origin-when-cross-origin`, hotlink 403 on `/t/*`, precompressed gzip, no directory listings, `404.html` for missing paths, GET/HEAD only, except `/k`, which is proxied to the daemon on `server.listen` with the client address in `X-Forwarded-For`. Serve mode: `reverse_proxy 127.0.0.1:8080`, the built-in server sends the same headers. nginx equivalent provided.
## Milestones
+69 -5
View File
@@ -3,6 +3,8 @@ package app
import (
"context"
"log"
"net/http"
"net/url"
"os"
"os/signal"
"sync"
@@ -12,7 +14,10 @@ import (
"github.com/luciochen233/luphoto/internal/build"
"github.com/luciochen233/luphoto/internal/config"
"github.com/luciochen233/luphoto/internal/keys"
"github.com/luciochen233/luphoto/internal/process"
"github.com/luciochen233/luphoto/internal/server"
"github.com/luciochen233/luphoto/internal/site"
"github.com/luciochen233/luphoto/internal/watch"
)
@@ -24,7 +29,9 @@ type daemon struct {
logger *log.Logger
cfg atomic.Pointer[config.Config]
builds chan string
keys *keys.Service
handler *server.Handler
root http.Handler
server *server.Server
watchCancel context.CancelFunc
watchDone chan struct{}
@@ -36,6 +43,17 @@ type daemon struct {
func Run(ctx context.Context, mode, configPath string, cfg *config.Config, logger *log.Logger) error {
d := &daemon{mode: mode, configPath: configPath, logger: logger, builds: make(chan string, 1)}
d.cfg.Store(cfg)
siteKey, err := process.SiteKey(cfg.State)
if err != nil {
return err
}
d.keys = keys.New(siteKey, keySettings(cfg))
if mode == "serve" {
d.handler = server.NewHandler(handlerSettings(cfg), d.keys)
d.root = d.handler
} else {
d.root = keys.Only(d.keys)
}
var builder sync.WaitGroup
builder.Add(1)
@@ -45,13 +63,15 @@ func Run(ctx context.Context, mode, configPath string, cfg *config.Config, logge
}()
d.requestBuild("startup")
if mode == "serve" {
d.handler = server.NewHandler(handlerSettings(cfg))
srv, err := server.Start(cfg.Server.Listen, d.handler, logger)
if d.listens(cfg) {
srv, err := server.Start(cfg.Server.Listen, d.root, logger)
if err != nil {
return err
}
d.server = srv
if mode != "serve" {
logger.Printf("export: serving only %s on %s", site.KeyPath, cfg.Server.Listen)
}
}
d.syncWatcher(ctx, cfg)
@@ -76,10 +96,35 @@ func Run(ctx context.Context, mode, configPath string, cfg *config.Config, logge
}
}
func (d *daemon) listens(cfg *config.Config) bool {
return d.mode == "serve" || string(cfg.Protection.Gate) == site.GateServer
}
func handlerSettings(cfg *config.Config) server.Settings {
return server.Settings{Output: cfg.Paths.Output, HotlinkAllow: cfg.Protection.HotlinkAllow}
}
func keySettings(cfg *config.Config) keys.Settings {
trusted, _ := config.ParsePrefixes(cfg.Server.TrustedProxies)
hosts := append([]string(nil), cfg.Protection.HotlinkAllow...)
if u, err := url.Parse(cfg.Server.BaseURL); err == nil && u.Hostname() != "" {
hosts = append(hosts, u.Hostname())
}
p := cfg.Protection
return keys.Settings{
Output: cfg.Paths.Output,
Gate: string(p.Gate),
Hosts: hosts,
Trusted: trusted,
IPHeader: cfg.Server.ClientIPHeader,
PowBits: p.PowBits,
PhotoLimit: p.PhotoLimit,
MinEntropy: p.MinEntropy,
LandingLimit: p.LandingLimit,
Window: p.Window.Duration,
PassTTL: p.PassTTL.Duration,
}
}
func (d *daemon) requestBuild(reason string) {
select {
case d.builds <- reason:
@@ -104,6 +149,7 @@ func (d *daemon) buildLoop(ctx context.Context) {
d.logger.Printf("build failed: %v; previous build stays live", err)
continue
}
d.keys.Reload()
d.logger.Print(summary.String())
}
}
@@ -166,8 +212,25 @@ func (d *daemon) reload(ctx context.Context) {
if next.Server.Mode != previous.Server.Mode {
d.logger.Printf("reload: server.mode changed to %q; restart the service to switch modes", next.Server.Mode)
}
if d.server != nil && next.Server.Listen != previous.Server.Listen {
srv, err := server.Start(next.Server.Listen, d.handler, d.logger)
want := d.listens(next)
switch {
case !want && d.server != nil:
old := d.server
d.server = nil
go func() {
if err := old.Shutdown(shutdownTimeout); err != nil {
d.logger.Printf("reload: closing listener: %v", err)
}
}()
case want && d.server == nil:
srv, err := server.Start(next.Server.Listen, d.root, d.logger)
if err != nil {
d.logger.Printf("reload: cannot listen on %s: %v", next.Server.Listen, err)
} else {
d.server = srv
}
case want && next.Server.Listen != previous.Server.Listen:
srv, err := server.Start(next.Server.Listen, d.root, d.logger)
if err != nil {
d.logger.Printf("reload: cannot listen on %s, keeping %s: %v", next.Server.Listen, previous.Server.Listen, err)
next.Server.Listen = previous.Server.Listen
@@ -185,6 +248,7 @@ func (d *daemon) reload(ctx context.Context) {
if d.handler != nil {
d.handler.Update(handlerSettings(next))
}
d.keys.Update(keySettings(next))
d.syncWatcher(ctx, next)
d.logger.Printf("reload: config %s applied", d.configPath)
d.requestBuild("SIGHUP")
+173 -41
View File
@@ -7,12 +7,14 @@ import (
"errors"
"fmt"
"io"
"io/fs"
"log"
"math"
"os"
"path/filepath"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"time"
@@ -21,6 +23,7 @@ import (
"github.com/luciochen233/luphoto/internal/config"
"github.com/luciochen233/luphoto/internal/fsutil"
"github.com/luciochen233/luphoto/internal/process"
"github.com/luciochen233/luphoto/internal/protect"
"github.com/luciochen233/luphoto/internal/site"
)
@@ -37,6 +40,8 @@ type Summary struct {
BytesWritten int64
BuildsRemoved int
TilesRemoved int
DecoysLinked int
DecoysRemoved int
Duration time.Duration
}
@@ -52,6 +57,7 @@ type albumPlan struct {
failed []string
problem string
manifest *site.Manifest
records []*process.Record
carriedOut bool
}
@@ -241,7 +247,7 @@ func (b *builder) run(ctx context.Context) (*Summary, error) {
}
sum.Cached = len(records) - sum.Processed
id, err := newBuildID()
id, err := b.newBuildID()
if err != nil {
return nil, err
}
@@ -253,8 +259,9 @@ func (b *builder) run(ctx context.Context) (*Summary, error) {
continue
}
sum.Skipped++
if m := b.carryOver(previous, plan.album.Slug, id); m != nil {
if m, recs := b.carryOver(previous, plan.album.Slug, id); m != nil {
plan.manifest = m
plan.records = recs
plan.carriedOut = true
sum.Carried++
b.log.Printf("skip album %s: %s (previous version stays live)", plan.album.Slug, plan.problem)
@@ -263,33 +270,71 @@ func (b *builder) run(ctx context.Context) (*Summary, error) {
}
}
var manifests []*site.Manifest
var published []*albumPlan
for _, plan := range plans {
if plan.manifest != nil {
manifests = append(manifests, plan.manifest)
published = append(published, plan)
}
}
sort.SliceStable(manifests, func(i, j int) bool {
sort.SliceStable(published, func(i, j int) bool {
mi, mj := published[i].manifest, published[j].manifest
return album.Before(
album.SortKey{Order: manifests[i].Order, Date: manifests[i].Date, Slug: manifests[i].Slug},
album.SortKey{Order: manifests[j].Order, Date: manifests[j].Date, Slug: manifests[j].Slug})
album.SortKey{Order: mi.Order, Date: mi.Date, Slug: mi.Slug},
album.SortKey{Order: mj.Order, Date: mj.Date, Slug: mj.Slug})
})
for _, m := range manifests {
if m.Hidden {
manifests := make([]*site.Manifest, len(published))
var lives []*live
seenLive := map[string]bool{}
for i, plan := range published {
manifests[i] = plan.manifest
if plan.manifest.Hidden {
sum.Hidden++
}
for _, rec := range plan.records {
if !seenLive[rec.Hash] {
seenLive[rec.Hash] = true
lives = append(lives, &live{rec: rec, album: i})
}
}
}
sum.Albums = len(manifests)
if err := b.writeBuild(id, manifests); err != nil {
secret, err := protect.NewSecret()
if err != nil {
return nil, err
}
keyer := protect.NewKeyer(secret)
coverKey := keyer.Cover()
covers := make(map[string]bool, len(manifests))
for _, m := range manifests {
covers[m.Cover.Hash] = true
}
keys := make(map[string][32]byte, len(lives))
for _, l := range lives {
if covers[l.rec.Hash] {
keys[l.rec.Hash] = coverKey
} else {
keys[l.rec.Hash] = keyer.Photo(l.rec.Hash)
}
}
poolStart := time.Now()
pools, linked, err := b.pools(lives, keys)
if err != nil {
return nil, fmt.Errorf("decoys: %w", err)
}
sum.DecoysLinked = linked
b.log.Printf("protect: %d pools sealed, %d decoys linked in %s", len(pools), linked, round(time.Since(poolStart)))
if err := b.writeBuild(id, manifests, secret, keys, coverKey, lives, pools); err != nil {
return nil, err
}
if err := fsutil.SymlinkAtomic(filepath.Join("builds", id), b.current); err != nil {
return nil, fmt.Errorf("switch current: %w", err)
}
removedBuilds, removedTiles, err := b.cleanup(id)
removedBuilds, removedTiles, removedDecoys, err := b.cleanup(id)
sum.BuildsRemoved = removedBuilds
sum.TilesRemoved = removedTiles
sum.DecoysRemoved = removedDecoys
if err != nil {
b.log.Printf("cleanup: %v", err)
}
@@ -337,19 +382,10 @@ func coverCrop(c *album.Cover, width, height int) ([4]int, error) {
return [4]int{x, y, max(1, w), max(1, h)}, nil
}
func (b *builder) overlap() int {
if b.cfg.Images.ScrambleCells {
return 0
}
return b.cfg.Images.Overlap
}
func (b *builder) tiles() site.Tiles {
tiles := site.Tiles{
Format: b.cfg.Images.Format,
TileSize: b.cfg.Images.TileSize,
Overlap: b.overlap(),
Path: "/t/",
Format: b.cfg.Images.Format,
Path: "/t/",
}
if b.cfg.Images.ScrambleCells {
tiles.Scrambled = true
@@ -360,7 +396,6 @@ func (b *builder) tiles() site.Tiles {
func (b *builder) manifest(id string, plan *albumPlan, records map[string]*process.Record) *site.Manifest {
a := plan.album
cover := records[plan.coverHash].Pyramid
m := &site.Manifest{
Build: id,
Slug: a.Slug,
@@ -372,14 +407,16 @@ func (b *builder) manifest(id string, plan *albumPlan, records map[string]*proce
CollapsedFocusY: *a.CollapsedFocusY,
ShowEXIF: *a.ShowEXIF,
Tiles: b.tiles(),
Cover: &cover,
Cover: site.Layout(&records[plan.coverHash].Pyramid),
OG: plan.ogHash,
Photos: make([]site.Photo, len(a.Photos)),
}
plan.records = make([]*process.Record, 0, len(a.Photos)+1)
for i, photo := range a.Photos {
rec := records[plan.hashes[i]]
plan.records = append(plan.records, rec)
p := site.Photo{
Pyramid: rec.Pyramid,
Pyramid: *site.Layout(&rec.Pyramid),
Title: photo.Title,
Caption: photo.Caption,
Alt: photo.Alt,
@@ -392,6 +429,7 @@ func (b *builder) manifest(id string, plan *albumPlan, records map[string]*proce
}
m.Photos[i] = p
}
plan.records = append(plan.records, records[plan.coverHash])
return m
}
@@ -407,28 +445,74 @@ func (b *builder) previousBuild() string {
return id
}
func (b *builder) carryOver(previous, slug, id string) *site.Manifest {
func (b *builder) carryOver(previous, slug, id string) (*site.Manifest, []*process.Record) {
if previous == "" {
return nil
return nil, nil
}
var m site.Manifest
path := filepath.Join(b.builds, previous, "a", slug, site.ManifestName(previous))
if err := fsutil.ReadJSON(path, &m); err != nil || m.Slug != slug || m.Tiles != b.tiles() {
return nil
if err := fsutil.ReadJSON(path, &m); err != nil || m.Slug != slug || m.Tiles != b.tiles() || m.Cover == nil {
return nil, nil
}
hashes := make([]string, 0, len(m.Photos)+1)
for _, p := range m.Photos {
hashes = append(hashes, p.Hash)
}
hashes = append(hashes, m.Cover.Hash)
records := make([]*process.Record, len(hashes))
for i, hash := range hashes {
rec, ok := b.proc.Lookup(hash)
if !ok || len(rec.Levels) == 0 {
return nil, nil
}
for _, level := range rec.Levels {
if level.TileSize <= 0 || len(level.Tiles) != level.Cols*level.Rows {
return nil, nil
}
}
records[i] = rec
}
m.Build = id
return &m
return &m, records
}
func newBuildID() (string, error) {
func buildStamp(t time.Time) string {
return t.Format("20060102-150405") + fmt.Sprintf("-%06d", t.Nanosecond()/1000)
}
func (b *builder) newBuildID() (string, error) {
var suffix [3]byte
if _, err := rand.Read(suffix[:]); err != nil {
return "", err
}
return time.Now().UTC().Format("20060102-150405") + "-" + hex.EncodeToString(suffix[:]), nil
t := time.Now().UTC().Truncate(time.Microsecond)
if entries, err := os.ReadDir(b.builds); err == nil {
for _, entry := range entries {
if last, ok := parseStamp(entry.Name()); ok && !t.After(last) {
t = last.Add(time.Microsecond)
}
}
}
return buildStamp(t) + "-" + hex.EncodeToString(suffix[:]), nil
}
func (b *builder) writeBuild(id string, manifests []*site.Manifest) error {
func parseStamp(name string) (time.Time, bool) {
if len(name) < 15 {
return time.Time{}, false
}
t, err := time.Parse("20060102-150405", name[:15])
if err != nil {
return time.Time{}, false
}
if len(name) >= 23 && name[15] == '-' && name[22] == '-' {
if micro, err := strconv.Atoi(name[16:22]); err == nil {
return t.Add(time.Duration(micro) * time.Microsecond), true
}
}
return t.Add(time.Second - time.Microsecond), true
}
func (b *builder) writeBuild(id string, manifests []*site.Manifest, secret []byte, keys map[string][32]byte, coverKey [32]byte, lives []*live, pools map[string]*pool) error {
stage := fsutil.TempName(filepath.Join(b.builds, id))
if err := os.MkdirAll(filepath.Join(stage, "a"), 0o755); err != nil {
return err
@@ -454,11 +538,34 @@ func (b *builder) writeBuild(id string, manifests []*site.Manifest) error {
MaxDPR: b.cfg.Loading.MaxDPR,
Concurrency: b.cfg.Loading.Concurrency,
BlockContextMenu: b.cfg.Protection.BlockContextMenu,
Gate: string(b.cfg.Protection.Gate),
MinEntropy: b.cfg.Protection.MinEntropy,
BaseURL: strings.TrimRight(b.cfg.Server.BaseURL, "/"),
}
index := &site.Index{Build: id, Tiles: b.tiles(), Albums: []site.IndexAlbum{}}
public := &site.Gate{Build: id, Mode: page.Gate, Cover: hex.EncodeToString(coverKey[:]), MinEntropy: page.MinEntropy}
if err := fsutil.WriteFileAtomic(filepath.Join(stage, protect.SecretName), secret, 0o600); err != nil {
return err
}
if err := fsutil.WriteFileAtomic(filepath.Join(stage, "robots.txt"), []byte(site.Robots), 0o644); err != nil {
return err
}
if err := writeRefs(filepath.Join(stage, refsName), lives, pools); err != nil {
return err
}
index := &site.Index{Build: id, Tiles: b.tiles(), Gate: public, Albums: []site.IndexAlbum{}}
for _, m := range manifests {
m.Gate = public
if public.Mode == site.GateOff {
open := *public
open.Keys = make(map[string]string, len(m.Photos))
for _, p := range m.Photos {
k := keys[p.Hash]
open.Keys[p.Hash] = hex.EncodeToString(k[:])
}
m.Gate = &open
}
if m.Hidden {
continue
}
@@ -485,10 +592,22 @@ func (b *builder) writeBuild(id string, manifests []*site.Manifest) error {
limit <- struct{}{}
defer func() { <-limit }()
dir := filepath.Join(stage, "a", m.Slug)
if err := os.MkdirAll(dir, 0o755); err != nil {
poolDir := filepath.Join(dir, site.PoolDir)
if err := os.MkdirAll(poolDir, 0o755); err != nil {
errs[i] = err
return
}
hashes := make([]string, 0, len(m.Photos)+1)
for _, p := range m.Photos {
hashes = append(hashes, p.Hash)
}
hashes = append(hashes, m.Cover.Hash)
for _, hash := range hashes {
if err := fsutil.WritePublic(filepath.Join(poolDir, site.PoolName(id, hash)), pools[hash].data); err != nil {
errs[i] = err
return
}
}
data, err := fsutil.EncodeJSON(m)
if err == nil {
err = fsutil.WritePublicAtomic(filepath.Join(dir, site.ManifestName(id)), data)
@@ -538,10 +657,10 @@ func (b *builder) writeBuild(id string, manifests []*site.Manifest) error {
return nil
}
func (b *builder) cleanup(id string) (int, int, error) {
func (b *builder) cleanup(id string) (int, int, int, error) {
entries, err := os.ReadDir(b.builds)
if err != nil {
return 0, 0, err
return 0, 0, 0, err
}
var names []string
for _, entry := range entries {
@@ -578,7 +697,7 @@ func (b *builder) cleanup(id string) (int, int, error) {
for _, name := range kept {
if err := collectRefs(filepath.Join(b.builds, name), name, refs, ogRefs); err != nil {
errs = append(errs, fmt.Errorf("build %s unreadable, keeping all tiles: %w", name, err))
return removed, 0, errors.Join(errs...)
return removed, 0, 0, errors.Join(errs...)
}
}
tilesRemoved, err := b.proc.ForgetUnreferenced(refs)
@@ -588,7 +707,20 @@ func (b *builder) cleanup(id string) (int, int, error) {
if _, err := b.proc.ForgetOG(ogRefs); err != nil {
errs = append(errs, err)
}
return removed, tilesRemoved, errors.Join(errs...)
pooled := map[uint64][]uint64{}
for _, name := range kept {
if err := readRefs(filepath.Join(b.builds, name, refsName), pooled); err != nil {
if !errors.Is(err, fs.ErrNotExist) {
errs = append(errs, fmt.Errorf("build %s pool list unreadable, keeping all decoys: %w", name, err))
}
return removed, tilesRemoved, 0, errors.Join(errs...)
}
}
decoysRemoved, err := b.sweepDecoys(pooled)
if err != nil {
errs = append(errs, err)
}
return removed, tilesRemoved, decoysRemoved, errors.Join(errs...)
}
type pyramidRef struct {
@@ -658,6 +790,6 @@ func megabytes(n int64) string {
}
func (s *Summary) String() string {
return fmt.Sprintf("build %s: %d albums (%d hidden, %d skipped, %d kept from previous build), %d pyramids processed (%d tiles, %s), %d cached, %d failed; removed %d old builds and %d tile folders; %s total",
s.ID, s.Albums, s.Hidden, s.Skipped, s.Carried, s.Processed, s.TilesWritten, megabytes(s.BytesWritten), s.Cached, s.Failed, s.BuildsRemoved, s.TilesRemoved, round(s.Duration))
return fmt.Sprintf("build %s: %d albums (%d hidden, %d skipped, %d kept from previous build), %d pyramids processed (%d tiles, %s), %d cached, %d failed, %d decoys linked; removed %d old builds, %d tile folders and %d stale decoys; %s total",
s.ID, s.Albums, s.Hidden, s.Skipped, s.Carried, s.Processed, s.TilesWritten, megabytes(s.BytesWritten), s.Cached, s.Failed, s.DecoysLinked, s.BuildsRemoved, s.TilesRemoved, s.DecoysRemoved, round(s.Duration))
}
+426
View File
@@ -0,0 +1,426 @@
package build
import (
"bufio"
"encoding/binary"
"errors"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"runtime"
"slices"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"github.com/luciochen233/luphoto/internal/fsutil"
"github.com/luciochen233/luphoto/internal/process"
"github.com/luciochen233/luphoto/internal/protect"
"github.com/luciochen233/luphoto/internal/site"
)
const refsName = ".refs"
type live struct {
rec *process.Record
album int
}
type sourceTile struct {
pos uint64
owner int32
level int16
index int32
}
type bucket struct {
size int
tiles []sourceTile
byAlbum map[int]int
byOwner map[int32]int
}
type decoyIndex struct {
lives []*live
buckets []*bucket
}
type pool struct {
data []byte
ids []uint64
}
type splitmix struct {
s uint64
}
func (r *splitmix) next() uint64 {
r.s += 0x9e3779b97f4a7c15
z := r.s
z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9
z = (z ^ (z >> 27)) * 0x94d049bb133111eb
return z ^ (z >> 31)
}
func (r *splitmix) intn(n int) int {
return int(r.next() % uint64(n))
}
func newDecoyIndex(lives []*live) *decoyIndex {
idx := &decoyIndex{lives: lives}
bySize := map[int]*bucket{}
for owner, l := range lives {
for li, level := range l.rec.Levels {
b := bySize[level.TileSize]
if b == nil {
b = &bucket{size: level.TileSize, byAlbum: map[int]int{}, byOwner: map[int32]int{}}
bySize[level.TileSize] = b
idx.buckets = append(idx.buckets, b)
}
for i, id := range level.Tiles {
pos, err := strconv.ParseUint(id, 16, 64)
if err != nil {
continue
}
b.tiles = append(b.tiles, sourceTile{pos: pos, owner: int32(owner), level: int16(li), index: int32(i)})
b.byAlbum[l.album]++
b.byOwner[int32(owner)]++
}
}
}
for _, b := range idx.buckets {
slices.SortFunc(b.tiles, func(x, y sourceTile) int {
switch {
case x.pos < y.pos:
return -1
case x.pos > y.pos:
return 1
}
return 0
})
}
sort.Slice(idx.buckets, func(i, j int) bool { return idx.buckets[i].size < idx.buckets[j].size })
return idx
}
type tier func(t sourceTile) bool
func (idx *decoyIndex) pick(owner int32, size int) (*bucket, tier, int) {
album := idx.lives[owner].album
tiers := []struct {
eligible func(b *bucket) int
accept tier
}{
{func(b *bucket) int { return len(b.tiles) - b.byAlbum[album] }, func(t sourceTile) bool { return idx.lives[t.owner].album != album }},
{func(b *bucket) int { return len(b.tiles) - b.byOwner[owner] }, func(t sourceTile) bool { return t.owner != owner }},
{func(b *bucket) int { return b.byOwner[owner] }, func(t sourceTile) bool { return t.owner == owner }},
}
for _, t := range tiers {
var best *bucket
bestCount, bestDistance := 0, 0
for _, b := range idx.buckets {
n := t.eligible(b)
if n == 0 {
continue
}
d := b.size - size
if d < 0 {
d = -d
}
if best == nil || d < bestDistance {
best, bestCount, bestDistance = b, n, d
}
}
if best != nil {
return best, t.accept, bestCount
}
}
return nil, nil, 0
}
func (b *builder) pools(lives []*live, keys map[string][32]byte) (map[string]*pool, int, error) {
idx := newDecoyIndex(lives)
out := make([]*pool, len(lives))
errs := make([]error, len(lives))
var linked atomic.Int64
var next atomic.Int64
var wg sync.WaitGroup
for w := 0; w < min(runtime.NumCPU(), len(lives)); w++ {
wg.Add(1)
go func() {
defer wg.Done()
keyed := b.proc.Keyed()
for {
i := int(next.Add(1) - 1)
if i >= len(lives) {
return
}
p, n, err := b.pool(idx, int32(i), keyed, keys[lives[i].rec.Hash])
out[i], errs[i] = p, err
linked.Add(int64(n))
}
}()
}
wg.Wait()
if err := errors.Join(errs...); err != nil {
return nil, 0, err
}
pools := make(map[string]*pool, len(lives))
for i, l := range lives {
pools[l.rec.Hash] = out[i]
}
return pools, int(linked.Load()), nil
}
type link struct {
name string
source string
}
func (b *builder) pool(idx *decoyIndex, owner int32, keyed *process.Keyed, key [32]byte) (*pool, int, error) {
rec := idx.lives[owner].rec
hash := rec.Hash
decoys := b.cfg.Protection.Decoys
public := site.Pool{Levels: make([]string, len(rec.Levels))}
sealed := site.Sealed{Seed: rec.Seed, Scramble: rec.Scramble, Levels: make([]site.SealedLevel, len(rec.Levels))}
var links []link
var ids []uint64
used := map[int]bool{}
for li, level := range rec.Levels {
real := len(level.Tiles)
entries := make([]string, real, real*(decoys+1))
copy(entries, level.Tiles)
if decoys > 0 {
src, accept, eligible := idx.pick(owner, level.TileSize)
if src != nil {
clear(used)
rng := splitmix{s: keyed.Seed("pick", hash, li)}
for slot := 0; slot < decoys*real; slot++ {
if len(used) >= eligible {
clear(used)
}
target := rng.next()
at := sort.Search(len(src.tiles), func(i int) bool { return src.tiles[i].pos >= target }) % len(src.tiles)
for step := 0; step < len(src.tiles); step++ {
j := (at + step) % len(src.tiles)
if !used[j] && accept(src.tiles[j]) {
at = j
break
}
}
used[at] = true
t := src.tiles[at]
from := idx.lives[t.owner].rec
sourceID := from.Levels[t.level].Tiles[t.index]
name := keyed.DecoyName(hash, li, slot, sourceID)
entries = append(entries, name)
links = append(links, link{name: name, source: filepath.Join(from.Hash, sourceID)})
}
}
}
rng := splitmix{s: keyed.Seed("pool", hash, li)}
order := make([]int32, len(entries))
for i := range order {
order[i] = int32(i)
}
for i := len(order) - 1; i > 0; i-- {
j := rng.intn(i + 1)
order[i], order[j] = order[j], order[i]
}
var text strings.Builder
text.Grow(len(entries) * 16)
m := make([]int32, real)
for at, from := range order {
text.WriteString(entries[from])
if int(from) < real {
m[from] = int32(at)
}
if v, err := strconv.ParseUint(entries[from], 16, 64); err == nil {
ids = append(ids, v)
}
}
public.Levels[li] = text.String()
sealed.Levels[li] = site.SealedLevel{Map: m, Bytes: level.Bytes}
}
made, err := b.link(hash, links)
if err != nil {
return nil, made, err
}
plain, err := fsutil.EncodeJSON(sealed)
if err != nil {
return nil, made, err
}
public.Sealed, err = protect.Seal(key, plain)
if err != nil {
return nil, made, err
}
data, err := fsutil.EncodeJSON(public)
if err != nil {
return nil, made, err
}
return &pool{data: data, ids: ids}, made, nil
}
func (b *builder) link(hash string, links []link) (int, error) {
if len(links) == 0 {
return 0, nil
}
dir := filepath.Join(b.proc.TilesDir, hash)
entries, err := os.ReadDir(dir)
if err != nil {
return 0, err
}
ext := b.proc.Ext()
have := make(map[string]bool, len(entries))
for _, entry := range entries {
have[entry.Name()] = true
}
made := 0
for _, l := range links {
name := l.name + ext
if have[name] {
continue
}
have[name] = true
target := filepath.Join(dir, name)
source := filepath.Join(b.proc.TilesDir, l.source+ext)
if err := os.Link(source, target); err != nil {
if errors.Is(err, fs.ErrExist) {
continue
}
if err := copyFile(source, target); err != nil {
return made, fmt.Errorf("decoy %s: %w", name, err)
}
}
made++
}
return made, nil
}
func copyFile(source, target string) error {
in, err := os.Open(source)
if err != nil {
return err
}
defer in.Close()
return fsutil.WriteAtomic(target, 0o644, func(w io.Writer) error {
_, err := io.Copy(w, in)
return err
})
}
func writeRefs(path string, lives []*live, pools map[string]*pool) error {
return fsutil.WriteAtomic(path, 0o644, func(w io.Writer) error {
var head [12]byte
var word [8]byte
for _, l := range lives {
h, err := strconv.ParseUint(l.rec.Hash, 16, 64)
if err != nil {
return err
}
ids := pools[l.rec.Hash].ids
binary.LittleEndian.PutUint64(head[:8], h)
binary.LittleEndian.PutUint32(head[8:], uint32(len(ids)))
if _, err := w.Write(head[:]); err != nil {
return err
}
for _, id := range ids {
binary.LittleEndian.PutUint64(word[:], id)
if _, err := w.Write(word[:]); err != nil {
return err
}
}
}
return nil
})
}
func readRefs(path string, into map[uint64][]uint64) error {
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close()
r := bufio.NewReaderSize(f, 256<<10)
var head [12]byte
for {
if _, err := io.ReadFull(r, head[:]); err != nil {
if errors.Is(err, io.EOF) {
return nil
}
return err
}
h := binary.LittleEndian.Uint64(head[:8])
n := int(binary.LittleEndian.Uint32(head[8:]))
buf := make([]byte, n*8)
if _, err := io.ReadFull(r, buf); err != nil {
return err
}
ids := into[h]
for i := 0; i < n; i++ {
ids = append(ids, binary.LittleEndian.Uint64(buf[i*8:]))
}
into[h] = ids
}
}
func (b *builder) sweepDecoys(refs map[uint64][]uint64) (int, error) {
hashes := make([]uint64, 0, len(refs))
for h := range refs {
hashes = append(hashes, h)
}
ext := b.proc.Ext()
var removed atomic.Int64
var next atomic.Int64
errs := make([]error, runtime.NumCPU())
var wg sync.WaitGroup
for w := range errs {
wg.Add(1)
go func(w int) {
defer wg.Done()
for {
i := int(next.Add(1) - 1)
if i >= len(hashes) {
return
}
keep := refs[hashes[i]]
slices.Sort(keep)
dir := filepath.Join(b.proc.TilesDir, fmt.Sprintf("%016x", hashes[i]))
entries, err := os.ReadDir(dir)
if err != nil {
if !errors.Is(err, fs.ErrNotExist) && errs[w] == nil {
errs[w] = err
}
continue
}
for _, entry := range entries {
name := entry.Name()
id, ok := strings.CutSuffix(name, ext)
if !ok || len(id) != 16 {
continue
}
v, err := strconv.ParseUint(id, 16, 64)
if err != nil {
continue
}
if _, found := slices.BinarySearch(keep, v); found {
continue
}
if err := os.Remove(filepath.Join(dir, name)); err != nil {
if errs[w] == nil {
errs[w] = err
}
continue
}
removed.Add(1)
}
}
}(w)
}
wg.Wait()
return int(removed.Load()), errors.Join(errs...)
}
+118 -13
View File
@@ -4,6 +4,7 @@ import (
"errors"
"fmt"
"io/fs"
"net/netip"
"os"
"path/filepath"
"sort"
@@ -28,9 +29,11 @@ type Config struct {
}
type Server struct {
Mode string `toml:"mode"`
Listen string `toml:"listen"`
BaseURL string `toml:"base_url"`
Mode string `toml:"mode"`
Listen string `toml:"listen"`
BaseURL string `toml:"base_url"`
TrustedProxies []string `toml:"trusted_proxies"`
ClientIPHeader string `toml:"client_ip_header"`
}
type Paths struct {
@@ -54,6 +57,7 @@ type Images struct {
SeedPx int `toml:"seed_px"`
TileNames string `toml:"tile_names"`
ScrambleCells bool `toml:"scramble_cells"`
MinGrid int `toml:"min_grid"`
}
type Loading struct {
@@ -72,6 +76,32 @@ type Build struct {
type Protection struct {
BlockContextMenu bool `toml:"block_context_menu"`
HotlinkAllow []string `toml:"hotlink_allow"`
Decoys int `toml:"decoys"`
Gate GateMode `toml:"gate"`
PowBits int `toml:"pow_bits"`
PhotoLimit int `toml:"photo_limit"`
MinEntropy int `toml:"min_entropy"`
LandingLimit int `toml:"landing_limit"`
Window Duration `toml:"window"`
PassTTL Duration `toml:"pass_ttl"`
}
type GateMode string
func (g *GateMode) UnmarshalTOML(value any) error {
switch v := value.(type) {
case string:
*g = GateMode(strings.TrimSpace(v))
case bool:
if v {
*g = "server"
} else {
*g = "off"
}
default:
return fmt.Errorf("protection.gate must be \"server\" or \"off\"")
}
return nil
}
type Duration struct {
@@ -94,21 +124,25 @@ func (d Duration) MarshalText() ([]byte, error) {
func Defaults() Config {
return Config{
Server: Server{
Mode: "export",
Listen: "127.0.0.1:8080",
BaseURL: "https://photos.luciochen.com",
Mode: "export",
Listen: "127.0.0.1:8080",
BaseURL: "https://photos.luciochen.com",
TrustedProxies: []string{"127.0.0.1/32", "::1/128"},
ClientIPHeader: "X-Forwarded-For",
},
Paths: Paths{
Albums: "/srv/luphoto/albums",
},
Images: Images{
TileSize: 512,
Overlap: 1,
Format: "webp",
Quality: Quality{Top: 82, Mid: 85, Low: 88},
MinLevels: 6,
SeedPx: 48,
TileNames: "hashed",
TileSize: 512,
Overlap: 1,
Format: "webp",
Quality: Quality{Top: 90, Mid: 88, Low: 88},
MinLevels: 6,
SeedPx: 48,
TileNames: "hashed",
ScrambleCells: true,
MinGrid: 3,
},
Loading: Loading{
BudgetMS: 3000,
@@ -124,6 +158,14 @@ func Defaults() Config {
Protection: Protection{
BlockContextMenu: true,
HotlinkAllow: []string{"photos.luciochen.com"},
Decoys: 4,
Gate: "server",
PowBits: 20,
PhotoLimit: 400,
MinEntropy: 20,
LandingLimit: 5,
Window: Duration{10 * time.Minute},
PassTTL: Duration{12 * time.Hour},
},
}
}
@@ -255,6 +297,9 @@ func (c *Config) Validate() error {
if img.TileNames != "hashed" {
add("images.tile_names must be \"hashed\"")
}
if img.MinGrid < 1 || img.MinGrid > 8 {
add("images.min_grid must be between 1 and 8")
}
if c.Loading.BudgetMS < 100 {
add("loading.budget_ms must be at least 100")
}
@@ -273,6 +318,41 @@ func (c *Config) Validate() error {
if c.Build.KeepBuilds < 1 {
add("build.keep_builds must be at least 1")
}
if c.Protection.Decoys < 0 || c.Protection.Decoys > 16 {
add("protection.decoys must be between 0 and 16")
}
p := c.Protection
switch p.Gate {
case "server", "off":
default:
add("protection.gate must be \"server\" or \"off\", got %q", p.Gate)
}
if p.PowBits < 10 || p.PowBits > 26 {
add("protection.pow_bits must be between 10 and 26")
}
if p.PhotoLimit < 1 || p.PhotoLimit > 1000000 {
add("protection.photo_limit must be between 1 and 1000000")
}
if p.MinEntropy < 0 || p.MinEntropy > 100 {
add("protection.min_entropy must be between 0 and 100")
}
if p.LandingLimit < 1 || p.LandingLimit > 10000 {
add("protection.landing_limit must be between 1 and 10000")
}
if p.Window.Duration < time.Minute || p.Window.Duration > 24*time.Hour {
add("protection.window must be between 1m and 24h")
}
if p.PassTTL.Duration < time.Minute || p.PassTTL.Duration > 30*24*time.Hour {
add("protection.pass_ttl must be between 1m and 720h")
}
if _, err := ParsePrefixes(c.Server.TrustedProxies); err != nil {
add("server.trusted_proxies: %v", err)
}
if h := c.Server.ClientIPHeader; h != "" && strings.IndexFunc(h, func(r rune) bool {
return !(r == '-' || r >= '0' && r <= '9' || r >= 'A' && r <= 'Z' || r >= 'a' && r <= 'z')
}) >= 0 {
add("server.client_ip_header %q is not a header name", h)
}
for _, host := range c.Protection.HotlinkAllow {
if host == "" || strings.ContainsAny(host, "/ ") {
add("protection.hotlink_allow entry %q is not a host name", host)
@@ -284,6 +364,31 @@ func (c *Config) Validate() error {
return nil
}
func ParsePrefixes(values []string) ([]netip.Prefix, error) {
out := make([]netip.Prefix, 0, len(values))
for _, value := range values {
value = strings.TrimSpace(value)
if strings.Contains(value, "/") {
prefix, err := netip.ParsePrefix(value)
if err != nil {
return nil, fmt.Errorf("%q is not a CIDR", value)
}
if prefix.Addr().Is4In6() {
prefix = netip.PrefixFrom(prefix.Addr().Unmap(), max(0, prefix.Bits()-96))
}
out = append(out, prefix.Masked())
continue
}
addr, err := netip.ParseAddr(value)
if err != nil {
return nil, fmt.Errorf("%q is not an address or CIDR", value)
}
addr = addr.Unmap()
out = append(out, netip.PrefixFrom(addr, addr.BitLen()))
}
return out, nil
}
func within(parent, child string) bool {
rel, err := filepath.Rel(parent, child)
if err != nil {
+18
View File
@@ -117,3 +117,21 @@ func WritePublicAtomic(path string, data []byte) error {
return zw.Close()
})
}
func WritePublic(path string, data []byte) error {
if err := os.WriteFile(path, data, 0o644); err != nil {
return err
}
var buf bytes.Buffer
zw, err := gzip.NewWriterLevel(&buf, gzip.BestCompression)
if err != nil {
return err
}
if _, err := zw.Write(data); err != nil {
return err
}
if err := zw.Close(); err != nil {
return err
}
return os.WriteFile(path+".gz", buf.Bytes(), 0o644)
}
+127
View File
@@ -0,0 +1,127 @@
package keys
import (
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/luciochen233/luphoto/internal/fsutil"
"github.com/luciochen233/luphoto/internal/protect"
"github.com/luciochen233/luphoto/internal/site"
)
const (
rescanEvery = 2 * time.Second
albumCache = 4096
)
type album map[string]struct{}
type buildInfo struct {
id string
dir string
secret []byte
mu sync.Mutex
albums map[string]album
}
type builds struct {
mu sync.RWMutex
root string
byID map[string]*buildInfo
scanned time.Time
}
func validID(id string) bool {
if id == "" || len(id) > 64 {
return false
}
for i := 0; i < len(id); i++ {
c := id[i]
if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'f' || c == '-') {
return false
}
}
return true
}
func validSlug(slug string) bool {
return slug != "" && len(slug) <= 255 && !strings.HasPrefix(slug, ".") && !strings.ContainsAny(slug, "/\\\x00")
}
func (b *builds) reload(root string) {
next := map[string]*buildInfo{}
b.mu.RLock()
old := b.byID
same := b.root == root
b.mu.RUnlock()
dir := filepath.Join(root, "builds")
entries, _ := os.ReadDir(dir)
for _, entry := range entries {
id := entry.Name()
if !entry.IsDir() || !validID(id) {
continue
}
if info, ok := old[id]; ok && same {
next[id] = info
continue
}
secret, err := protect.ReadSecret(filepath.Join(dir, id))
if err != nil {
continue
}
next[id] = &buildInfo{id: id, dir: filepath.Join(dir, id), secret: secret, albums: map[string]album{}}
}
b.mu.Lock()
b.root = root
b.byID = next
b.scanned = time.Now()
b.mu.Unlock()
}
func (b *builds) get(root, id string) *buildInfo {
if !validID(id) {
return nil
}
b.mu.RLock()
info := b.byID[id]
fresh := time.Since(b.scanned) < rescanEvery && b.root == root
b.mu.RUnlock()
if info != nil || fresh {
return info
}
b.reload(root)
b.mu.RLock()
info = b.byID[id]
b.mu.RUnlock()
return info
}
func (info *buildInfo) album(slug string) album {
if !validSlug(slug) {
return nil
}
info.mu.Lock()
defer info.mu.Unlock()
if a, ok := info.albums[slug]; ok {
return a
}
var m struct {
Photos []struct {
Hash string `json:"hash"`
} `json:"photos"`
}
var a album
if err := fsutil.ReadJSON(filepath.Join(info.dir, "a", slug, site.ManifestName(info.id)), &m); err == nil {
a = make(album, len(m.Photos))
for _, p := range m.Photos {
a[p.Hash] = struct{}{}
}
}
if a != nil || len(info.albums) < albumCache {
info.albums[slug] = a
}
return a
}
+448
View File
@@ -0,0 +1,448 @@
package keys
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/binary"
"encoding/hex"
"encoding/json"
"hash"
"net"
"net/http"
"net/netip"
"net/url"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/luciochen233/luphoto/internal/protect"
"github.com/luciochen233/luphoto/internal/site"
)
const (
bodyLimit = 4 << 10
maxPhotos = 8
tokenRaw = 24
tokenLen = 32
macLen = tokenRaw - 5
challengeTTL = 5 * time.Minute
clockSkew = 30 * time.Second
usedCapacity = 1 << 15
maxNonce = 1 << 53
contextNav = "nav"
contextLand = "land"
challengeKind = 'c'
passKind = 'p'
pageKind = 'g'
pageTTL = 30 * time.Minute
)
type Settings struct {
Output string
Gate string
Hosts []string
Trusted []netip.Prefix
IPHeader string
PowBits int
PhotoLimit int
MinEntropy int
LandingLimit int
Window time.Duration
PassTTL time.Duration
}
type Service struct {
settings atomic.Pointer[Settings]
table atomic.Pointer[table]
macs sync.Pool
builds builds
used used
}
type used struct {
mu sync.Mutex
seen map[[macLen]byte]struct{}
ring [][macLen]byte
next int
}
func (u *used) add(mac [macLen]byte) bool {
u.mu.Lock()
defer u.mu.Unlock()
if _, ok := u.seen[mac]; ok {
return false
}
if len(u.ring) < usedCapacity {
u.ring = append(u.ring, mac)
} else {
delete(u.seen, u.ring[u.next])
u.ring[u.next] = mac
u.next = (u.next + 1) % usedCapacity
}
u.seen[mac] = struct{}{}
return true
}
func New(siteKey []byte, settings Settings) *Service {
s := &Service{}
key := append([]byte(nil), siteKey...)
s.macs.New = func() any { return hmac.New(sha256.New, key) }
s.used.seen = make(map[[macLen]byte]struct{})
s.Update(settings)
return s
}
func (s *Service) Update(settings Settings) {
hosts := make([]string, 0, len(settings.Hosts))
for _, h := range settings.Hosts {
if h = strings.ToLower(strings.TrimSpace(h)); h != "" {
hosts = append(hosts, h)
}
}
settings.Hosts = hosts
previous := s.settings.Swap(&settings)
if previous == nil || previous.Window != settings.Window || s.table.Load() == nil {
s.table.Store(newTable(settings.Window))
}
if previous == nil || previous.Output != settings.Output {
s.builds.reload(settings.Output)
}
}
func (s *Service) Reload() {
if set := s.settings.Load(); set != nil {
s.builds.reload(set.Output)
}
}
func (s *Service) sign(kind byte, bucket [16]byte, head []byte, scope ...string) [32]byte {
mac := s.macs.Get().(hash.Hash)
mac.Reset()
var buf [1 + 16 + 5]byte
buf[0] = kind
copy(buf[1:], bucket[:])
copy(buf[17:], head)
mac.Write(buf[:])
for _, part := range scope {
mac.Write([]byte{0})
mac.Write([]byte(part))
}
var out [32]byte
mac.Sum(out[:0])
s.macs.Put(mac)
return out
}
func (s *Service) token(kind byte, bucket [16]byte, stamp uint32, extra byte, scope ...string) string {
var raw [tokenRaw]byte
binary.BigEndian.PutUint32(raw[:4], stamp)
raw[4] = extra
sum := s.sign(kind, bucket, raw[:5], scope...)
copy(raw[5:], sum[:macLen])
return base64.RawURLEncoding.EncodeToString(raw[:])
}
func (s *Service) open(kind byte, bucket [16]byte, text string, scope ...string) (uint32, byte, [macLen]byte, bool) {
var raw [tokenRaw]byte
var mac [macLen]byte
if len(text) != tokenLen {
return 0, 0, mac, false
}
if n, err := base64.RawURLEncoding.Decode(raw[:], []byte(text)); err != nil || n != tokenRaw {
return 0, 0, mac, false
}
sum := s.sign(kind, bucket, raw[:5], scope...)
if !hmac.Equal(sum[:macLen], raw[5:]) {
return 0, 0, mac, false
}
copy(mac[:], raw[5:])
return binary.BigEndian.Uint32(raw[:4]), raw[4], mac, true
}
func (s *Service) passValid(bucket [16]byte, text string, now time.Time, ttl time.Duration) bool {
expiry, _, _, ok := s.open(passKind, bucket, text)
if !ok {
return false
}
at := time.Unix(int64(expiry), 0)
return now.Before(at) && at.Sub(now) <= ttl+clockSkew
}
func (s *Service) pageValid(bucket [16]byte, text, build, album string, now time.Time) bool {
if text == "" {
return false
}
expiry, _, _, ok := s.open(pageKind, bucket, text, build, album)
if !ok {
return false
}
at := time.Unix(int64(expiry), 0)
return now.Before(at) && at.Sub(now) <= pageTTL+clockSkew
}
func (s *Service) solved(bucket [16]byte, c *challengeAnswer, now time.Time) bool {
if c == nil || c.Nonce > maxNonce {
return false
}
issued, bits, mac, ok := s.open(challengeKind, bucket, c.Token)
if !ok || bits < 1 || bits > 32 {
return false
}
at := time.Unix(int64(issued), 0)
if now.Sub(at) > challengeTTL || at.Sub(now) > clockSkew {
return false
}
var msg [tokenLen + 8]byte
copy(msg[:], c.Token)
binary.BigEndian.PutUint64(msg[tokenLen:], c.Nonce)
sum := sha256.Sum256(msg[:])
if binary.BigEndian.Uint32(sum[:4])>>(32-uint(bits)) != 0 {
return false
}
return s.used.add(mac)
}
type challengeAnswer struct {
Token string `json:"token"`
Nonce uint64 `json:"nonce"`
}
type request struct {
Build string `json:"build"`
Album string `json:"album"`
Photos []string `json:"photos"`
Context string `json:"context"`
Entropy float64 `json:"entropy"`
Pass string `json:"pass"`
Page string `json:"page"`
Challenge *challengeAnswer `json:"challenge"`
}
type granted struct {
Keys map[string]string `json:"keys"`
Pass string `json:"pass,omitempty"`
Page string `json:"page,omitempty"`
Stale bool `json:"stale,omitempty"`
}
type puzzle struct {
Token string `json:"token"`
Bits int `json:"bits"`
}
type challenged struct {
Challenge puzzle `json:"challenge"`
Stale bool `json:"stale,omitempty"`
}
type failure struct {
Error string `json:"error"`
}
func reply(w http.ResponseWriter, status int, body any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
enc := json.NewEncoder(w)
enc.SetEscapeHTML(false)
_ = enc.Encode(body)
}
func (s *Service) ServeHTTP(w http.ResponseWriter, r *http.Request) {
header := w.Header()
header.Set("Cache-Control", "no-store")
set := s.settings.Load()
if set.Gate != site.GateServer {
reply(w, http.StatusNotFound, failure{"off"})
return
}
if r.Method != http.MethodPost {
header.Set("Allow", "POST")
reply(w, http.StatusMethodNotAllowed, failure{"method"})
return
}
if !allowedOrigin(r, set.Hosts) {
reply(w, http.StatusForbidden, failure{"origin"})
return
}
r.Body = http.MaxBytesReader(w, r.Body, bodyLimit)
var req request
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
reply(w, http.StatusBadRequest, failure{"body"})
return
}
if len(req.Photos) > maxPhotos || (req.Context != contextNav && req.Context != contextLand) || !(req.Entropy >= 0 && req.Entropy <= 100) {
reply(w, http.StatusBadRequest, failure{"request"})
return
}
info := s.builds.get(set.Output, req.Build)
if info == nil {
reply(w, http.StatusBadRequest, failure{"build"})
return
}
members := info.album(req.Album)
if members == nil {
reply(w, http.StatusBadRequest, failure{"album"})
return
}
photos := req.Photos[:0]
for _, h := range req.Photos {
if _, ok := members[h]; !ok {
continue
}
dup := false
for _, seen := range photos {
if seen == h {
dup = true
break
}
}
if !dup {
photos = append(photos, h)
}
}
now := time.Now()
bucket := bucketOf(clientIP(r, set))
pass := req.Pass != "" && s.passValid(bucket, req.Pass, now, set.PassTTL)
stale := req.Pass != "" && !pass
page := s.pageValid(bucket, req.Page, req.Build, req.Album, now)
solved := s.solved(bucket, req.Challenge, now)
out := s.table.Load().decide(bucket, now, input{
nav: req.Context == contextNav,
low: req.Entropy < float64(set.MinEntropy),
pass: pass,
page: page,
solved: solved,
photos: len(photos),
photoLimit: set.PhotoLimit,
landings: set.LandingLimit,
powBits: set.PowBits,
})
switch out.verdict {
case limited:
header.Set("Retry-After", strconv.Itoa(max(1, int((out.retry+time.Second-1)/time.Second))))
reply(w, http.StatusTooManyRequests, failure{"limit"})
case challenge:
reply(w, http.StatusOK, challenged{Challenge: puzzle{Token: s.token(challengeKind, bucket, uint32(now.Unix()), byte(out.bits)), Bits: out.bits}, Stale: stale})
default:
body := granted{Keys: make(map[string]string, len(photos)), Stale: stale && !solved}
keyer := protect.NewKeyer(info.secret)
for _, h := range photos {
k := keyer.Photo(h)
body.Keys[h] = hex.EncodeToString(k[:])
}
if solved {
body.Pass = s.token(passKind, bucket, uint32(now.Add(set.PassTTL).Unix()), 1)
}
if !page {
body.Page = s.token(pageKind, bucket, uint32(now.Add(pageTTL).Unix()), 1, req.Build, req.Album)
}
reply(w, http.StatusOK, body)
}
}
func Only(keys http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
header := w.Header()
header.Set("X-Content-Type-Options", "nosniff")
header.Set("Referrer-Policy", "strict-origin-when-cross-origin")
if r.URL.Path != site.KeyPath {
header.Set("Cache-Control", "no-store")
http.NotFound(w, r)
return
}
keys.ServeHTTP(w, r)
})
}
func hostOf(hostport string) string {
if h, _, err := net.SplitHostPort(hostport); err == nil {
return strings.ToLower(h)
}
return strings.ToLower(strings.Trim(hostport, "[]"))
}
func allowedOrigin(r *http.Request, hosts []string) bool {
source := r.Header.Get("Origin")
if source == "" {
source = r.Header.Get("Referer")
}
if source == "" || source == "null" {
return false
}
u, err := url.Parse(source)
if err != nil || u.Host == "" || (u.Scheme != "http" && u.Scheme != "https") {
return false
}
host := strings.ToLower(u.Hostname())
if host == hostOf(r.Host) {
return true
}
for _, allowed := range hosts {
if host == allowed {
return true
}
}
return false
}
func trusted(addr netip.Addr, prefixes []netip.Prefix) bool {
for _, p := range prefixes {
if p.Contains(addr) {
return true
}
}
return false
}
func clientIP(r *http.Request, set *Settings) netip.Addr {
var peer netip.Addr
if ap, err := netip.ParseAddrPort(r.RemoteAddr); err == nil {
peer = ap.Addr().Unmap()
} else if a, err := netip.ParseAddr(r.RemoteAddr); err == nil {
peer = a.Unmap()
}
if set.IPHeader == "" || !peer.IsValid() || !trusted(peer, set.Trusted) {
return peer
}
values := r.Header.Values(set.IPHeader)
var leftmost netip.Addr
for i := len(values) - 1; i >= 0; i-- {
rest := values[i]
for rest != "" {
part := rest
if at := strings.LastIndexByte(rest, ','); at >= 0 {
part, rest = rest[at+1:], rest[:at]
} else {
rest = ""
}
addr, err := netip.ParseAddr(strings.TrimSpace(part))
if err != nil {
if ap, err := netip.ParseAddrPort(strings.TrimSpace(part)); err == nil {
addr = ap.Addr()
} else {
return peer
}
}
addr = addr.Unmap()
if !trusted(addr, set.Trusted) {
return addr
}
leftmost = addr
}
}
if leftmost.IsValid() {
return leftmost
}
return peer
}
func bucketOf(addr netip.Addr) [16]byte {
key := addr.As16()
if addr.Is6() {
clear(key[8:])
}
return key
}
+219
View File
@@ -0,0 +1,219 @@
package keys
import (
"math"
"sync"
"time"
)
const (
slotCount = 16
shardCount = 16
maxBuckets = 200000
)
type slot struct {
photos uint32
low uint16
solved uint16
}
type bucket struct {
key [16]byte
at int64
solveAt int64
solveBase uint32
prev int32
next int32
slots [slotCount]slot
}
type shard struct {
mu sync.Mutex
index map[[16]byte]int32
items []bucket
head int32
tail int32
}
type table struct {
width int64
span int64
limit int
shards [shardCount]shard
}
func newTable(window time.Duration) *table {
width := max(int64(time.Minute), (int64(window)+slotCount-1)/slotCount)
width = (width + int64(time.Minute) - 1) / int64(time.Minute) * int64(time.Minute)
span := min(int64(slotCount), (int64(window)+width-1)/width)
t := &table{width: width, span: span, limit: maxBuckets / shardCount}
for i := range t.shards {
t.shards[i].index = make(map[[16]byte]int32)
t.shards[i].head = -1
t.shards[i].tail = -1
}
return t
}
func (s *shard) unlink(i int32) {
b := &s.items[i]
if b.prev >= 0 {
s.items[b.prev].next = b.next
} else {
s.head = b.next
}
if b.next >= 0 {
s.items[b.next].prev = b.prev
} else {
s.tail = b.prev
}
b.prev, b.next = -1, -1
}
func (s *shard) front(i int32) {
b := &s.items[i]
b.prev = -1
b.next = s.head
if s.head >= 0 {
s.items[s.head].prev = i
}
s.head = i
if s.tail < 0 {
s.tail = i
}
}
func (s *shard) get(key [16]byte, limit int, now int64) *bucket {
if i, ok := s.index[key]; ok {
if s.head != i {
s.unlink(i)
s.front(i)
}
return &s.items[i]
}
var i int32
if len(s.items) < limit {
s.items = append(s.items, bucket{})
i = int32(len(s.items) - 1)
} else {
i = s.tail
s.unlink(i)
delete(s.index, s.items[i].key)
}
s.items[i] = bucket{key: key, at: now, solveAt: math.MinInt64 / 2, prev: -1, next: -1}
s.index[key] = i
s.front(i)
return &s.items[i]
}
func (b *bucket) advance(now int64) {
if now <= b.at {
return
}
if now-b.at >= slotCount {
b.slots = [slotCount]slot{}
} else {
for at := b.at + 1; at <= now; at++ {
b.slots[at%slotCount] = slot{}
}
}
b.at = now
}
type input struct {
nav bool
low bool
pass bool
page bool
solved bool
photos int
photoLimit int
landings int
powBits int
}
type verdict int
const (
grant verdict = iota
challenge
limited
)
type outcome struct {
verdict verdict
bits int
retry time.Duration
}
func shardOf(key [16]byte) int {
h := uint32(2166136261)
for _, c := range key {
h = (h ^ uint32(c)) * 16777619
}
return int(h % shardCount)
}
func (t *table) decide(key [16]byte, now time.Time, in input) outcome {
s := &t.shards[shardOf(key)]
s.mu.Lock()
defer s.mu.Unlock()
cur := now.UnixNano() / t.width
b := s.get(key, t.limit, cur)
b.advance(cur)
var photos, since, low, solved uint64
for i := int64(0); i < t.span; i++ {
at := cur - i
sl := &b.slots[at%slotCount]
photos += uint64(sl.photos)
low += uint64(sl.low)
solved += uint64(sl.solved)
if at >= b.solveAt {
since += uint64(sl.photos)
}
}
if b.solveAt > cur-t.span {
since -= min(since, uint64(b.solveBase))
} else {
since = photos
}
limit := uint64(in.photoLimit)
if photos > 4*limit {
return outcome{verdict: limited, retry: t.retry(b, cur, now, photos-4*limit)}
}
here := &b.slots[cur%slotCount]
if in.solved {
for i := range b.slots {
b.slots[i].low = 0
}
if here.solved < math.MaxUint16 {
here.solved++
}
b.solveAt = cur
b.solveBase = here.photos
here.photos += uint32(in.photos)
return outcome{verdict: grant}
}
admitted := in.pass || in.page
if since > limit || (!admitted && in.nav && in.low) || (!admitted && low >= uint64(in.landings)) {
return outcome{verdict: challenge, bits: min(32, in.powBits+int(min(6, solved)))}
}
here.photos += uint32(in.photos)
if !admitted && !in.nav && in.low && here.low < math.MaxUint16 {
here.low++
}
return outcome{verdict: grant}
}
func (t *table) retry(b *bucket, cur int64, now time.Time, excess uint64) time.Duration {
var dropped uint64
for i := t.span - 1; i >= 0; i-- {
at := cur - i
dropped += uint64(b.slots[at%slotCount].photos)
if dropped >= excess {
return time.Duration((at+t.span)*t.width - now.UnixNano())
}
}
return time.Duration(t.width)
}
+51
View File
@@ -0,0 +1,51 @@
package process
import (
"crypto/hmac"
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"hash"
"strconv"
)
type Keyed struct {
mac hash.Hash
buf []byte
sum []byte
}
func (p *Processor) Keyed() *Keyed {
return &Keyed{mac: hmac.New(sha256.New, p.key), buf: make([]byte, 0, 96), sum: make([]byte, 0, sha256.Size)}
}
func (k *Keyed) digest(label, hash string, level, slot int, source string) []byte {
b := append(k.buf[:0], label...)
b = append(b, '|')
b = append(b, hash...)
b = append(b, '|')
b = strconv.AppendInt(b, int64(level), 10)
if slot >= 0 {
b = append(b, '|')
b = strconv.AppendInt(b, int64(slot), 10)
b = append(b, '|')
b = append(b, source...)
}
k.buf = b
k.mac.Reset()
k.mac.Write(b)
k.sum = k.mac.Sum(k.sum[:0])
return k.sum
}
func (k *Keyed) DecoyName(hash string, level, slot int, source string) string {
return hex.EncodeToString(k.digest("decoy", hash, level, slot, source)[:8])
}
func (k *Keyed) Seed(label, hash string, level int) uint64 {
return binary.BigEndian.Uint64(k.digest(label, hash, level, -1, ""))
}
func (p *Processor) Ext() string {
return "." + p.images.Format
}
+22 -11
View File
@@ -21,16 +21,18 @@ import (
"github.com/luciochen233/luphoto/internal/fsutil"
)
const processorVersion = "luphoto-pyramid-1"
const processorVersion = "luphoto-pyramid-2"
type Level struct {
Width int `json:"width"`
Height int `json:"height"`
Cols int `json:"cols"`
Rows int `json:"rows"`
Quality int `json:"quality"`
Tiles []string `json:"tiles"`
Bytes []int64 `json:"bytes"`
Width int `json:"width"`
Height int `json:"height"`
TileSize int `json:"tile_size"`
Overlap int `json:"overlap,omitempty"`
Cols int `json:"cols"`
Rows int `json:"rows"`
Quality int `json:"quality"`
Tiles []string `json:"tiles"`
Bytes []int64 `json:"bytes"`
}
type Pyramid struct {
@@ -94,7 +96,7 @@ func New(ctx context.Context, cfg *config.Config) (*Processor, error) {
return nil, err
}
}
key, err := loadOrCreateKey(filepath.Join(cfg.State, "site.key"))
key, err := SiteKey(cfg.State)
if err != nil {
return nil, err
}
@@ -113,13 +115,18 @@ func New(ctx context.Context, cfg *config.Config) (*Processor, error) {
}
img := cfg.Images
keySum := sha256.Sum256(key)
format := img.Format
if format == "webp" {
format += "+smart_subsample"
}
fingerprint := strings.Join([]string{
processorVersion,
"tile=" + strconv.Itoa(img.TileSize),
"overlap=" + strconv.Itoa(img.Overlap),
"format=" + img.Format,
"format=" + format,
fmt.Sprintf("q=%d,%d,%d", img.Quality.Top, img.Quality.Mid, img.Quality.Low),
"min_levels=" + strconv.Itoa(img.MinLevels),
"min_grid=" + strconv.Itoa(img.MinGrid),
"seed=" + strconv.Itoa(img.SeedPx),
"names=" + img.TileNames,
"scramble=" + strconv.FormatBool(img.ScrambleCells),
@@ -143,7 +150,11 @@ func (p *Processor) VipsVersion() string {
return p.vips.Version
}
func loadOrCreateKey(path string) ([]byte, error) {
func SiteKey(state string) ([]byte, error) {
path := filepath.Join(state, "site.key")
if err := os.MkdirAll(state, 0o755); err != nil {
return nil, err
}
key, err := os.ReadFile(path)
if err == nil {
if len(key) != 32 {
+33 -18
View File
@@ -29,14 +29,27 @@ func (p *Processor) Overlap() int {
return p.images.Overlap
}
func LevelSizes(width, height, minLevels int) [][2]int {
func (p *Processor) levelTile(size [2]int) (int, int) {
ts := max(1, min(p.images.TileSize, min(size[0], size[1])/p.images.MinGrid))
overlap := p.Overlap()
if ts <= 2*overlap {
overlap = 0
}
return ts, overlap
}
func LevelSizes(width, height, minLevels, minGrid int) [][2]int {
sizes := [][2]int{{width, height}}
for {
w, h := sizes[len(sizes)-1][0], sizes[len(sizes)-1][1]
if (max(w, h) < minLongEdge && len(sizes) >= minLevels) || (w == 1 && h == 1) {
break
}
sizes = append(sizes, [2]int{(w + 1) / 2, (h + 1) / 2})
next := [2]int{(w + 1) / 2, (h + 1) / 2}
if min(next[0], next[1]) < minGrid {
break
}
sizes = append(sizes, next)
}
for i, j := 0, len(sizes)-1; i < j; i, j = i+1, j-1 {
sizes[i], sizes[j] = sizes[j], sizes[i]
@@ -107,7 +120,7 @@ func (p *Processor) renderOG(ctx context.Context, job *Job) (*Record, error) {
}
final := filepath.Join(p.OGDir, job.Hash+".jpg")
tmp := fsutil.TempName(final) + ".jpg"
if err := p.vips.Run(ctx, "thumbnail", prepared, tmp+p.vips.SaveOptions(OGQuality),
if err := p.vips.Run(ctx, "thumbnail", prepared, tmp+p.vips.SaveOptions("jpeg", OGQuality),
strconv.Itoa(OGWidth), "--height", strconv.Itoa(OGHeight), "--crop", "centre"); err != nil {
_ = os.Remove(tmp)
return nil, err
@@ -152,7 +165,7 @@ func (p *Processor) process(ctx context.Context, job *Job) (*Record, error) {
if err != nil {
return nil, err
}
sizes := LevelSizes(width, height, p.images.MinLevels)
sizes := LevelSizes(width, height, p.images.MinLevels, p.images.MinGrid)
count := len(sizes)
seedLevel := count - 1
for i, size := range sizes {
@@ -200,9 +213,9 @@ func (p *Processor) process(ctx context.Context, job *Job) (*Record, error) {
defer wg.Done()
defer src.release()
input := src.path
if p.images.ScrambleCells {
if ts, _ := p.levelTile(sizes[i]); p.images.ScrambleCells && ts >= 2*ScrambleCell {
scrambled := filepath.Join(work, "s"+strconv.Itoa(i)+".v")
if err := ScrambleV(src.path, scrambled, scrambleSeed, i, p.images.TileSize, ScrambleCell); err != nil {
if err := ScrambleV(src.path, scrambled, scrambleSeed, i, ts, ScrambleCell); err != nil {
fail(fmt.Errorf("scramble level %d: %w", i, err))
return
}
@@ -323,7 +336,7 @@ func (p *Processor) resize(ctx context.Context, src, dst string, from, to [2]int
func (p *Processor) seed(ctx context.Context, src, work string) (string, error) {
out := filepath.Join(work, "seed."+p.images.Format)
if err := p.vips.Run(ctx, "thumbnail", src, out+p.vips.SaveOptions(p.images.Quality.Low),
if err := p.vips.Run(ctx, "thumbnail", src, out+p.vips.SaveOptions(p.images.Format, p.images.Quality.Low),
strconv.Itoa(p.images.SeedPx), "--height", strconv.Itoa(p.images.SeedPx)); err != nil {
return "", fmt.Errorf("seed: %w", err)
}
@@ -368,12 +381,13 @@ func (p *Processor) cutLevel(ctx context.Context, hash, src, stage string, level
quality := p.levelQuality(level, count, size)
base := filepath.Join(stage, strconv.Itoa(level))
ext := "." + p.images.Format
ts, overlap := p.levelTile(size)
if err := p.vips.Run(ctx, "dzsave", src, base,
"--layout", "dz",
"--depth", "one",
"--tile-size", strconv.Itoa(p.images.TileSize),
"--overlap", strconv.Itoa(p.Overlap()),
"--suffix", ext+p.vips.SaveOptions(quality)); err != nil {
"--tile-size", strconv.Itoa(ts),
"--overlap", strconv.Itoa(overlap),
"--suffix", ext+p.vips.SaveOptions(p.images.Format, quality)); err != nil {
return Level{}, err
}
dir, err := levelDir(base + "_files")
@@ -384,7 +398,6 @@ func (p *Processor) cutLevel(ctx context.Context, hash, src, stage string, level
if err != nil {
return Level{}, err
}
ts := p.images.TileSize
cols := (size[0] + ts - 1) / ts
rows := (size[1] + ts - 1) / ts
files := make([]tileFile, 0, len(entries))
@@ -405,13 +418,15 @@ func (p *Processor) cutLevel(ctx context.Context, hash, src, stage string, level
return Level{}, fmt.Errorf("expected %dx%d tiles, found %d", cols, rows, len(files))
}
out := Level{
Width: size[0],
Height: size[1],
Cols: cols,
Rows: rows,
Quality: quality,
Tiles: make([]string, cols*rows),
Bytes: make([]int64, cols*rows),
Width: size[0],
Height: size[1],
TileSize: ts,
Overlap: overlap,
Cols: cols,
Rows: rows,
Quality: quality,
Tiles: make([]string, cols*rows),
Bytes: make([]int64, cols*rows),
}
renamers := min(4, (len(files)+31)/32)
var wg sync.WaitGroup
+2 -2
View File
@@ -171,10 +171,10 @@ func scrambleBand(in, out *os.File, buf, tmp []byte, header vHeader, band int, r
for tx := 0; tx < tiles; tx++ {
width := min(tileSize, header.width-tx*tileSize)
cols := width / cell
n := cols * cellRows
if n < 2 {
if cols < 2 || cellRows < 2 {
continue
}
n := cols * cellRows
perm := CellPermutation(n, tileSeed(seed, level, tx, band))
origin := tx * tileSize * header.pixelBytes
at := func(index, row int) []byte {
+4 -1
View File
@@ -99,7 +99,10 @@ func (v *Vips) Run(ctx context.Context, args ...string) error {
return nil
}
func (v *Vips) SaveOptions(quality int) string {
func (v *Vips) SaveOptions(format string, quality int) string {
if format == "webp" {
return "[Q=" + strconv.Itoa(quality) + ",smart_subsample=true," + v.Strip + "]"
}
return "[Q=" + strconv.Itoa(quality) + "," + v.Strip + "]"
}
+97
View File
@@ -0,0 +1,97 @@
package protect
import (
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/binary"
"fmt"
"hash"
"os"
"path/filepath"
)
const (
SealMagic = "luphoto-sealed-1"
NonceSize = 12
SecretName = ".secret"
SecretSize = 32
)
func NewSecret() ([]byte, error) {
secret := make([]byte, SecretSize)
if _, err := rand.Read(secret); err != nil {
return nil, err
}
return secret, nil
}
func ReadSecret(buildDir string) ([]byte, error) {
secret, err := os.ReadFile(filepath.Join(buildDir, SecretName))
if err != nil {
return nil, err
}
if len(secret) != SecretSize {
return nil, fmt.Errorf("build secret %s: expected %d bytes, found %d", buildDir, SecretSize, len(secret))
}
return secret, nil
}
type Keyer struct {
mac hash.Hash
buf []byte
sum []byte
}
func NewKeyer(secret []byte) *Keyer {
return &Keyer{mac: hmac.New(sha256.New, secret), buf: make([]byte, 0, 64), sum: make([]byte, 0, sha256.Size)}
}
func (k *Keyer) derive(label, hash string) [32]byte {
b := append(k.buf[:0], label...)
b = append(b, '|')
b = append(b, hash...)
k.buf = b
k.mac.Reset()
k.mac.Write(b)
k.sum = k.mac.Sum(k.sum[:0])
var out [32]byte
copy(out[:], k.sum)
return out
}
func (k *Keyer) Photo(hash string) [32]byte {
return k.derive("photo", hash)
}
func (k *Keyer) Cover() [32]byte {
return k.derive("cover", "")
}
func Seal(key [32]byte, plain []byte) (string, error) {
out := make([]byte, NonceSize+len(SealMagic)+len(plain))
if _, err := rand.Read(out[:NonceSize]); err != nil {
return "", err
}
body := out[NonceSize:]
copy(body, SealMagic)
copy(body[len(SealMagic):], plain)
XOR(key, out[:NonceSize], body)
return base64.StdEncoding.EncodeToString(out), nil
}
func XOR(key [32]byte, nonce, data []byte) {
var block [32 + NonceSize + 4]byte
copy(block[:32], key[:])
copy(block[32:], nonce)
for i := uint32(0); len(data) > 0; i++ {
binary.BigEndian.PutUint32(block[32+NonceSize:], i)
stream := sha256.Sum256(block[:])
n := min(len(stream), len(data))
for j := 0; j < n; j++ {
data[j] ^= stream[j]
}
data = data[n:]
}
}
+8 -2
View File
@@ -50,10 +50,11 @@ type Settings struct {
type Handler struct {
settings atomic.Pointer[Settings]
keys http.Handler
}
func NewHandler(settings Settings) *Handler {
h := &Handler{}
func NewHandler(settings Settings, keys http.Handler) *Handler {
h := &Handler{keys: keys}
h.Update(settings)
return h
}
@@ -72,6 +73,10 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
header.Set("Content-Security-Policy", contentSecurityPolicy)
header.Set("X-Content-Type-Options", "nosniff")
header.Set("Referrer-Policy", "strict-origin-when-cross-origin")
if r.URL.Path == "/k" && h.keys != nil {
h.keys.ServeHTTP(w, r)
return
}
if r.Method != http.MethodGet && r.Method != http.MethodHead {
header.Set("Allow", "GET, HEAD")
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
@@ -80,6 +85,7 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
settings := h.settings.Load()
clean := path.Clean("/" + r.URL.Path)
if strings.HasPrefix(clean, "/t/") && hotlinked(r, settings.HotlinkAllow) {
header.Set("Cache-Control", "no-store")
http.Error(w, "forbidden", http.StatusForbidden)
return
}
+89 -25
View File
@@ -32,15 +32,67 @@ const (
type Tiles struct {
Format string `json:"format"`
TileSize int `json:"tile_size"`
Overlap int `json:"overlap"`
Path string `json:"path"`
Scrambled bool `json:"scrambled,omitempty"`
Cell int `json:"cell,omitempty"`
}
type Level struct {
Width int `json:"width"`
Height int `json:"height"`
TileSize int `json:"tile_size"`
Overlap int `json:"overlap,omitempty"`
Cols int `json:"cols"`
Rows int `json:"rows"`
}
type Pyramid struct {
Hash string `json:"hash"`
Width int `json:"width"`
Height int `json:"height"`
Levels []Level `json:"levels"`
}
func Layout(p *process.Pyramid) *Pyramid {
out := &Pyramid{Hash: p.Hash, Width: p.Width, Height: p.Height, Levels: make([]Level, len(p.Levels))}
for i, l := range p.Levels {
out.Levels[i] = Level{Width: l.Width, Height: l.Height, TileSize: l.TileSize, Overlap: l.Overlap, Cols: l.Cols, Rows: l.Rows}
}
return out
}
const (
GateServer = "server"
GateOff = "off"
KeyPath = "/k"
)
type Gate struct {
Build string `json:"build"`
Mode string `json:"mode"`
Cover string `json:"cover"`
MinEntropy int `json:"min_entropy"`
Keys map[string]string `json:"keys,omitempty"`
}
type Pool struct {
Levels []string `json:"levels"`
Sealed string `json:"sealed"`
}
type SealedLevel struct {
Map []int32 `json:"map"`
Bytes []int64 `json:"bytes"`
}
type Sealed struct {
Seed string `json:"seed"`
Scramble string `json:"scramble,omitempty"`
Levels []SealedLevel `json:"levels"`
}
type Photo struct {
process.Pyramid
Pyramid
Title string `json:"title,omitempty"`
Caption string `json:"caption,omitempty"`
Alt string `json:"alt,omitempty"`
@@ -49,36 +101,38 @@ type Photo struct {
}
type Manifest struct {
Build string `json:"build"`
Slug string `json:"slug"`
Title string `json:"title"`
Subtitle string `json:"subtitle,omitempty"`
Date string `json:"date,omitempty"`
Order *int `json:"order,omitempty"`
Hidden bool `json:"hidden,omitempty"`
CollapsedFocusY float64 `json:"collapsed_focus_y"`
ShowEXIF bool `json:"show_exif"`
Tiles Tiles `json:"tiles"`
Cover *process.Pyramid `json:"cover"`
OG string `json:"og,omitempty"`
Photos []Photo `json:"photos"`
Build string `json:"build"`
Slug string `json:"slug"`
Title string `json:"title"`
Subtitle string `json:"subtitle,omitempty"`
Date string `json:"date,omitempty"`
Order *int `json:"order,omitempty"`
Hidden bool `json:"hidden,omitempty"`
CollapsedFocusY float64 `json:"collapsed_focus_y"`
ShowEXIF bool `json:"show_exif"`
Tiles Tiles `json:"tiles"`
Gate *Gate `json:"gate,omitempty"`
Cover *Pyramid `json:"cover"`
OG string `json:"og,omitempty"`
Photos []Photo `json:"photos"`
}
type IndexAlbum struct {
Slug string `json:"slug"`
Title string `json:"title"`
Subtitle string `json:"subtitle,omitempty"`
Date string `json:"date,omitempty"`
CollapsedFocusY float64 `json:"collapsed_focus_y"`
Photos int `json:"photos"`
Manifest string `json:"manifest"`
Cover *process.Pyramid `json:"cover"`
OG string `json:"og,omitempty"`
Slug string `json:"slug"`
Title string `json:"title"`
Subtitle string `json:"subtitle,omitempty"`
Date string `json:"date,omitempty"`
CollapsedFocusY float64 `json:"collapsed_focus_y"`
Photos int `json:"photos"`
Manifest string `json:"manifest"`
Cover *Pyramid `json:"cover"`
OG string `json:"og,omitempty"`
}
type Index struct {
Build string `json:"build"`
Tiles Tiles `json:"tiles"`
Gate *Gate `json:"gate,omitempty"`
Albums []IndexAlbum `json:"albums"`
}
@@ -102,6 +156,14 @@ func IndexName(build string) string {
return "index." + build + ".json"
}
const PoolDir = "p"
func PoolName(build, hash string) string {
return hash + "." + build + ".json"
}
const Robots = "User-agent: *\nDisallow: /t/\nDisallow: /a/*/p/\n"
func OGPath(hash string) string {
if hash == "" {
return ""
@@ -115,6 +177,8 @@ type Page struct {
MaxDPR float64
Concurrency int
BlockContextMenu bool
Gate string
MinEntropy int
BaseURL string
}
+1 -1
View File
@@ -1 +1 @@
:root{--lucio-graphite: #111114;--lucio-graphite-2: #1A1A1F;--lucio-graphite-3: #26262D;--lucio-paper: #F3F1EC;--lucio-paper-2: #E9E6DF;--lucio-paper-3: #D9D6CD;--lucio-beam: #FFF3CF;--lucio-beam-deep: #5E5238;--lucio-beam-glow: #FFFBF0;--lucio-steel: #8A94A6;--lucio-steel-deep: #3F4B60;--lucio-cinnabar: #C3361F;--lucio-cinnabar-light: #F08A77;--lucio-ash: #666A74;--lucio-ash-dark: #43464F;--lucio-ash-light: #A6A9B3;--lucio-font-display: "Bricolage Grotesque", "Noto Sans SC", "PingFang SC", "Microsoft YaHei", system-ui, sans-serif;--lucio-font-body: "IBM Plex Sans", "Noto Sans SC", "PingFang SC", "Microsoft YaHei", system-ui, sans-serif;--lucio-font-mono: "IBM Plex Mono", "JetBrains Mono", ui-monospace, "Cascadia Code", Consolas, monospace;--lucio-font-cjk-display: "Noto Serif SC", "Songti SC", "SimSun", serif;--lucio-font-cjk-body: "Noto Sans SC", "PingFang SC", "Microsoft YaHei", sans-serif;--lucio-space-1: 4px;--lucio-space-2: 8px;--lucio-space-3: 12px;--lucio-space-4: 16px;--lucio-space-5: 24px;--lucio-space-6: 32px;--lucio-space-7: 48px;--lucio-space-8: 64px;--lucio-space-9: 96px;--lucio-space-10: 128px;--lucio-radius-none: 0px;--lucio-radius-sm: 4px;--lucio-radius-md: 8px;--lucio-radius-lg: 16px;--lucio-radius-icon: 22%;--lucio-shadow-glow: 0 0 0 1px rgba(255,243,207,.3), 0 8px 32px -8px rgba(255,243,207,.35);--lucio-motion-fast: .12s;--lucio-ease-fast: cubic-bezier(.2, 0, 0, 1);--lucio-motion-base: .24s;--lucio-ease-base: cubic-bezier(.2, 0, 0, 1);--lucio-motion-glow: .9s;--lucio-ease-glow: cubic-bezier(.16, 1, .3, 1)}@font-face{font-family:Bricolage Grotesque;font-style:normal;font-weight:200 800;font-display:swap;src:url("./bricolage-grotesque-latin-ext-wght-normal.EMW626ZA.woff2") format("woff2-variations");unicode-range:U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF}@font-face{font-family:Bricolage Grotesque;font-style:normal;font-weight:200 800;font-display:swap;src:url("./bricolage-grotesque-latin-wght-normal.HY2A4V5R.woff2") format("woff2-variations");unicode-range:U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD}@font-face{font-family:IBM Plex Sans;font-style:normal;font-weight:400;font-display:swap;src:url("./ibm-plex-sans-latin-ext-400-normal.EDOVP6TU.woff2") format("woff2");unicode-range:U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF}@font-face{font-family:IBM Plex Sans;font-style:normal;font-weight:400;font-display:swap;src:url("./ibm-plex-sans-latin-400-normal.COQVXTP6.woff2") format("woff2");unicode-range:U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD}@font-face{font-family:IBM Plex Sans;font-style:normal;font-weight:500;font-display:swap;src:url("./ibm-plex-sans-latin-ext-500-normal.SG2XNXKB.woff2") format("woff2");unicode-range:U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF}@font-face{font-family:IBM Plex Sans;font-style:normal;font-weight:500;font-display:swap;src:url("./ibm-plex-sans-latin-500-normal.JTONHBWS.woff2") format("woff2");unicode-range:U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD}@font-face{font-family:IBM Plex Sans;font-style:normal;font-weight:600;font-display:swap;src:url("./ibm-plex-sans-latin-ext-600-normal.ZNWKNRXL.woff2") format("woff2");unicode-range:U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF}@font-face{font-family:IBM Plex Sans;font-style:normal;font-weight:600;font-display:swap;src:url("./ibm-plex-sans-latin-600-normal.DTNZULF4.woff2") format("woff2");unicode-range:U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD}@font-face{font-family:IBM Plex Sans;font-style:italic;font-weight:400;font-display:swap;src:url("./ibm-plex-sans-latin-ext-400-italic.VMPJJ47P.woff2") format("woff2");unicode-range:U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF}@font-face{font-family:IBM Plex Sans;font-style:italic;font-weight:400;font-display:swap;src:url("./ibm-plex-sans-latin-400-italic.PR7YQ55B.woff2") format("woff2");unicode-range:U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,Line truncated
:root{--lucio-graphite: #111114;--lucio-graphite-2: #1A1A1F;--lucio-graphite-3: #26262D;--lucio-paper: #F3F1EC;--lucio-paper-2: #E9E6DF;--lucio-paper-3: #D9D6CD;--lucio-beam: #FFF3CF;--lucio-beam-deep: #5E5238;--lucio-beam-glow: #FFFBF0;--lucio-steel: #8A94A6;--lucio-steel-deep: #3F4B60;--lucio-cinnabar: #C3361F;--lucio-cinnabar-light: #F08A77;--lucio-ash: #666A74;--lucio-ash-dark: #43464F;--lucio-ash-light: #A6A9B3;--lucio-font-display: "Bricolage Grotesque", "Noto Sans SC", "PingFang SC", "Microsoft YaHei", system-ui, sans-serif;--lucio-font-body: "IBM Plex Sans", "Noto Sans SC", "PingFang SC", "Microsoft YaHei", system-ui, sans-serif;--lucio-font-mono: "IBM Plex Mono", "JetBrains Mono", ui-monospace, "Cascadia Code", Consolas, monospace;--lucio-font-cjk-display: "Noto Serif SC", "Songti SC", "SimSun", serif;--lucio-font-cjk-body: "Noto Sans SC", "PingFang SC", "Microsoft YaHei", sans-serif;--lucio-space-1: 4px;--lucio-space-2: 8px;--lucio-space-3: 12px;--lucio-space-4: 16px;--lucio-space-5: 24px;--lucio-space-6: 32px;--lucio-space-7: 48px;--lucio-space-8: 64px;--lucio-space-9: 96px;--lucio-space-10: 128px;--lucio-radius-none: 0px;--lucio-radius-sm: 4px;--lucio-radius-md: 8px;--lucio-radius-lg: 16px;--lucio-radius-icon: 22%;--lucio-shadow-glow: 0 0 0 1px rgba(255,243,207,.3), 0 8px 32px -8px rgba(255,243,207,.35);--lucio-motion-fast: .12s;--lucio-ease-fast: cubic-bezier(.2, 0, 0, 1);--lucio-motion-base: .24s;--lucio-ease-base: cubic-bezier(.2, 0, 0, 1);--lucio-motion-glow: .9s;--lucio-ease-glow: cubic-bezier(.16, 1, .3, 1)}@font-face{font-family:Bricolage Grotesque;font-style:normal;font-weight:200 800;font-display:swap;src:url("./bricolage-grotesque-latin-ext-wght-normal.EMW626ZA.woff2") format("woff2-variations");unicode-range:U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF}@font-face{font-family:Bricolage Grotesque;font-style:normal;font-weight:200 800;font-display:swap;src:url("./bricolage-grotesque-latin-wght-normal.HY2A4V5R.woff2") format("woff2-variations");unicode-range:U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD}@font-face{font-family:IBM Plex Sans;font-style:normal;font-weight:400;font-display:swap;src:url("./ibm-plex-sans-latin-ext-400-normal.EDOVP6TU.woff2") format("woff2");unicode-range:U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF}@font-face{font-family:IBM Plex Sans;font-style:normal;font-weight:400;font-display:swap;src:url("./ibm-plex-sans-latin-400-normal.COQVXTP6.woff2") format("woff2");unicode-range:U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD}@font-face{font-family:IBM Plex Sans;font-style:normal;font-weight:500;font-display:swap;src:url("./ibm-plex-sans-latin-ext-500-normal.SG2XNXKB.woff2") format("woff2");unicode-range:U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF}@font-face{font-family:IBM Plex Sans;font-style:normal;font-weight:500;font-display:swap;src:url("./ibm-plex-sans-latin-500-normal.JTONHBWS.woff2") format("woff2");unicode-range:U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD}@font-face{font-family:IBM Plex Sans;font-style:normal;font-weight:600;font-display:swap;src:url("./ibm-plex-sans-latin-ext-600-normal.ZNWKNRXL.woff2") format("woff2");unicode-range:U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF}@font-face{font-family:IBM Plex Sans;font-style:normal;font-weight:600;font-display:swap;src:url("./ibm-plex-sans-latin-600-normal.DTNZULF4.woff2") format("woff2");unicode-range:U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD}@font-face{font-family:IBM Plex Sans;font-style:italic;font-weight:400;font-display:swap;src:url("./ibm-plex-sans-latin-ext-400-italic.VMPJJ47P.woff2") format("woff2");unicode-range:U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF}@font-face{font-family:IBM Plex Sans;font-style:italic;font-weight:400;font-display:swap;src:url("./ibm-plex-sans-latin-400-italic.PR7YQ55B.woff2") format("woff2");unicode-range:U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,Line truncated
+279 -1
View File
@@ -1 +1,279 @@
"use strict";(()=>{(function(r){let t={from:"Guoliang",to:"Lucio",letters:[{ch:"G",kind:"keep",shared:"M8.50 22.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L58.00 91.50",fullA:"M80.00 8.50L58.00 8.50L22.00 8.50A13.50 13.50 0 0 0 8.50 22.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L58.00 91.50A13.50 13.50 0 0 0 71.50 78.00L71.50 56.00L41.50 56.00",fullB:"M8.50 0.00L8.50 22.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L58.00 91.50L80.00 91.50",out:[{d:"M80.00 8.50L58.00 8.50L22.00 8.50A13.50 13.50 0 0 0 8.50 22.00",P:79.21,j:"end"},{d:"M58.00 91.50A13.50 13.50 0 0 0 71.50 78.00L71.50 56.00L41.50 56.00",P:73.21,j:"start"}],in:[{d:"M8.50 22.00L8.50 0.00",P:22,j:"start"},{d:"M58.00 91.50L80.00 91.50",P:22,j:"start"}],x0:0,x1:0,dot:null},{ch:"u",kind:"keep",shared:"M8.50 38.00L8.50 60.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L38.00 91.50A13.50 13.50 0 0 0 51.50 78.00L51.50 60.00L51.50 38.00",fullA:"M8.50 38.00L8.50 60.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L38.00 91.50A13.50 13.50 0 0 0 51.50 78.00L51.50 60.00L51.50 38.00",fullB:"M8.50 38.00L8.50 60.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L38.00 91.50A13.50 13.50 0 0 0 51.50 78.00L51.50 60.00L51.50 38.00",out:[],in:[],x0:88.8,x1:88,dot:null},{ch:"o",kind:"keep",shared:"M38.00 46.50L22.00 46.50A13.50 13.50 0 0 0 8.50 60.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L38.00 91.50",fullA:"M38.00 91.50A13.50 13.50 0 0 0 51.50 78.00L51.50 60.00A13.50 13.50 0 0 0 38.00 46.50L22.00 46.50A13.50 13.50 0 0 0 8.50 60.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L38.00 91.50",fullB:"M60.00 46.50L38.00 46.50L22.00 46.50A13.50 13.50 0 0 0 8.50 60.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L38.00 91.50L60.00 91.50",out:[{d:"M38.00 91.50A13.50 13.50 0 0 0 51.50 78.00L51.50 60.00A13.50 13.50 0 0 0 38.00 46.50",P:60.41,j:"both"}],in:[{d:"M38.00 46.50L60.00 46.50",P:22,j:"start"},{d:"M38.00 91.50L60.00 91.50",P:22,j:"start"}],x0:159,x1:158.2,dot:null},{ch:"l",kind:"fade",d:"M8.50 0.00L8.50 100.00",x0:230.8,x1:230.8,dot:null},{ch:"i",kind:"keep",shared:"M8.50 38.00L8.50 100.00",fullA:"M8.50 38.00L8.50 100.00",fullB:"M8.50 38.00L8.50 100.00",out:[],in:[],x0:262.8,x1:227.9,dot:[0,14,17]},{ch:"a",kind:"fade",d:"M38.00 91.50L51.50 91.50L51.50 78.00L51.50 60.00L51.50 46.50L38.00 46.50L22.00 46.50A13.50 13.50 0 0 0 8.50 60.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L38.00 91.50",x0:291.6,x1:291.6,dot:null},{ch:"n",kind:"fade",d:"M51.50 100.00L51.50 78.00L51.50 60.00A13.50 13.50 0 0 0 38.00 46.50L22.00 46.50A13.50 13.50 0 0 0 8.50 60.00L8.50 78.00L8.50 100.00",x0:362.7,x1:362.7,dot:null},{ch:"g",kind:"keep",shared:"M38.00 91.50A13.50 13.50 0 0 0 51.50 78.00L51.50 60.00A13.50 13.50 0 0 0 38.00 46.50L22.00 46.50A13.50 13.50 0 0 0 8.50 60.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L38.00 91.50",fullA:"M0.00 127.50L38.00 127.50A13.50 13.50 0 0 0 51.50 114.00L51.50 60.00A13.50 13.50 0 0 0 38.00 46.50L22.00 46.50A13.50 13.50 0 0 0 8.50 60.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L38.00 91.50A13.50 13.50 0 0 0 51.50 78.00L51.50 60.00",fullB:"M38.00 91.50A13.50 13.50 0 0 0 51.50 78.00L51.50 60.00A13.50 13.50 0 0 0 38.00 46.50L22.00 46.50A13.50 13.50 0 0 0 8.50 60.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L38.00 91.50",out:[{d:"M51.50 60.00L51.50 114.00A13.50 13.50 0 0 1 38.00 127.50L0.00 127.50",P:113.21,j:"start"}],in:[],x0:432.9,x1:256.7,dot:null}],pad:17,vbw:526.9,vbh:170,stroke:17,raysT:"translate(0.000 22.727) scale(0.7727)"},e="M47.6 70.7L71.9 61.1L71.1 58.2L45.2 62.0ZM44.9 61.5L61.2 40.9L59.1 38.8L38.5 55.1ZM38.0 54.8L41.8 28.9L38.9 28.1L29.3 52.4Z",i="http://www.w3.org/2000/svg",s=(c,w)=>{let d=document.createElementNS(i,c);for(let u in w)d.setAttribute(u,w[u]);return d},n=()=>r.matchMedia&&r.matchMedia("(prefers-reduced-motion: reduce)").matches,o=c=>Math.max(0,Math.min(1,c)),a=c=>c*c*(3-2*c),l=.5;function h(c,w){let d=0,u=0,p=null,g=0;function A(y){let b=(y-g)/w;g=y,d=d<u?Math.min(u,d+b):Math.max(u,d-b),c(d),p=d===u?null:requestAnimationFrame(A)}function v(y){if(u=y,n()){d=y,c(d);return}p===null&&(g=performance.now(),p=requestAnimationFrame(A))}return{play:()=>v(1),reverse:()=>v(0),toggle:()=>v(u?0:1),set:y=>{cancelAnimationFrame(p),p=null,u=d=y,c(d)},stop:()=>{cancelAnimationFrame(p),p=null},get t(){return d}}}function m(c,w,d,u){let p=o(u)*w;if(c.style.visibility=p<.05?"hidden":"visible",d==="both"){let g=p/2;c.setAttribute("stroke-dasharray",g.toFixed(2)+" "+Math.max(0,w-2*g).toFixed(2)+" "+g.toFixed(2)),c.setAttribute("stroke-dashoffset","0")}else d==="end"?(c.setAttribute("stroke-dasharray",p.toFixed(2)+" "+(2*w+20).toFixed(2)),c.setAttribute("stroke-dashoffset",(-(w-p)).toFixed(2))):(c.setAttribute("stroke-dasharray",p.toFixed(2)+" "+(2*w+20).toFixed(2)),c.setAttribute("stroke-dashoffset","0"))}function M(c,w={}){let d=Object.assign({trigger:"hover",color:"currentColor",rays:"#FFF3CF",duration:450,autoDelay:1800},w),u=s("svg",{viewBox:"0 0 "+t.vbw+" "+t.vbh,role:"img","aria-label":"Guoliang Chen, Lucio"});u.style.display="block",u.style.width="100%",u.style.height="auto";let p=sLine truncated
"use strict";(()=>{(function(n){let e={from:"Guoliang",to:"Lucio",letters:[{ch:"G",kind:"keep",shared:"M8.50 22.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L58.00 91.50",fullA:"M80.00 8.50L58.00 8.50L22.00 8.50A13.50 13.50 0 0 0 8.50 22.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L58.00 91.50A13.50 13.50 0 0 0 71.50 78.00L71.50 56.00L41.50 56.00",fullB:"M8.50 0.00L8.50 22.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L58.00 91.50L80.00 91.50",out:[{d:"M80.00 8.50L58.00 8.50L22.00 8.50A13.50 13.50 0 0 0 8.50 22.00",P:79.21,j:"end"},{d:"M58.00 91.50A13.50 13.50 0 0 0 71.50 78.00L71.50 56.00L41.50 56.00",P:73.21,j:"start"}],in:[{d:"M8.50 22.00L8.50 0.00",P:22,j:"start"},{d:"M58.00 91.50L80.00 91.50",P:22,j:"start"}],x0:0,x1:0,dot:null},{ch:"u",kind:"keep",shared:"M8.50 38.00L8.50 60.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L38.00 91.50A13.50 13.50 0 0 0 51.50 78.00L51.50 60.00L51.50 38.00",fullA:"M8.50 38.00L8.50 60.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L38.00 91.50A13.50 13.50 0 0 0 51.50 78.00L51.50 60.00L51.50 38.00",fullB:"M8.50 38.00L8.50 60.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L38.00 91.50A13.50 13.50 0 0 0 51.50 78.00L51.50 60.00L51.50 38.00",out:[],in:[],x0:88.8,x1:88,dot:null},{ch:"o",kind:"keep",shared:"M38.00 46.50L22.00 46.50A13.50 13.50 0 0 0 8.50 60.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L38.00 91.50",fullA:"M38.00 91.50A13.50 13.50 0 0 0 51.50 78.00L51.50 60.00A13.50 13.50 0 0 0 38.00 46.50L22.00 46.50A13.50 13.50 0 0 0 8.50 60.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L38.00 91.50",fullB:"M60.00 46.50L38.00 46.50L22.00 46.50A13.50 13.50 0 0 0 8.50 60.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L38.00 91.50L60.00 91.50",out:[{d:"M38.00 91.50A13.50 13.50 0 0 0 51.50 78.00L51.50 60.00A13.50 13.50 0 0 0 38.00 46.50",P:60.41,j:"both"}],in:[{d:"M38.00 46.50L60.00 46.50",P:22,j:"start"},{d:"M38.00 91.50L60.00 91.50",P:22,j:"start"}],x0:159,x1:158.2,dot:null},{ch:"l",kind:"fade",d:"M8.50 0.00L8.50 100.00",x0:230.8,x1:230.8,dot:null},{ch:"i",kind:"keep",shared:"M8.50 38.00L8.50 100.00",fullA:"M8.50 38.00L8.50 100.00",fullB:"M8.50 38.00L8.50 100.00",out:[],in:[],x0:262.8,x1:227.9,dot:[0,14,17]},{ch:"a",kind:"fade",d:"M38.00 91.50L51.50 91.50L51.50 78.00L51.50 60.00L51.50 46.50L38.00 46.50L22.00 46.50A13.50 13.50 0 0 0 8.50 60.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L38.00 91.50",x0:291.6,x1:291.6,dot:null},{ch:"n",kind:"fade",d:"M51.50 100.00L51.50 78.00L51.50 60.00A13.50 13.50 0 0 0 38.00 46.50L22.00 46.50A13.50 13.50 0 0 0 8.50 60.00L8.50 78.00L8.50 100.00",x0:362.7,x1:362.7,dot:null},{ch:"g",kind:"keep",shared:"M38.00 91.50A13.50 13.50 0 0 0 51.50 78.00L51.50 60.00A13.50 13.50 0 0 0 38.00 46.50L22.00 46.50A13.50 13.50 0 0 0 8.50 60.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L38.00 91.50",fullA:"M0.00 127.50L38.00 127.50A13.50 13.50 0 0 0 51.50 114.00L51.50 60.00A13.50 13.50 0 0 0 38.00 46.50L22.00 46.50A13.50 13.50 0 0 0 8.50 60.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L38.00 91.50A13.50 13.50 0 0 0 51.50 78.00L51.50 60.00",fullB:"M38.00 91.50A13.50 13.50 0 0 0 51.50 78.00L51.50 60.00A13.50 13.50 0 0 0 38.00 46.50L22.00 46.50A13.50 13.50 0 0 0 8.50 60.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L38.00 91.50",out:[{d:"M51.50 60.00L51.50 114.00A13.50 13.50 0 0 1 38.00 127.50L0.00 127.50",P:113.21,j:"start"}],in:[],x0:432.9,x1:256.7,dot:null}],pad:17,vbw:526.9,vbh:170,stroke:17,raysT:"translate(0.000 22.727) scale(0.7727)"},t="M47.6 70.7L71.9 61.1L71.1 58.2L45.2 62.0ZM44.9 61.5L61.2 40.9L59.1 38.8L38.5 55.1ZM38.0 54.8L41.8 28.9L38.9 28.1L29.3 52.4Z",i="http://www.w3.org/2000/svg",s=(v,E)=>{let p=document.createElementNS(i,v);for(let y in E)p.setAttribute(y,E[y]);return p},r=()=>n.matchMedia&&n.matchMedia("(prefers-reduced-motion: reduce)").matches,o=v=>Math.max(0,Math.min(1,v)),a=v=>v*v*(3-2*v),l=.5;function h(v,E){let p=0,y=0,x=null,M=0;function F(T){let A=(T-M)/E;M=T,p=p<y?Math.min(y,p+A):Math.max(y,p-A),v(p),x=p===y?null:requestAnimationFrame(F)}function w(T){if(y=T,r()){p=T,v(p);return}x===null&&(M=performance.now(),x=requestAnimationFrame(F))}return{play:()=>w(1),reverse:()=>w(0),toggle:()=>w(y?0:1),set:T=>{cancelAnimationFrame(x),x=null,y=p=T,v(p)},stop:()=>{cancelAnimationFrame(x),x=null},get t(){return p}}}function c(v,E,p,y){let x=o(y)*E;if(v.style.visibility=x<.05?"hidden":"visible",p==="both"){let M=x/2;v.setAttribute("stroke-dasharray",M.toFixed(2)+" "+Math.max(0,E-2*M).toFixed(2)+" "+M.toFixed(2)),v.setAttribute("stroke-dashoffset","0")}else p==="end"?(v.setAttribute("stroke-dasharray",x.toFixed(2)+" "+(2*E+20).toFixed(2)),v.setAttribute("stroke-dashoffset",(-(E-x)).toFixed(2))):(v.setAttribute("stroke-dasharray",x.toFixed(2)+" "+(2*E+20).toFixed(2)),v.setAttribute("stroke-dashoffset","0"))}function f(v,E={}){let p=Object.assign({trigger:"hover",color:"currentColor",rays:"#FFF3CF",duration:450,autoDelay:1800},E),y=s("svg",{viewBox:"0 0 "+e.vbw+" "+e.vbh,role:"img","aria-label":"Guoliang Chen, Lucio"});y.style.display="block",y.style.width="100%",y.style.height="auto";let x=sLine truncated
precision highp float;
uniform vec2 uRes;
uniform float uPx, uTime, uDark;
uniform vec3 uColor;
#define PI 3.14159265
#define HPI 1.5707963
const float HB = ${49.8.toFixed(4)}, CR = ${16.2.toFixed(4)}, HW = ${10.2.toFixed(4)}, H = ${s.toFixed(4)};
const float SL = ${r.toFixed(4)}, CL = ${o.toFixed(4)}, PER = ${a.toFixed(4)}, Q = ${l.toFixed(4)};
const vec2 L2 = vec2(0.6608, 0.7506); // the brand's one light: from the upper right
float sdRB(vec2 p) { vec2 q = abs(p) - vec2(H); return length(max(q, 0.)) + min(max(q.x, q.y), 0.) - CR; }
// arc length of the nearest centreline point, CCW, 0 at the bottom-right corner's 45-degree point
float pathS(vec2 p) {
if (abs(p.x) <= H && abs(p.y) <= H) { if (abs(p.x) > abs(p.y)) p.x = sign(p.x) * (H + 1e-3); else p.y = sign(p.y) * (H + 1e-3); }
float s;
if (p.x > H && p.y > H) s = SL + atan(p.y - H, p.x - H) * CR;
else if (p.x < -H && p.y > H) s = 2. * SL + CL + (atan(p.y - H, p.x + H) - HPI) * CR;
else if (p.x < -H && p.y < -H) s = 3. * SL + 2. * CL + atan(-(p.y + H), -(p.x + H)) * CR;
else if (p.x > H && p.y < -H) s = 4. * SL + 3. * CL + (atan(p.y + H, p.x - H) + HPI) * CR;
else if (p.x > H) s = p.y + H;
else if (p.y > H) s = SL + CL + (H - p.x);
else if (p.x < -H) s = 2. * SL + 2. * CL + (H - p.y);
else s = 3. * SL + 3. * CL + (p.x + H);
return mod(s + CL * 0.5, PER);
}
float hash11(float n) { return fract(sin(n * 127.1 + 11.7) * 43758.5453); }
float hash12(vec2 p) { vec3 p3 = fract(vec3(p.xyx) * .1031); p3 += dot(p3, p3.yzx + 33.33); return fract((p3.x + p3.y) * p3.z); }
vec2 hash22(vec2 p) { vec3 p3 = fract(vec3(p.xyx) * vec3(.1031, .1030, .0973)); p3 += dot(p3, p3.yzx + 33.33); return fract((p3.xx + p3.yz) * p3.zy); }
// simplex noise 3D (Ashima Arts / Stefan Gustavson, MIT)
vec3 mod289(vec3 x) { return x - floor(x * (1. / 289.)) * 289.; }
vec4 mod289(vec4 x) { return x - floor(x * (1. / 289.)) * 289.; }
vec4 permute(vec4 x) { return mod289(((x * 34.) + 1.) * x); }
vec4 taylorInvSqrt(vec4 r) { return 1.79284291400159 - 0.85373472095314 * r; }
float snoise(vec3 v) {
const vec2 C = vec2(1. / 6., 1. / 3.); const vec4 D = vec4(0., .5, 1., 2.);
vec3 i = floor(v + dot(v, C.yyy)); vec3 x0 = v - i + dot(i, C.xxx);
vec3 g = step(x0.yzx, x0.xyz); vec3 l = 1. - g; vec3 i1 = min(g.xyz, l.zxy); vec3 i2 = max(g.xyz, l.zxy);
vec3 x1 = x0 - i1 + C.xxx; vec3 x2 = x0 - i2 + C.yyy; vec3 x3 = x0 - D.yyy;
i = mod289(i);
vec4 p = permute(permute(permute(i.z + vec4(0., i1.z, i2.z, 1.)) + i.y + vec4(0., i1.y, i2.y, 1.)) + i.x + vec4(0., i1.x, i2.x, 1.));
float n_ = 0.142857142857; vec3 ns = n_ * D.wyz - D.xzx;
vec4 j = p - 49. * floor(p * ns.z * ns.z);
vec4 x_ = floor(j * ns.z); vec4 y_ = floor(j - 7. * x_);
vec4 x = x_ * ns.x + ns.yyyy; vec4 y = y_ * ns.x + ns.yyyy; vec4 h = 1. - abs(x) - abs(y);
vec4 b0 = vec4(x.xy, y.xy); vec4 b1 = vec4(x.zw, y.zw);
vec4 s0 = floor(b0) * 2. + 1.; vec4 s1 = floor(b1) * 2. + 1.; vec4 sh = -step(h, vec4(0.));
vec4 a0 = b0.xzyw + s0.xzyw * sh.xxyy; vec4 a1 = b1.xzyw + s1.xzyw * sh.zzww;
vec3 p0 = vec3(a0.xy, h.x); vec3 p1 = vec3(a0.zw, h.y); vec3 p2 = vec3(a1.xy, h.z); vec3 p3 = vec3(a1.zw, h.w);
vec4 norm = taylorInvSqrt(vec4(dot(p0, p0), dot(p1, p1), dot(p2, p2), dot(p3, p3)));
p0 *= norm.x; p1 *= norm.y; p2 *= norm.z; p3 *= norm.w;
vec4 m = max(.6 - vec4(dot(x0, x0), dot(x1, x1), dot(x2, x2), dot(x3, x3)), 0.); m = m * m;
return 42. * dot(m * m, vec4(dot(p0, x0), dot(p1, x1), dot(p2, x2), dot(p3, x3)));
}
// premultiplied "over": c with coverage a goes on top of dst
void over(inout vec4 dst, vec3 c, float a) { a = clamp(a, 0., 1.); dst = vec4(c * a, a) + dst * (1. - a); }
vec2 frag() { return (gl_FragCoord.xy - 0.5 * uRes) * uPx; }
`,L=`
uniform float uHead, uLen, uSurge, uMid, uFlowA, uFlowB, uFlowW;
uniform sampler2D uWet; // how recently each stretch of pipe was under water, 1 = now
const float RI = 0.84; // bore radius / outer radius: the rest is glass wall
const float MEN = 0.55; // meniscus depth, fraction of bore radius
// x: coverage, y: distance behind the head along the pipe, z: distance inside the nearest meniscus
vec3 slug(float s, float vi) {
float rel = mod(uHead - s + 24., PER) - 24.;
float gap = PER - uLen, full = 1. - smoothstep(0.3, 1.5, gap); // O: the two ends meet and the ring closes
float c = sqrt(max(0., 1. - vi * vi));
float m = MEN * HW * RI * smoothstep(0., 30., gap);
float front = m * c * (1. - 0.4 * uSurge); // concave: the water climbs the wall ahead of the centre
float back = uLen + m * (1. - c) * (1. + 0.4 * uSurge);
float dIn = mix(min(rel - front, back - rel), 60., full);
return vec3(clamp(dIn / uPx + 0.5, 0., 1.), rel, dIn);
}
// noise laid on a circle, so the texture wraps the loop without a seam
float ringNoise(float s, float vi, float freq, float z) {
float a = 6.2831853 * s / PER, R = PER / 6.2831853 * freq;
return snoise(vec3(R * cos(a) + uTime * 0.3, R * sin(a) - uTime * 0.2, vi * 1.25 + z));
}
float flowTex(float s, float vi, float z) {
return 0.5 + 0.5 * (0.6 * ringNoise(s, vi, 0.06, z) + 0.28 * ringNoise(s, vi * 1.8, 0.13, z + 3.1) + 0.12 * ringNoise(s, vi * 3.6, 0.27, z + 7.7));
}
void main() {
vec2 p = frag();
vec4 o = vec4(0.);
// contact shadow thrown down-left, and the light the water focuses into it
vec2 so = -L2 * 5.5;
vec2 ps = p - so;
float dsh = sdRB(ps);
float sr = abs(dsh) / HW; // glass passes most light: the shadow is darkest under the walls
o.a = (1. - smoothstep(-4., 10., abs(dsh) - HW)) * mix(0.05, 0.2, uDark) + exp(-pow((sr - 0.95) / 0.35, 2.)) * mix(0.08, 0.06, uDark);
{
vec3 Ws = slug(pathS(ps), clamp(dsh / (HW * RI), -1., 1.));
float cz = exp(-pow((dsh / HW + 0.2) / 0.3, 2.)) * Ws.x;
o.rgb += mix(uColor, vec3(1.), 0.25) * cz * mix(0.45, 0.12, uDark);
}
float dc = sdRB(p);
float v = dc / HW;
float tube = clamp((HW - abs(dc)) / uPx + 0.5, 0., 1.);
if (tube <= 0.) { gl_FragColor = o; return; }
vec2 n2 = normalize(p - clamp(p, -H, H) + 1e-4);
vec2 t2 = vec2(-n2.y, n2.x);
float s = pathS(p);
float vc = clamp(v, -1., 1.);
vec3 N = vec3(n2 * vc, sqrt(max(0., 1. - vc * vc)));
vec3 Ld = normalize(vec3(L2 * 0.78, 0.62));
vec3 Hh = normalize(Ld + vec3(0., 0., 1.));
vec3 gTint = mix(vec3(0.42, 0.50, 0.53), vec3(0.78, 0.88, 0.92), uDark);
vec3 hiC = vec3(1.0, 0.985, 0.95);
// glass: the walls are thicker to the eye near the silhouette
float gl = 2. * (sqrt(max(0., 1. - vc * vc)) - sqrt(max(0., RI * RI - vc * vc)));
float gA = 1. - exp(-gl * 0.42);
over(o, gTint, gA * 0.3 * tube);
float vi = clamp(v / RI, -1., 1.);
float bore = clamp((RI * HW - abs(dc)) / uPx + 0.5, 0., 1.);
vec3 W = slug(s, vi);
float cov = W.x * bore;
vec2 hl = vec2(dot(L2, -t2), dot(L2, n2)); // light direction in the slug's local frame
vec3 wetC = mix(uColor, vec3(1.), 0.35);
// where the water has just left: a film on the walls and beads that drain away
float wet = texture2D(uWet, vec2(s / PER, 0.5)).r * (1. - W.x);
if (wet > 0.01 && bore > 0.) {
over(o, wetC, wet * 0.22 * smoothstep(0.5, 0.95, abs(vi)) * bore);
float cs = PER / 110.;
float gx = floor(s / cs), gy = floor((vi + 1.) * 2.);
for (int a = -1; a <= 1; a++) for (int b = -1; b <= 1; b++) {
vec2 cell = vec2(gx + float(a), gy + float(b));
if (cell.y < 0. || cell.y > 3.) continue;
vec2 hc = vec2(mod(cell.x, 110.), cell.y);
vec2 h = hash22(hc);
float h3 = hash12(hc.yx + 17.);
float pres = smoothstep(h3, h3 + 0.3, wet * 1.2) * step(0.45, hash12(hc + 3.7));
if (pres <= 0.01) continue;
vec2 c = vec2((cell.x + h.x) * cs, clamp(-1. + (cell.y + h.y) * 0.5, -0.88, 0.88));
float r = mix(0.35, 1.3, h.x * h.y) * sqrt(pres);
vec2 dl = vec2(s - c.x, (vi - c.y) * RI * HW);
float d = length(dl) - r;
float fill = clamp(-d / uPx + 0.5, 0., 1.) * bore;
over(o, wetC * 0.75, fill * 0.45);
over(o, uColor * 0.4, exp(-pow(d / 0.25, 2.)) * 0.35 * bore);
over(o, hiC, exp(-pow(length(dl - vec2(-hl.x, hl.y) * r * 0.45) / (0.28 * r + 0.08), 2.)) * 0.85 * bore);
}
}
if (cov > 0.) {
float th = sqrt(max(0., 1. - vi * vi));
float kv = 1. + 0.4 * (1. - 2. * vi * vi); // the centre runs ahead of the walls
float tex = mix(flowTex(s - kv * uFlowA, vi, 0.), flowTex(s - kv * uFlowB, vi, 7.3), uFlowW);
float side = dot(n2 * vi, L2);
vec3 wc = mix(mix(uColor, vec3(1.), 0.55), uColor, smoothstep(0.05, 0.9, th)); // Beer-Lambert: thicker is deeper
wc *= 1. - 0.55 * smoothstep(0.62, 1.0, abs(vi)); // total internal reflection at the wall
wc += mix(uColor, vec3(1.), 0.65) * exp(-pow((side + 0.42) / 0.17, 2.)) * 0.42; // caustic on the far wall
wc *= 0.8 + 0.4 * tex;
float spA = smoothstep(0.62, 0.9, ringNoise(s - kv * uFlowA, vi * 4., 0.45, 11.));
float spB = smoothstep(0.62, 0.9, ringNoise(s - kv * uFlowB, vi * 4., 0.45, 19.));
wc += 0.25 * mix(spA, spB, uFlowW);
wc *= 1. - 0.6 * exp(-pow(W.z / 1.1, 2.)); // meniscus: dark refracted band
wc += 0.5 * exp(-pow((W.z - 2.1) / 0.7, 2.)) * mix(uColor, vec3(1.), 0.75); // and its bright inner lip
over(o, wc, (0.58 + 0.34 * th + 0.2 * exp(-pow(W.z / 1.5, 2.))) * cov);
// entrained bubbles ride the flow; they only move when the water does
float full = 1. - smoothstep(0.3, 1.5, PER - uLen);
for (int i = 0; i < 12; i++) {
float fi = float(i);
float bv = (hash11(fi + 1.3) * 2. - 1.) * 0.62;
float br = mix(0.5, 1.9, hash11(fi + 7.9) * hash11(fi + 3.1));
float bk = 1. + 0.35 * (1. - 2. * bv * bv) + 0.2 * (hash11(fi + 4.4) - 0.5);
float bs = mod(hash11(fi + 9.2) * PER + bk * uMid, PER);
float bx = mod(uHead - bs + 24., PER) - 24.;
float fade = mix(smoothstep(4., 9., bx) * smoothstep(uLen, uLen - 9., bx), 1., full);
vec2 dl = vec2(W.y - bx, (vi - bv) * RI * HW);
dl.x -= PER * floor(dl.x / PER + 0.5);
float d = length(dl) - br;
if (d < 1.2 && fade > 0.) {
float f = fade * cov;
over(o, mix(wc, vec3(1.), 0.5), clamp(-d / uPx + 0.5, 0., 1.) * 0.3 * f);
over(o, wc * 0.3, exp(-pow(d / 0.28, 2.)) * 0.6 * f);
over(o, hiC, exp(-pow(length(dl - hl * br * 0.42) / (0.22 * br + 0.12), 2.)) * 0.9 * f);
}
}
}
// front wall, reflections
over(o, gTint, gA * 0.3 * tube);
float ndh = max(dot(N, Hh), 0.);
float spec = pow(ndh, 110.) * 0.95 + pow(ndh, 14.) * 0.09;
spec += pow(max(dot(vec3(-N.xy, N.z), Hh), 0.), 70.) * 0.28; // the back inner surface
float fres = pow(1. - N.z, 3.) * mix(0.12, 0.3, uDark);
float wl = exp(-pow((abs(v) - RI) * HW / 0.3, 2.)) * 0.2; // bore wall seen edge-on
over(o, hiC, (spec + fres + wl) * tube);
over(o, gTint * 0.55, exp(-pow((abs(v) - 1.) * HW / 0.45, 2.)) * mix(0.45, 0.1, uDark) * tube);
gl_FragColor = o;
}`,v=`
uniform vec4 uPuff[${c}]; // one puff per stretch of the frame: centre xy, radius, weight
const float W0 = ${f.toFixed(4)};
float fbm(vec3 p) { float f = 0., a = 0.55; for (int i = 0; i < 4; i++) { f += a * snoise(p); p = p * 2.03 + vec3(1.7, 9.2, 3.1); a *= 0.42; } return f; }
vec2 warpAt(vec2 p) { vec3 np = vec3(p * 0.022, uTime * 0.12); return vec2(snoise(np), snoise(np + vec3(19.1, 7.3, 3.7))); }
// x: density, y: mean growth of the puffs here (released smoke has grown)
vec2 puffs(vec2 p, vec2 warp) {
float D = 0., G = 0.;
for (int i = 0; i < ${c}; i++) {
vec4 f = uPuff[i];
float grow = f.z - W0;
vec2 q = p - warp * (1.5 + 0.6 * grow) - f.xy; // turbulence displaces older smoke further (kept below folding)
float g = f.w * exp(-dot(q, q) / (f.z * f.z));
D += g; G += g * grow;
}
return vec2(D, G / max(D, 1e-5));
}
void main() {
vec2 p = frag();
vec2 wp = warpAt(p);
vec2 P = puffs(p, wp);
float ext = min(0.5 * uRes.x * uPx - abs(p.x), 0.5 * uRes.y * uPx - abs(p.y));
P.x *= smoothstep(0., 16., ext);
if (P.x < 0.004) { gl_FragColor = vec4(0.); return; }
// billows: domain-warped noise evolving in place, eaten away as the smoke ages
vec2 pw = p - wp * (1.5 + 0.6 * P.y);
vec3 dp = vec3(pw * 0.035, uTime * 0.16);
vec2 q = vec2(snoise(dp), snoise(dp + vec3(5.2, 1.3, 2.8)));
float n = fbm(vec3(pw * 0.045 + 1.1 * q, uTime * 0.2 + 3.));
float bil = smoothstep(-0.7, 0.55, n + 0.1 - 0.04 * P.y);
float d = P.x * (0.5 + 0.75 * bil);
// light from the upper right: shade by how much smoke lies toward it
vec2 pl = p + L2 * 7.;
float dl = puffs(pl, warpAt(pl)).x;
float lit = clamp(mix(0.55, 0.85, uDark) - (dl - P.x) * mix(1.3, 0.9, uDark), 0., 1.) * (0.88 + 0.16 * bil);
float a = 1. - exp(-d * 1.9);
vec3 shade = uColor * mix(vec3(0.62, 0.64, 0.70), vec3(0.50, 0.53, 0.60), uDark);
vec3 c = mix(shade, uColor, clamp(lit, 0., 1.));
c += uColor * 0.18 * (1. - a) * lit; // thin wisps let light through
gl_FragColor = vec4(min(c, vec3(1.)) * a, a);
}`,E=`
uniform float uSegA, uLen, uMix, uMove, uHum, uTR;
uniform vec3 uColA, uColB;
uniform vec2 uPts[${h}];
vec3 emit(float s) {
float x = mod(s - uSegA, PER); // distance ahead of the tail
float din = x <= uLen ? min(x, uLen - x) : -min(x - uLen, PER - x);
din = mix(din, 1e3, step(PER - 0.5, uLen));
float on = smoothstep(-0.6, 0.6, din);
float strike = uMove * exp(-max(uLen - x, 0.) / 18.) * on; // the end being struck stutters while it runs
float fl = mix(1., 0.15 + 0.85 * step(0.3, hash12(vec2(floor(x / 6.), floor(uTime * 30.)))), strike);
float after = uMove * exp(-mod(uSegA - s, PER) / 10.) * (1. - on) * 0.6; // the tail lets go with an afterglow
vec3 col = mix(uColB, uColA, uMix);
return (col * (on * fl * (1. + 0.6 * strike) + after) + vec3(0.35) * strike * fl) * uHum;
}
void main() {
vec2 p = frag();
float dc = sdRB(p), d = abs(dc), s = pathS(p);
vec3 e = emit(s);
// light spilling onto the wall: integrated over the whole tube so every lit stretch contributes
vec3 g = vec3(0.);
for (int i = 0; i < ${h}; i++) {
vec2 dv = p - uPts[i];
float r2 = dot(dv, dv);
g += emit((float(i) + 0.5) * (PER / ${h}.)) * (exp(-r2 / 60.) + 0.35 * exp(-r2 / 420.));
}
g *= (PER / ${h}.) / 40.;
float vt = clamp(dc / uTR, -1., 1.);
float tm = clamp((uTR - d) / uPx + 0.5, 0., 1.);
float I = max(max(e.r, e.g), e.b);
float core = exp(-vt * vt * 3.2);
vec3 tubeL = e * (0.4 + 0.85 * core) + vec3(1.) * I * pow(core, 4.) * 0.55; // white-hot centre, saturated rim
vec3 nearL = e * exp(-max(d - uTR * 0.8, 0.) / 1.2) * 0.6;
vec3 L = g + nearL * (1. - tm) + tubeL * tm;
vec3 mapped = 1. - exp(-L * 1.25);
// the glass itself, visible where it is dark
vec2 n2 = normalize(p - clamp(p, -H, H) + 1e-4);
vec3 N = vec3(n2 * vt, sqrt(max(0., 1. - vt * vt)));
vec3 Hh = normalize(normalize(vec3(L2 * 0.78, 0.62)) + vec3(0., 0., 1.));
vec3 gTint = mix(vec3(0.22, 0.24, 0.27), vec3(0.62, 0.66, 0.72), uDark);
vec4 o = vec4(0.);
over(o, gTint, tm * (0.14 + 0.35 * pow(1. - N.z, 2.)) * (1. - clamp(I, 0., 1.) * 0.6));
if (uDark > 0.5) o.rgb += mapped;
else { // on paper light can't add; lay the hue down instead, keeping it saturated
vec3 Lc = g + nearL * (1. - tm) + e * (0.4 + 0.85 * core) * tm;
float m = max(max(Lc.r, Lc.g), Lc.b);
over(o, Lc / max(m, 1e-3), (1. - exp(-m * 1.4)) * mix(0.85, 1., tm));
over(o, vec3(1.), pow(core, 4.) * min(I, 1.) * 0.6 * tm);
}
over(o, vec3(1.), pow(max(dot(N, Hh), 0.), 60.) * 0.5 * tm);
gl_FragColor = o;
}`,p={water:L,smoke:v,neon:E},y={water:1.3,smoke:1.9,neon:1.8},x={water:{color:"#2FA8FF"},smoke:{color:"#F5F5F2"},neon:{colors:["#FF2E88","#2EF0FF","#FFB020","#7CFF4F","#9B5CFF"],tube:.58}},M={sequence:"LUCIO",hold:.7,morph:.45,speed:1,size:96},F=m=>{let S=m.replace("#",""),z=S.length===3?S.split("").map(d=>d+d).join(""):S;return[0,2,4].map(d=>parseInt(z.slice(d,d+2),16)/255)},w=()=>n.matchMedia&&n.matchMedia("(prefers-reduced-motion: reduce)").matches,T=m=>m<.5?4*m*m*m:1-Math.pow(-2*m+2,3)/2,A=m=>m-Math.floor(m),P=m=>A(Math.sin(m*127.1+11.7)*43758.5453),N=(m,S,z)=>{let d=Math.min(1,Math.max(0,(z-m)/(S-m)));return d*d*(3-2*d)};function C(m){for(let S=m;S&&S.nodeType===1;S=S.parentElement){let z=getComputedStyle(S).backgroundColor.match(/[\d.]+/g);if(z&&(z.length<4||+z[3]>.5))return(.2126*z[0]+.7152*z[1]+.0722*z[2])/255<.5}return!!(n.matchMedia&&n.matchMedia("(prefers-color-scheme: dark)").matches)}let R={C:[0,.75],L:[.25,.75],U:[.25,1],I:[.75,1],O:[.75,1.75]};function _(m){let S=()=>{let X=(m.sequence||"LUCIO").toUpperCase().split("").filter(U=>R[U]);return X.length?X:["O"]},z=(X,U)=>{let[q,I]=R[U];for(let j=-1;j<6;j++)if(q+j>=X[0]-1e-6&&I+j>=X[1]-1e-6)return[q+j,I+j];return[q,I]},d={i:0,j:0,seg:R[S()[0]].slice(),u:1,f:1,moving:!1,travel:0,vHead:0},H=d.seg,D=d.seg,u=0;return d.step=X=>{let U=d.seg.slice();if(u+=X,!d.moving&&u>=m.hold){let q=S();d.j=(d.i+1)%q.length,H=d.seg.slice(),D=z(d.seg,q[d.j]),d.moving=!0,u-=m.hold}if(d.moving){let q=w()?0:m.morph;d.f=q>0?Math.min(1,u/q):1,d.u=T(d.f),d.seg=[H[0]+(D[0]-H[0])*d.u,H[1]+(D[1]-H[1])*d.u],d.f>=1&&(d.moving=!1,d.i=d.j,u=0)}else d.f=1,d.u=1;if(d.travel+=(d.seg[0]-U[0]+(d.seg[1]-U[1]))/2*a,d.vHead=X>0?(d.seg[1]-U[1])*a/X:0,!d.moving){let q=Math.floor(d.seg[0]);d.seg[0]-=q,d.seg[1]-=q}},d.units=()=>({a:a*(d.seg[0]+.25),len:Math.min(a,(d.seg[1]-d.seg[0])*a)}),d.reset=()=>{d.i=d.j=0,d.seg=R[S()[0]].slice(),d.moving=!1,u=0},d}let O=new Set,$=0,Q=0;function pe(m){let S=Q?Math.min(.1,(m-Q)/1e3):0;Q=m;for(let z of O)z.frame(S);$=O.size?requestAnimationFrame(pe):0,$||(Q=0)}function oe(m,S,z){let d=Object.assign({},M,x[m],z||{}),H=document.createElement("div");H.className="lucio-fx lucio-fx-"+m,H.setAttribute("role","img"),H.setAttribute("aria-label","Loading"),H.style.cssText="position:relative;display:inline-block;vertical-align:middle;flex:none";let D=document.createElement("canvas");D.style.cssText="position:absolute;pointer-events:none",H.appendChild(D),S.appendChild(H);let u=D.getContext("webgl",{premultipliedAlpha:!0,alpha:!0,antialias:!1});if(!u)return console.warn("LucioLoaders: WebGL unavailable"),null;let X=(k,K)=>{let W=u.createShader(k);if(u.shaderSource(W,K),u.compileShader(W),!u.getShaderParameter(W,u.COMPILE_STATUS))throw new Error(m+": "+u.getShaderInfoLog(W));return W},U=u.createProgram();if(u.attachShader(U,X(u.VERTEX_SHADER,"attribute vec2 a; void main(){ gl_Position = vec4(a, 0., 1.); }")),u.attachShader(U,X(u.FRAGMENT_SHADER,g+p[m])),u.linkProgram(U),!u.getProgramParameter(U,u.LINK_STATUS))throw new Error(m+": "+u.getProgramInfoLog(U));u.useProgram(U),u.bindBuffer(u.ARRAY_BUFFER,u.createBuffer()),u.bufferData(u.ARRAY_BUFFER,new Float32Array([-1,-1,3,-1,-1,3]),u.STATIC_DRAW),u.enableVertexAttribArray(0),u.vertexAttribPointer(0,2,u.FLOAT,!1,0,0);let q={},I=k=>k in q?q[k]:q[k]=u.getUniformLocation(U,k);if(m==="neon"){let k=[];for(let K=0;K<h;K++)k.push(...b((K+.5)*a/h));u.uniform2fv(I("uPts[0]"),new Float32Array(k))}let j=64,mt=new Float32Array(j).fill(-1e3),ft=new Uint8Array(j);m==="water"&&(u.bindTexture(u.TEXTURE_2D,u.createTexture()),u.texParameteri(u.TEXTURE_2D,u.TEXTURE_MIN_FILTER,u.LINEAR),u.texParameteri(u.TEXTURE_2D,u.TEXTURE_MAG_FILTER,u.LINEAR),u.texParameteri(u.TEXTURE_2D,u.TEXTURE_WRAP_S,u.REPEAT),u.texParameteri(u.TEXTURE_2D,u.TEXTURE_WRAP_T,u.CLAMP_TO_EDGE),u.uniform1i(I("uWet"),0));let vt=new Float32Array(c*4),ae=new Float32Array(c),ye=new Float32Array(c),Y=_(d),gt=(k,K,W)=>{if(W>=a-.5)return 1e3;let G=((k-K)%a+a)%a;return G<=W?Math.min(G,W-G):-Math.min(G-W,a-G)},ie=0,Ge=d.theme==="light"?!1:d.theme==="dark"?!0:C(S),Zt=0,bt=!0,xe=n.IntersectionObserver?new IntersectionObserver(k=>{bt=k[0].isIntersecting}):null;xe&&xe.observe(H);function yt(k){d.size=k;let K=Math.min(n.devicePixelRatio||1,2),W=k*y[m];H.style.width=H.style.height=k+"px",D.style.width=D.style.height=W+"px",D.style.left=D.style.top=-(W-k)/2+"px",D.width=D.height=Math.round(W*K),u.viewport(0,0,D.width,D.height),u.uniform2f(I("uRes"),D.width,D.height),u.uniform1f(I("uPx"),120/(k*D.width/W))}yt(d.size);function xt(k){if((d.theme==="auto"||!d.theme)&&++Zt%30===0&&(Ge=C(S)),!bt)return;k*=d.speed,ie+=k*(w()?.35:1),Y.step(k);let{a:K,len:W}=Y.units();if(u.uniform1f(I("uTime"),ie),u.uniform1f(I("uDark"),Ge?1:0),m==="water"){let le=A(Y.travel/70),B=A(Y.travel/70+.5);u.uniform3fv(I("uColor"),F(d.color)),u.uniform1f(I("uHead"),K+W),u.uniform1f(I("uLen"),W),u.uniform1f(I("uSurge"),Math.min(1,Math.max(0,Y.vHead/700))),u.uniform1f(I("uMid"),Y.travel),u.uniform1f(I("uFlowA"),le*70),u.uni Line truncated
+1 -1
View File
@@ -1 +1 @@
"use strict";(()=>{function k(r){let n=r.seed+"|"+r.level+"|"+r.x+"|"+r.y,o=2166136261;for(let t=0;t<n.length;t++)o=Math.imul(o^n.charCodeAt(t),16777619)>>>0;return o}function v(r,n){let o=new Array(r);for(let e=0;e<r;e++)o[e]=e;let t=n|0,a=()=>{t=t+1831565813|0;let e=Math.imul(t^t>>>15,1|t);return e=e+Math.imul(e^e>>>7,61|e)^e,((e^e>>>14)>>>0)/4294967296};for(let e=r-1;e>0;e--){let s=Math.floor(a()*(e+1)),m=o[e];o[e]=o[s],o[s]=m}return o}function g(r,n,o,t,a){r.drawImage(n,0,0);let e=a.cell,s=Math.floor(o/e),m=Math.floor(t/e),u=s*m;if(u<2)return;let d=v(u,k(a));for(let c=0;c<u;c++){let f=d[c];if(f===c)continue;let p=c%s*e,y=Math.floor(c/s)*e,h=f%s*e,w=Math.floor(f/s)*e;r.drawImage(n,p,y,e,e,h,w,e,e)}}var l=self,i=new Map,M=typeof createImageBitmap=="function",b=self.OffscreenCanvas;l.onmessage=r=>{let n=r.data;if(n.type==="abort"){i.get(n.key)?.abort(),i.delete(n.key);return}S(n)};function x(r,n){if(!b)throw new Error("unsupported-offscreen");let o=new b(r.width,r.height),t=o.getContext("2d");if(!t)throw new Error("unsupported-offscreen");return g(t,r,r.width,r.height,n),r.close(),o.transferToImageBitmap()}async function S(r){if(!M){l.postMessage({key:r.key,ok:!1,bytes:0,ms:0,error:"unsupported-bitmap"});return}if(r.scramble&&!b){l.postMessage({key:r.key,ok:!1,bytes:0,ms:0,error:"unsupported-offscreen"});return}let n=new AbortController;i.set(r.key,n);let o=performance.now();try{let t=await fetch(r.url,{signal:n.signal,credentials:"same-origin"});if(!t.ok)throw new Error("HTTP "+t.status);let a=await t.blob(),e=performance.now()-o,s=await createImageBitmap(a);if(r.scramble&&(s=x(s,r.scramble)),n.signal.aborted)throw s.close(),new Error("aborted");l.postMessage({key:r.key,ok:!0,bitmap:s,bytes:a.size,ms:e},[s])}catch(t){let a=t instanceof Error?t.message:String(t);l.postMessage({key:r.key,ok:!1,bytes:0,ms:0,error:a})}finally{i.delete(r.key)}}})();
"use strict";(()=>{function M(e){let a=e.seed+"|"+e.level+"|"+e.x+"|"+e.y,o=2166136261;for(let n=0;n<a.length;n++)o=Math.imul(o^a.charCodeAt(n),16777619)>>>0;return o}function v(e,a){let o=new Array(e);for(let t=0;t<e;t++)o[t]=t;let n=a|0,r=()=>{n=n+1831565813|0;let t=Math.imul(n^n>>>15,1|n);return t=t+Math.imul(t^t>>>7,61|t)^t,((t^t>>>14)>>>0)/4294967296};for(let t=e-1;t>0;t--){let c=Math.floor(r()*(t+1)),l=o[t];o[t]=o[c],o[c]=l}return o}function w(e,a,o,n,r){e.drawImage(a,0,0);let t=r.cell,c=Math.floor(o/t),l=Math.floor(n/t);if(c<2||l<2)return;let s=c*l,i=v(s,M(r));for(let f=0;f<s;f++){let b=i[f];if(b===f)continue;let x=f%c*t,m=Math.floor(f/c)*t,h=b%c*t,I=Math.floor(b/c)*t;e.drawImage(a,x,m,t,t,h,I,t,t)}}var C=new Int32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),A=new Int32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);function S(e,a){for(let o=a;o<64;o++){let n=e[o-15],r=e[o-2],t=(n>>>7|n<<25)^(n>>>18|n<<14)^n>>>3,c=(r>>>17|r<<15)^(r>>>19|r<<13)^r>>>10;e[o]=e[o-16]+t+e[o-7]+c|0}}function k(e,a,o,n){let r=e[0],t=e[1],c=e[2],l=e[3],s=e[4],i=e[5],f=e[6],b=e[7];for(let x=o;x<n;x++){let m=b+((s>>>6|s<<26)^(s>>>11|s<<21)^(s>>>25|s<<7))+(s&i^~s&f)+C[x]+a[x]|0,h=((r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10))+(r&t^r&c^t&c)|0;b=f,f=i,i=s,s=l+m|0,l=c,c=t,t=r,r=m+h|0}e[0]=r,e[1]=t,e[2]=c,e[3]=l,e[4]=s,e[5]=i,e[6]=f,e[7]=b}var E=new Int32Array(64),T=new Int32Array(8),j=new Int32Array(8);var p=4294967296,d=class{constructor(a,o){this.w=new Int32Array(64);this.mid=new Int32Array(8);this.s=new Int32Array(8);let n=this.w;for(let r=0;r<8;r++)n[r]=a.charCodeAt(r*4)<<24|a.charCodeAt(r*4+1)<<16|a.charCodeAt(r*4+2)<<8|a.charCodeAt(r*4+3);n[10]=-2147483648,n[15]=320,this.mid.set(A),k(this.mid,n,0,8),this.shift=32-Math.max(1,Math.min(32,o))}run(a,o,n){let r=this.w,t=this.s,c=this.mid,l=this.shift,s=A[0];r[8]=a|0;for(let i=o;i<n;i++)if(r[9]=i|0,S(r,16),t.set(c),k(t,r,8,64),!(s+t[0]>>>l))return i;return-1}};var u=self,y=new Map,U=typeof createImageBitmap=="function",g=self.OffscreenCanvas;u.onmessage=e=>{let a=e.data;if(a.type==="pow"){let o=new d(a.token,a.bits);for(let n=0;n<2097152;n++){let r=o.run(n,0,p);if(r>=0){u.postMessage({pow:n*p+r});return}}u.postMessage({pow:-1});return}if(a.type==="abort"){y.get(a.key)?.abort(),y.delete(a.key);return}O(a)};function B(e,a){if(!g)throw new Error("unsupported-offscreen");let o=new g(e.width,e.height),n=o.getContext("2d");if(!n)throw new Error("unsupported-offscreen");return w(n,e,e.width,e.height,a),e.close(),o.transferToImageBitmap()}async function O(e){if(!U){u.postMessage({key:e.key,ok:!1,bytes:0,ms:0,error:"unsupported-bitmap"});return}if(e.scramble&&!g){u.postMessage({key:e.key,ok:!1,bytes:0,ms:0,error:"unsupported-offscreen"});return}let a=new AbortController;y.set(e.key,a);let o=performance.now();try{let n=await fetch(e.url,{signal:a.signal,credentials:"same-origin"});if(!n.ok)throw new Error("HTTP "+n.status);let r=await n.blob(),t=performance.now()-o,c=await createImageBitmap(r);if(e.scramble&&(c=B(c,e.scramble)),a.signal.aborted)throw c.close(),new Error("aborted");u.postMessage({key:e.key,ok:!0,bitmap:c,bytes:r.size,ms:t},[c])}catch(n){let r=n instanceof Error?n.message:String(n);u.postMessage({key:e.key,ok:!1,bytes:0,ms:0,error:r})}finally{y.delete(e.key)}}})();
-1
View File
@@ -16,6 +16,5 @@
<noscript><p>This album needs JavaScript to draw its photos.</p></noscript>
<p><a href="/">All albums</a></p>
</div>
<template id="chop-template"><span class="chop">{{.Assets.Chop}}</span></template>
</body>
</html>
+1 -1
View File
@@ -24,7 +24,7 @@
<link rel="stylesheet" href="{{.Assets.CSS.URL}}">
<script src="{{.Assets.JS.URL}}" defer></script>
{{- end}}
{{define "body-data"}} data-build="{{.Build}}" data-index="{{.IndexURL}}" data-worker="{{.Assets.Worker.URL}}" data-budget-ms="{{.BudgetMS}}" data-max-dpr="{{.MaxDPR}}" data-concurrency="{{.Concurrency}}" data-block-context-menu="{{.BlockContextMenu}}"{{end}}
{{define "body-data"}} data-build="{{.Build}}" data-index="{{.IndexURL}}" data-worker="{{.Assets.Worker.URL}}" data-budget-ms="{{.BudgetMS}}" data-max-dpr="{{.MaxDPR}}" data-concurrency="{{.Concurrency}}" data-block-context-menu="{{.BlockContextMenu}}" data-gate="{{.Gate}}" data-min-entropy="{{.MinEntropy}}"{{end}}
{{define "footer"}}<footer class="site-footer">
<p class="footer-line">Guoliang Chen · <span lang="zh">陈国梁</span> · Lucio</p>
<span class="chop">{{.Assets.Chop}}</span>
+13 -3
View File
@@ -6,7 +6,10 @@ photos.luciochen.com {
header Referer *
not header_regexp Referer ^https?://photos\.luciochen\.com(:[0-9]+)?(/|$)
}
respond @hotlink 403
handle @hotlink {
header Cache-Control "no-store"
respond 403
}
@hidden path */.* *.gz
error @hidden 404
@@ -14,7 +17,7 @@ photos.luciochen.com {
@immutable path /t/* /og/* /assets/*
header @immutable Cache-Control "public, max-age=31536000, immutable"
@short not path /t/* /og/* /assets/*
@short not path /t/* /og/* /assets/* /k
header @short Cache-Control "public, max-age=60"
header {
@@ -24,7 +27,14 @@ photos.luciochen.com {
-Server
}
@methods not method GET HEAD
handle /k {
reverse_proxy 127.0.0.1:8080
}
@methods {
not method GET HEAD
not path /k
}
respond @methods 405
file_server {
+20 -5
View File
@@ -1,10 +1,25 @@
# Cloudflare
Run the site behind a Cloudflare Tunnel (`cloudflared.yml` in this folder). In serve mode the tunnel points at LuPhoto on `127.0.0.1:8080`. In export mode it points at Caddy or nginx; give that web server a plain HTTP listener on `127.0.0.1:8080` for the tunnel, for example `http://photos.luciochen.com:8080` in the Caddyfile, or `listen 127.0.0.1:8080;` in nginx.
Run the site behind a Cloudflare Tunnel (`cloudflared.yml` in this folder). In serve mode the tunnel points at LuPhoto on `127.0.0.1:8080`. In export mode it points at Caddy or nginx, and LuPhoto itself listens on `server.listen` (`127.0.0.1:8080` by default) for the key endpoint `/k`, so give the web server a different plain HTTP listener for the tunnel, for example `http://photos.luciochen.com:8081` in the Caddyfile, or `listen 127.0.0.1:8081;` in nginx, and point the tunnel there.
Cache rules (Caching → Cache Rules), in this order:
## Client addresses
1. Tiles, OG images and assets: when the URI path starts with `/t/`, `/og/` or `/assets/`, set *Eligible for cache*, Edge TTL 1 month (or "use cache-control header"), Browser TTL "respect origin". Their names are content-hashed, so they never change.
2. Everything else (HTML, `/a/*`, `index.<build>.json`): Edge TTL 1 minute or "respect origin" (`max-age=60`). Manifests are named after the build, so a new build needs no purge.
LuPhoto limits photo keys per visitor address, so it must see the real one. Through the tunnel every request reaches the origin from `cloudflared` on loopback, and Cloudflare puts the visitor's address in `CF-Connecting-IP`. In `/etc/luphoto/config.toml`:
Keep "Cache by device type" and query-string variations off. Hotlink protection is done by LuPhoto, Caddy or nginx on `/t/*`; Cloudflare's own Hotlink Protection can stay off, or be enabled for the same hostname.
```toml
[server]
trusted_proxies = ["127.0.0.1/32", "::1/128"]
client_ip_header = "CF-Connecting-IP"
```
`trusted_proxies` must list the address the request comes from when it reaches LuPhoto: loopback for `cloudflared`, Caddy or nginx on the same machine (they pass `CF-Connecting-IP` through unchanged). If `cloudflared` runs on another host, add that host's address. Never trust a range the public can connect from directly, or anyone can choose their own address. Without the tunnel, behind Caddy or nginx only, keep the default `"X-Forwarded-For"`.
## Cache rules
Caching → Cache Rules, in this order:
1. Key endpoint: when the URI path equals `/k`, *Bypass cache*. It is a per-visitor `POST` answered with `Cache-Control: no-store`; it must never be cached or served from the edge.
2. Tiles, OG images and assets: when the URI path starts with `/t/`, `/og/` or `/assets/`, set *Eligible for cache*, Edge TTL 1 month (or "use cache-control header"), Browser TTL "respect origin". Their names are content-hashed, so they never change. A tile URL depends only on the photo's bytes, the processing settings and the site key in `/var/lib/luphoto/state/site.key`, so it stays the same across builds and restarts; back up that key, because a new one gives every tile a new URL and empties the edge cache.
3. Everything else (HTML, `/a/*` including the per-photo pool files under `/a/<slug>/p/`, `index.<build>.json`, `robots.txt`): Edge TTL 1 minute or "respect origin" (`max-age=60`). Manifests and pool files are named after the build, so a new build needs no purge. Decoy tiles under `/t/` never change their bytes either, so rule 2 holds for them.
Keep "Cache by device type" and query-string variations off. Once a tile is in the edge cache, Cloudflare serves it without asking the origin, so the `Referer` check in LuPhoto, Caddy or nginx only sees cache misses (its 403 is sent with `Cache-Control: no-store`, so a refused request is never cached for real visitors). To block hotlinking of cached tiles too, add a WAF custom rule: when the URI path starts with `/t/`, the `Referer` header is not empty and it does not start with `https://photos.luciochen.com/`, *Block*. Cloudflare's Scrape Shield Hotlink Protection works as well, but it only covers image extensions it knows. `/k` checks `Origin` itself. Bot Fight Mode and similar challenges must not be applied to `/k`, because they would answer the browser's `fetch` with an HTML page.
+16 -5
View File
@@ -1,7 +1,9 @@
[server]
mode = "export"
listen = "127.0.0.1:8080"
base_url = "https://photos.luciochen.com"
mode = "export"
listen = "127.0.0.1:8080"
base_url = "https://photos.luciochen.com"
trusted_proxies = ["127.0.0.1/32", "::1/128"]
client_ip_header = "X-Forwarded-For"
[paths]
albums = "/srv/luphoto/albums"
@@ -12,11 +14,12 @@ cache = "/var/cache/luphoto"
tile_size = 512
overlap = 1
format = "webp"
quality = { top = 82, mid = 85, low = 88 }
quality = { top = 90, mid = 88, low = 88 }
min_levels = 6
seed_px = 48
tile_names = "hashed"
scramble_cells = false
scramble_cells = true
min_grid = 3
[loading]
budget_ms = 3000
@@ -32,3 +35,11 @@ keep_builds = 3
[protection]
block_context_menu = true
hotlink_allow = ["photos.luciochen.com"]
decoys = 4
gate = "server"
pow_bits = 20
photo_limit = 400
min_entropy = 20
landing_limit = 5
window = "10m"
pass_ttl = "12h"
+17 -1
View File
@@ -4,6 +4,12 @@ map $http_referer $luphoto_hotlink {
"~^https?://photos\.luciochen\.com(:[0-9]+)?(/|$)" 0;
}
map "$request_method $uri" $luphoto_bad_method {
default 1;
"~^(GET|HEAD) " 0;
"POST /k" 0;
}
server {
listen 443 ssl;
listen [::]:443 ssl;
@@ -21,7 +27,7 @@ server {
server_tokens off;
error_page 404 /404.html;
if ($request_method !~ ^(GET|HEAD)$) {
if ($luphoto_bad_method) {
return 405;
}
@@ -29,6 +35,15 @@ server {
return 404;
}
location = /k {
client_max_body_size 4k;
proxy_pass http://127.0.0.1:8080;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Connection "";
}
location = /404.html {
internal;
add_header Cache-Control "public, max-age=60" always;
@@ -39,6 +54,7 @@ server {
location /t/ {
if ($luphoto_hotlink) {
add_header Cache-Control "no-store" always;
return 403;
}
add_header Cache-Control "public, max-age=31536000, immutable" always;
+1
View File
@@ -12,6 +12,7 @@ server {
proxy_pass http://127.0.0.1:8080;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Connection "";
proxy_buffering on;
}
+4 -3
View File
@@ -3,10 +3,10 @@ set -euo pipefail
scripts_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
repo_dir="$(dirname "$scripts_dir")"
brand_dir="${LUCIO_IP_DIR:-$repo_dir/../LUCIO_ip}"
brand_dir="${LUCIO_IP_DIR:-$repo_dir/../lucioIP}"
out_dir="$repo_dir/web/brand"
for required in tokens/tokens.css motion/lucio-morph.js logo/favicon.svg logo/lucio-chop-chen.svg; do
for required in tokens/tokens.css motion/lucio-morph.js motion/lucio-loaders.js logo/favicon.svg logo/lucio-chop-chen.svg; do
if [ ! -f "$brand_dir/$required" ]; then
echo "sync-brand: $brand_dir/$required not found (set LUCIO_IP_DIR)" >&2
exit 1
@@ -33,7 +33,8 @@ strip_svg() {
} > "$out_dir/tokens.css"
strip_js < "$brand_dir/motion/lucio-morph.js" > "$out_dir/lucio-morph.js"
strip_js < "$brand_dir/motion/lucio-loaders.js" > "$out_dir/lucio-loaders.js"
strip_svg < "$brand_dir/logo/favicon.svg" > "$out_dir/favicon.svg"
strip_svg < "$brand_dir/logo/lucio-chop-chen.svg" > "$out_dir/lucio-chop-chen.svg"
echo "sync-brand: copied tokens.css, lucio-morph.js, favicon.svg, lucio-chop-chen.svg from $brand_dir into $out_dir"
echo "sync-brand: copied tokens.css, lucio-morph.js, lucio-loaders.js, favicon.svg, lucio-chop-chen.svg from $brand_dir into $out_dir"
+468
View File
@@ -0,0 +1,468 @@
(function (global) {
const HB = 49.8, CR = 16.2, HW = 10.2, H = HB - CR, SL = 2 * H, CL = Math.PI / 2 * CR, PER = 4 * (SL + CL), Q = PER / 4;
const NPTS = 96, NPUFF = 64, W0 = HW * 0.85;
function pathP(s) {
s = (((s - CL / 2) % PER) + PER) % PER;
const arc = (cx, cy, a) => [cx + CR * Math.cos(a), cy + CR * Math.sin(a)];
if (s < SL) return [HB, -H + s]; s -= SL;
if (s < CL) return arc(H, H, s / CR); s -= CL;
if (s < SL) return [H - s, HB]; s -= SL;
if (s < CL) return arc(-H, H, Math.PI / 2 + s / CR); s -= CL;
if (s < SL) return [-HB, H - s]; s -= SL;
if (s < CL) return arc(-H, -H, Math.PI + s / CR); s -= CL;
if (s < SL) return [-H + s, -HB]; s -= SL;
return arc(H, -H, -Math.PI / 2 + s / CR);
}
const PRELUDE = `
precision highp float;
uniform vec2 uRes;
uniform float uPx, uTime, uDark;
uniform vec3 uColor;
#define PI 3.14159265
#define HPI 1.5707963
const float HB = ${HB.toFixed(4)}, CR = ${CR.toFixed(4)}, HW = ${HW.toFixed(4)}, H = ${H.toFixed(4)};
const float SL = ${SL.toFixed(4)}, CL = ${CL.toFixed(4)}, PER = ${PER.toFixed(4)}, Q = ${Q.toFixed(4)};
const vec2 L2 = vec2(0.6608, 0.7506); // the brand's one light: from the upper right
float sdRB(vec2 p) { vec2 q = abs(p) - vec2(H); return length(max(q, 0.)) + min(max(q.x, q.y), 0.) - CR; }
// arc length of the nearest centreline point, CCW, 0 at the bottom-right corner's 45-degree point
float pathS(vec2 p) {
if (abs(p.x) <= H && abs(p.y) <= H) { if (abs(p.x) > abs(p.y)) p.x = sign(p.x) * (H + 1e-3); else p.y = sign(p.y) * (H + 1e-3); }
float s;
if (p.x > H && p.y > H) s = SL + atan(p.y - H, p.x - H) * CR;
else if (p.x < -H && p.y > H) s = 2. * SL + CL + (atan(p.y - H, p.x + H) - HPI) * CR;
else if (p.x < -H && p.y < -H) s = 3. * SL + 2. * CL + atan(-(p.y + H), -(p.x + H)) * CR;
else if (p.x > H && p.y < -H) s = 4. * SL + 3. * CL + (atan(p.y + H, p.x - H) + HPI) * CR;
else if (p.x > H) s = p.y + H;
else if (p.y > H) s = SL + CL + (H - p.x);
else if (p.x < -H) s = 2. * SL + 2. * CL + (H - p.y);
else s = 3. * SL + 3. * CL + (p.x + H);
return mod(s + CL * 0.5, PER);
}
float hash11(float n) { return fract(sin(n * 127.1 + 11.7) * 43758.5453); }
float hash12(vec2 p) { vec3 p3 = fract(vec3(p.xyx) * .1031); p3 += dot(p3, p3.yzx + 33.33); return fract((p3.x + p3.y) * p3.z); }
vec2 hash22(vec2 p) { vec3 p3 = fract(vec3(p.xyx) * vec3(.1031, .1030, .0973)); p3 += dot(p3, p3.yzx + 33.33); return fract((p3.xx + p3.yz) * p3.zy); }
// simplex noise 3D (Ashima Arts / Stefan Gustavson, MIT)
vec3 mod289(vec3 x) { return x - floor(x * (1. / 289.)) * 289.; }
vec4 mod289(vec4 x) { return x - floor(x * (1. / 289.)) * 289.; }
vec4 permute(vec4 x) { return mod289(((x * 34.) + 1.) * x); }
vec4 taylorInvSqrt(vec4 r) { return 1.79284291400159 - 0.85373472095314 * r; }
float snoise(vec3 v) {
const vec2 C = vec2(1. / 6., 1. / 3.); const vec4 D = vec4(0., .5, 1., 2.);
vec3 i = floor(v + dot(v, C.yyy)); vec3 x0 = v - i + dot(i, C.xxx);
vec3 g = step(x0.yzx, x0.xyz); vec3 l = 1. - g; vec3 i1 = min(g.xyz, l.zxy); vec3 i2 = max(g.xyz, l.zxy);
vec3 x1 = x0 - i1 + C.xxx; vec3 x2 = x0 - i2 + C.yyy; vec3 x3 = x0 - D.yyy;
i = mod289(i);
vec4 p = permute(permute(permute(i.z + vec4(0., i1.z, i2.z, 1.)) + i.y + vec4(0., i1.y, i2.y, 1.)) + i.x + vec4(0., i1.x, i2.x, 1.));
float n_ = 0.142857142857; vec3 ns = n_ * D.wyz - D.xzx;
vec4 j = p - 49. * floor(p * ns.z * ns.z);
vec4 x_ = floor(j * ns.z); vec4 y_ = floor(j - 7. * x_);
vec4 x = x_ * ns.x + ns.yyyy; vec4 y = y_ * ns.x + ns.yyyy; vec4 h = 1. - abs(x) - abs(y);
vec4 b0 = vec4(x.xy, y.xy); vec4 b1 = vec4(x.zw, y.zw);
vec4 s0 = floor(b0) * 2. + 1.; vec4 s1 = floor(b1) * 2. + 1.; vec4 sh = -step(h, vec4(0.));
vec4 a0 = b0.xzyw + s0.xzyw * sh.xxyy; vec4 a1 = b1.xzyw + s1.xzyw * sh.zzww;
vec3 p0 = vec3(a0.xy, h.x); vec3 p1 = vec3(a0.zw, h.y); vec3 p2 = vec3(a1.xy, h.z); vec3 p3 = vec3(a1.zw, h.w);
vec4 norm = taylorInvSqrt(vec4(dot(p0, p0), dot(p1, p1), dot(p2, p2), dot(p3, p3)));
p0 *= norm.x; p1 *= norm.y; p2 *= norm.z; p3 *= norm.w;
vec4 m = max(.6 - vec4(dot(x0, x0), dot(x1, x1), dot(x2, x2), dot(x3, x3)), 0.); m = m * m;
return 42. * dot(m * m, vec4(dot(p0, x0), dot(p1, x1), dot(p2, x2), dot(p3, x3)));
}
// premultiplied "over": c with coverage a goes on top of dst
void over(inout vec4 dst, vec3 c, float a) { a = clamp(a, 0., 1.); dst = vec4(c * a, a) + dst * (1. - a); }
vec2 frag() { return (gl_FragCoord.xy - 0.5 * uRes) * uPx; }
`;
const WATER = `
uniform float uHead, uLen, uSurge, uMid, uFlowA, uFlowB, uFlowW;
uniform sampler2D uWet; // how recently each stretch of pipe was under water, 1 = now
const float RI = 0.84; // bore radius / outer radius: the rest is glass wall
const float MEN = 0.55; // meniscus depth, fraction of bore radius
// x: coverage, y: distance behind the head along the pipe, z: distance inside the nearest meniscus
vec3 slug(float s, float vi) {
float rel = mod(uHead - s + 24., PER) - 24.;
float gap = PER - uLen, full = 1. - smoothstep(0.3, 1.5, gap); // O: the two ends meet and the ring closes
float c = sqrt(max(0., 1. - vi * vi));
float m = MEN * HW * RI * smoothstep(0., 30., gap);
float front = m * c * (1. - 0.4 * uSurge); // concave: the water climbs the wall ahead of the centre
float back = uLen + m * (1. - c) * (1. + 0.4 * uSurge);
float dIn = mix(min(rel - front, back - rel), 60., full);
return vec3(clamp(dIn / uPx + 0.5, 0., 1.), rel, dIn);
}
// noise laid on a circle, so the texture wraps the loop without a seam
float ringNoise(float s, float vi, float freq, float z) {
float a = 6.2831853 * s / PER, R = PER / 6.2831853 * freq;
return snoise(vec3(R * cos(a) + uTime * 0.3, R * sin(a) - uTime * 0.2, vi * 1.25 + z));
}
float flowTex(float s, float vi, float z) {
return 0.5 + 0.5 * (0.6 * ringNoise(s, vi, 0.06, z) + 0.28 * ringNoise(s, vi * 1.8, 0.13, z + 3.1) + 0.12 * ringNoise(s, vi * 3.6, 0.27, z + 7.7));
}
void main() {
vec2 p = frag();
vec4 o = vec4(0.);
// contact shadow thrown down-left, and the light the water focuses into it
vec2 so = -L2 * 5.5;
vec2 ps = p - so;
float dsh = sdRB(ps);
float sr = abs(dsh) / HW; // glass passes most light: the shadow is darkest under the walls
o.a = (1. - smoothstep(-4., 10., abs(dsh) - HW)) * mix(0.05, 0.2, uDark) + exp(-pow((sr - 0.95) / 0.35, 2.)) * mix(0.08, 0.06, uDark);
{
vec3 Ws = slug(pathS(ps), clamp(dsh / (HW * RI), -1., 1.));
float cz = exp(-pow((dsh / HW + 0.2) / 0.3, 2.)) * Ws.x;
o.rgb += mix(uColor, vec3(1.), 0.25) * cz * mix(0.45, 0.12, uDark);
}
float dc = sdRB(p);
float v = dc / HW;
float tube = clamp((HW - abs(dc)) / uPx + 0.5, 0., 1.);
if (tube <= 0.) { gl_FragColor = o; return; }
vec2 n2 = normalize(p - clamp(p, -H, H) + 1e-4);
vec2 t2 = vec2(-n2.y, n2.x);
float s = pathS(p);
float vc = clamp(v, -1., 1.);
vec3 N = vec3(n2 * vc, sqrt(max(0., 1. - vc * vc)));
vec3 Ld = normalize(vec3(L2 * 0.78, 0.62));
vec3 Hh = normalize(Ld + vec3(0., 0., 1.));
vec3 gTint = mix(vec3(0.42, 0.50, 0.53), vec3(0.78, 0.88, 0.92), uDark);
vec3 hiC = vec3(1.0, 0.985, 0.95);
// glass: the walls are thicker to the eye near the silhouette
float gl = 2. * (sqrt(max(0., 1. - vc * vc)) - sqrt(max(0., RI * RI - vc * vc)));
float gA = 1. - exp(-gl * 0.42);
over(o, gTint, gA * 0.3 * tube);
float vi = clamp(v / RI, -1., 1.);
float bore = clamp((RI * HW - abs(dc)) / uPx + 0.5, 0., 1.);
vec3 W = slug(s, vi);
float cov = W.x * bore;
vec2 hl = vec2(dot(L2, -t2), dot(L2, n2)); // light direction in the slug's local frame
vec3 wetC = mix(uColor, vec3(1.), 0.35);
// where the water has just left: a film on the walls and beads that drain away
float wet = texture2D(uWet, vec2(s / PER, 0.5)).r * (1. - W.x);
if (wet > 0.01 && bore > 0.) {
over(o, wetC, wet * 0.22 * smoothstep(0.5, 0.95, abs(vi)) * bore);
float cs = PER / 110.;
float gx = floor(s / cs), gy = floor((vi + 1.) * 2.);
for (int a = -1; a <= 1; a++) for (int b = -1; b <= 1; b++) {
vec2 cell = vec2(gx + float(a), gy + float(b));
if (cell.y < 0. || cell.y > 3.) continue;
vec2 hc = vec2(mod(cell.x, 110.), cell.y);
vec2 h = hash22(hc);
float h3 = hash12(hc.yx + 17.);
float pres = smoothstep(h3, h3 + 0.3, wet * 1.2) * step(0.45, hash12(hc + 3.7));
if (pres <= 0.01) continue;
vec2 c = vec2((cell.x + h.x) * cs, clamp(-1. + (cell.y + h.y) * 0.5, -0.88, 0.88));
float r = mix(0.35, 1.3, h.x * h.y) * sqrt(pres);
vec2 dl = vec2(s - c.x, (vi - c.y) * RI * HW);
float d = length(dl) - r;
float fill = clamp(-d / uPx + 0.5, 0., 1.) * bore;
over(o, wetC * 0.75, fill * 0.45);
over(o, uColor * 0.4, exp(-pow(d / 0.25, 2.)) * 0.35 * bore);
over(o, hiC, exp(-pow(length(dl - vec2(-hl.x, hl.y) * r * 0.45) / (0.28 * r + 0.08), 2.)) * 0.85 * bore);
}
}
if (cov > 0.) {
float th = sqrt(max(0., 1. - vi * vi));
float kv = 1. + 0.4 * (1. - 2. * vi * vi); // the centre runs ahead of the walls
float tex = mix(flowTex(s - kv * uFlowA, vi, 0.), flowTex(s - kv * uFlowB, vi, 7.3), uFlowW);
float side = dot(n2 * vi, L2);
vec3 wc = mix(mix(uColor, vec3(1.), 0.55), uColor, smoothstep(0.05, 0.9, th)); // Beer-Lambert: thicker is deeper
wc *= 1. - 0.55 * smoothstep(0.62, 1.0, abs(vi)); // total internal reflection at the wall
wc += mix(uColor, vec3(1.), 0.65) * exp(-pow((side + 0.42) / 0.17, 2.)) * 0.42; // caustic on the far wall
wc *= 0.8 + 0.4 * tex;
float spA = smoothstep(0.62, 0.9, ringNoise(s - kv * uFlowA, vi * 4., 0.45, 11.));
float spB = smoothstep(0.62, 0.9, ringNoise(s - kv * uFlowB, vi * 4., 0.45, 19.));
wc += 0.25 * mix(spA, spB, uFlowW);
wc *= 1. - 0.6 * exp(-pow(W.z / 1.1, 2.)); // meniscus: dark refracted band
wc += 0.5 * exp(-pow((W.z - 2.1) / 0.7, 2.)) * mix(uColor, vec3(1.), 0.75); // and its bright inner lip
over(o, wc, (0.58 + 0.34 * th + 0.2 * exp(-pow(W.z / 1.5, 2.))) * cov);
// entrained bubbles ride the flow; they only move when the water does
float full = 1. - smoothstep(0.3, 1.5, PER - uLen);
for (int i = 0; i < 12; i++) {
float fi = float(i);
float bv = (hash11(fi + 1.3) * 2. - 1.) * 0.62;
float br = mix(0.5, 1.9, hash11(fi + 7.9) * hash11(fi + 3.1));
float bk = 1. + 0.35 * (1. - 2. * bv * bv) + 0.2 * (hash11(fi + 4.4) - 0.5);
float bs = mod(hash11(fi + 9.2) * PER + bk * uMid, PER);
float bx = mod(uHead - bs + 24., PER) - 24.;
float fade = mix(smoothstep(4., 9., bx) * smoothstep(uLen, uLen - 9., bx), 1., full);
vec2 dl = vec2(W.y - bx, (vi - bv) * RI * HW);
dl.x -= PER * floor(dl.x / PER + 0.5);
float d = length(dl) - br;
if (d < 1.2 && fade > 0.) {
float f = fade * cov;
over(o, mix(wc, vec3(1.), 0.5), clamp(-d / uPx + 0.5, 0., 1.) * 0.3 * f);
over(o, wc * 0.3, exp(-pow(d / 0.28, 2.)) * 0.6 * f);
over(o, hiC, exp(-pow(length(dl - hl * br * 0.42) / (0.22 * br + 0.12), 2.)) * 0.9 * f);
}
}
}
// front wall, reflections
over(o, gTint, gA * 0.3 * tube);
float ndh = max(dot(N, Hh), 0.);
float spec = pow(ndh, 110.) * 0.95 + pow(ndh, 14.) * 0.09;
spec += pow(max(dot(vec3(-N.xy, N.z), Hh), 0.), 70.) * 0.28; // the back inner surface
float fres = pow(1. - N.z, 3.) * mix(0.12, 0.3, uDark);
float wl = exp(-pow((abs(v) - RI) * HW / 0.3, 2.)) * 0.2; // bore wall seen edge-on
over(o, hiC, (spec + fres + wl) * tube);
over(o, gTint * 0.55, exp(-pow((abs(v) - 1.) * HW / 0.45, 2.)) * mix(0.45, 0.1, uDark) * tube);
gl_FragColor = o;
}`;
const SMOKE = `
uniform vec4 uPuff[${NPUFF}]; // one puff per stretch of the frame: centre xy, radius, weight
const float W0 = ${W0.toFixed(4)};
float fbm(vec3 p) { float f = 0., a = 0.55; for (int i = 0; i < 4; i++) { f += a * snoise(p); p = p * 2.03 + vec3(1.7, 9.2, 3.1); a *= 0.42; } return f; }
vec2 warpAt(vec2 p) { vec3 np = vec3(p * 0.022, uTime * 0.12); return vec2(snoise(np), snoise(np + vec3(19.1, 7.3, 3.7))); }
// x: density, y: mean growth of the puffs here (released smoke has grown)
vec2 puffs(vec2 p, vec2 warp) {
float D = 0., G = 0.;
for (int i = 0; i < ${NPUFF}; i++) {
vec4 f = uPuff[i];
float grow = f.z - W0;
vec2 q = p - warp * (1.5 + 0.6 * grow) - f.xy; // turbulence displaces older smoke further (kept below folding)
float g = f.w * exp(-dot(q, q) / (f.z * f.z));
D += g; G += g * grow;
}
return vec2(D, G / max(D, 1e-5));
}
void main() {
vec2 p = frag();
vec2 wp = warpAt(p);
vec2 P = puffs(p, wp);
float ext = min(0.5 * uRes.x * uPx - abs(p.x), 0.5 * uRes.y * uPx - abs(p.y));
P.x *= smoothstep(0., 16., ext);
if (P.x < 0.004) { gl_FragColor = vec4(0.); return; }
// billows: domain-warped noise evolving in place, eaten away as the smoke ages
vec2 pw = p - wp * (1.5 + 0.6 * P.y);
vec3 dp = vec3(pw * 0.035, uTime * 0.16);
vec2 q = vec2(snoise(dp), snoise(dp + vec3(5.2, 1.3, 2.8)));
float n = fbm(vec3(pw * 0.045 + 1.1 * q, uTime * 0.2 + 3.));
float bil = smoothstep(-0.7, 0.55, n + 0.1 - 0.04 * P.y);
float d = P.x * (0.5 + 0.75 * bil);
// light from the upper right: shade by how much smoke lies toward it
vec2 pl = p + L2 * 7.;
float dl = puffs(pl, warpAt(pl)).x;
float lit = clamp(mix(0.55, 0.85, uDark) - (dl - P.x) * mix(1.3, 0.9, uDark), 0., 1.) * (0.88 + 0.16 * bil);
float a = 1. - exp(-d * 1.9);
vec3 shade = uColor * mix(vec3(0.62, 0.64, 0.70), vec3(0.50, 0.53, 0.60), uDark);
vec3 c = mix(shade, uColor, clamp(lit, 0., 1.));
c += uColor * 0.18 * (1. - a) * lit; // thin wisps let light through
gl_FragColor = vec4(min(c, vec3(1.)) * a, a);
}`;
const NEON = `
uniform float uSegA, uLen, uMix, uMove, uHum, uTR;
uniform vec3 uColA, uColB;
uniform vec2 uPts[${NPTS}];
vec3 emit(float s) {
float x = mod(s - uSegA, PER); // distance ahead of the tail
float din = x <= uLen ? min(x, uLen - x) : -min(x - uLen, PER - x);
din = mix(din, 1e3, step(PER - 0.5, uLen));
float on = smoothstep(-0.6, 0.6, din);
float strike = uMove * exp(-max(uLen - x, 0.) / 18.) * on; // the end being struck stutters while it runs
float fl = mix(1., 0.15 + 0.85 * step(0.3, hash12(vec2(floor(x / 6.), floor(uTime * 30.)))), strike);
float after = uMove * exp(-mod(uSegA - s, PER) / 10.) * (1. - on) * 0.6; // the tail lets go with an afterglow
vec3 col = mix(uColB, uColA, uMix);
return (col * (on * fl * (1. + 0.6 * strike) + after) + vec3(0.35) * strike * fl) * uHum;
}
void main() {
vec2 p = frag();
float dc = sdRB(p), d = abs(dc), s = pathS(p);
vec3 e = emit(s);
// light spilling onto the wall: integrated over the whole tube so every lit stretch contributes
vec3 g = vec3(0.);
for (int i = 0; i < ${NPTS}; i++) {
vec2 dv = p - uPts[i];
float r2 = dot(dv, dv);
g += emit((float(i) + 0.5) * (PER / ${NPTS}.)) * (exp(-r2 / 60.) + 0.35 * exp(-r2 / 420.));
}
g *= (PER / ${NPTS}.) / 40.;
float vt = clamp(dc / uTR, -1., 1.);
float tm = clamp((uTR - d) / uPx + 0.5, 0., 1.);
float I = max(max(e.r, e.g), e.b);
float core = exp(-vt * vt * 3.2);
vec3 tubeL = e * (0.4 + 0.85 * core) + vec3(1.) * I * pow(core, 4.) * 0.55; // white-hot centre, saturated rim
vec3 nearL = e * exp(-max(d - uTR * 0.8, 0.) / 1.2) * 0.6;
vec3 L = g + nearL * (1. - tm) + tubeL * tm;
vec3 mapped = 1. - exp(-L * 1.25);
// the glass itself, visible where it is dark
vec2 n2 = normalize(p - clamp(p, -H, H) + 1e-4);
vec3 N = vec3(n2 * vt, sqrt(max(0., 1. - vt * vt)));
vec3 Hh = normalize(normalize(vec3(L2 * 0.78, 0.62)) + vec3(0., 0., 1.));
vec3 gTint = mix(vec3(0.22, 0.24, 0.27), vec3(0.62, 0.66, 0.72), uDark);
vec4 o = vec4(0.);
over(o, gTint, tm * (0.14 + 0.35 * pow(1. - N.z, 2.)) * (1. - clamp(I, 0., 1.) * 0.6));
if (uDark > 0.5) o.rgb += mapped;
else { // on paper light can't add; lay the hue down instead, keeping it saturated
vec3 Lc = g + nearL * (1. - tm) + e * (0.4 + 0.85 * core) * tm;
float m = max(max(Lc.r, Lc.g), Lc.b);
over(o, Lc / max(m, 1e-3), (1. - exp(-m * 1.4)) * mix(0.85, 1., tm));
over(o, vec3(1.), pow(core, 4.) * min(I, 1.) * 0.6 * tm);
}
over(o, vec3(1.), pow(max(dot(N, Hh), 0.), 60.) * 0.5 * tm);
gl_FragColor = o;
}`;
const SRC = { water: WATER, smoke: SMOKE, neon: NEON };
const PAD = { water: 1.3, smoke: 1.9, neon: 1.8 };
const DEFAULTS = {
water: { color: "#2FA8FF" },
smoke: { color: "#F5F5F2" },
neon: { colors: ["#FF2E88", "#2EF0FF", "#FFB020", "#7CFF4F", "#9B5CFF"], tube: 0.58 },
};
const COMMON = { sequence: "LUCIO", hold: 0.7, morph: 0.45, speed: 1, size: 96 };
const rgb = hex => { const h = hex.replace("#", ""), f = h.length === 3 ? h.split("").map(c => c + c).join("") : h; return [0, 2, 4].map(i => parseInt(f.slice(i, i + 2), 16) / 255); };
const reduced = () => global.matchMedia && global.matchMedia("(prefers-reduced-motion: reduce)").matches;
const ease = f => f < 0.5 ? 4 * f * f * f : 1 - Math.pow(-2 * f + 2, 3) / 2;
const fract = x => x - Math.floor(x);
const hash = n => fract(Math.sin(n * 127.1 + 11.7) * 43758.5453);
const smooth = (a, b, x) => { const k = Math.min(1, Math.max(0, (x - a) / (b - a))); return k * k * (3 - 2 * k); };
function bgIsDark(el) {
for (let n = el; n && n.nodeType === 1; n = n.parentElement) {
const m = getComputedStyle(n).backgroundColor.match(/[\d.]+/g);
if (m && (m.length < 4 || +m[3] > 0.5)) return (0.2126 * m[0] + 0.7152 * m[1] + 0.0722 * m[2]) / 255 < 0.5;
}
return !!(global.matchMedia && global.matchMedia("(prefers-color-scheme: dark)").matches);
}
const LET = { C: [0, .75], L: [.25, .75], U: [.25, 1], I: [.75, 1], O: [.75, 1.75] };
function speller(o) {
const seq = () => { const s = (o.sequence || "LUCIO").toUpperCase().split("").filter(c => LET[c]); return s.length ? s : ["O"]; };
const target = (cur, ch) => { const [s2, e2] = LET[ch]; for (let q = -1; q < 6; q++) { if (s2 + q >= cur[0] - 1e-6 && e2 + q >= cur[1] - 1e-6) return [s2 + q, e2 + q]; } return [s2, e2]; };
const st = { i: 0, j: 0, seg: LET[seq()[0]].slice(), u: 1, f: 1, moving: false, travel: 0, vHead: 0 };
let from = st.seg, to = st.seg, timer = 0;
st.step = dt => {
const before = st.seg.slice();
timer += dt;
if (!st.moving && timer >= o.hold) {
const s = seq(); st.j = (st.i + 1) % s.length; from = st.seg.slice(); to = target(st.seg, s[st.j]);
st.moving = true; timer -= o.hold;
}
if (st.moving) {
const dur = reduced() ? 0 : o.morph;
st.f = dur > 0 ? Math.min(1, timer / dur) : 1; st.u = ease(st.f);
st.seg = [from[0] + (to[0] - from[0]) * st.u, from[1] + (to[1] - from[1]) * st.u];
if (st.f >= 1) { st.moving = false; st.i = st.j; timer = 0; }
} else { st.f = 1; st.u = 1; }
st.travel += ((st.seg[0] - before[0]) + (st.seg[1] - before[1])) / 2 * PER;
st.vHead = dt > 0 ? (st.seg[1] - before[1]) * PER / dt : 0;
if (!st.moving) { const n = Math.floor(st.seg[0]); st.seg[0] -= n; st.seg[1] -= n; }
};
st.units = () => ({ a: PER * (st.seg[0] + 0.25), len: Math.min(PER, (st.seg[1] - st.seg[0]) * PER) });
st.reset = () => { st.i = st.j = 0; st.seg = LET[seq()[0]].slice(); st.moving = false; timer = 0; };
return st;
}
const live = new Set();
let raf = 0, last = 0;
function loop(now) {
const dt = last ? Math.min(0.1, (now - last) / 1000) : 0; last = now;
for (const inst of live) inst.frame(dt);
raf = live.size ? requestAnimationFrame(loop) : 0;
if (!raf) last = 0;
}
function create(kind, container, opts) {
const o = Object.assign({}, COMMON, DEFAULTS[kind], opts || {});
const wrap = document.createElement("div");
wrap.className = "lucio-fx lucio-fx-" + kind;
wrap.setAttribute("role", "img"); wrap.setAttribute("aria-label", "Loading");
wrap.style.cssText = "position:relative;display:inline-block;vertical-align:middle;flex:none";
const canvas = document.createElement("canvas");
canvas.style.cssText = "position:absolute;pointer-events:none";
wrap.appendChild(canvas); container.appendChild(wrap);
const gl = canvas.getContext("webgl", { premultipliedAlpha: true, alpha: true, antialias: false });
if (!gl) { console.warn("LucioLoaders: WebGL unavailable"); return null; }
const sh = (type, src) => { const s = gl.createShader(type); gl.shaderSource(s, src); gl.compileShader(s); if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) throw new Error(kind + ": " + gl.getShaderInfoLog(s)); return s; };
const prog = gl.createProgram();
gl.attachShader(prog, sh(gl.VERTEX_SHADER, "attribute vec2 a; void main(){ gl_Position = vec4(a, 0., 1.); }"));
gl.attachShader(prog, sh(gl.FRAGMENT_SHADER, PRELUDE + SRC[kind]));
gl.linkProgram(prog);
if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) throw new Error(kind + ": " + gl.getProgramInfoLog(prog));
gl.useProgram(prog);
gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer());
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), gl.STATIC_DRAW);
gl.enableVertexAttribArray(0); gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);
const U = {}; const u = n => n in U ? U[n] : (U[n] = gl.getUniformLocation(prog, n));
if (kind === "neon") { const pts = []; for (let i = 0; i < NPTS; i++) pts.push(...pathP((i + 0.5) * PER / NPTS)); gl.uniform2fv(u("uPts[0]"), new Float32Array(pts)); }
const BINS = 64, wetAt = new Float32Array(BINS).fill(-1e3), wetTex = new Uint8Array(BINS);
if (kind === "water") {
gl.bindTexture(gl.TEXTURE_2D, gl.createTexture());
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.uniform1i(u("uWet"), 0);
}
const puff = new Float32Array(NPUFF * 4), pDen = new Float32Array(NPUFF), pAge = new Float32Array(NPUFF);
const sp = speller(o);
const inside = (s, a, len) => { if (len >= PER - 0.5) return 1e3; const x = ((s - a) % PER + PER) % PER; return x <= len ? Math.min(x, len - x) : -Math.min(x - len, PER - x); };
let t = 0, dark = o.theme === "light" ? false : o.theme === "dark" ? true : bgIsDark(container), frames = 0, visible = true;
const io = global.IntersectionObserver ? new IntersectionObserver(es => { visible = es[0].isIntersecting; }) : null;
if (io) io.observe(wrap);
function setSize(px) {
o.size = px;
const dpr = Math.min(global.devicePixelRatio || 1, 2), c = px * PAD[kind];
wrap.style.width = wrap.style.height = px + "px";
canvas.style.width = canvas.style.height = c + "px";
canvas.style.left = canvas.style.top = (-(c - px) / 2) + "px";
canvas.width = canvas.height = Math.round(c * dpr);
gl.viewport(0, 0, canvas.width, canvas.height);
gl.uniform2f(u("uRes"), canvas.width, canvas.height);
gl.uniform1f(u("uPx"), 120 / (px * canvas.width / c));
}
setSize(o.size);
function frame(dt) {
if (o.theme === "auto" || !o.theme) { if (++frames % 30 === 0) dark = bgIsDark(container); }
if (!visible) return;
dt *= o.speed;
t += dt * (reduced() ? 0.35 : 1);
sp.step(dt);
const { a, len } = sp.units();
gl.uniform1f(u("uTime"), t);
gl.uniform1f(u("uDark"), dark ? 1 : 0);
if (kind === "water") {
const Df = 70, pa = fract(sp.travel / Df), pb = fract(sp.travel / Df + 0.5);
gl.uniform3fv(u("uColor"), rgb(o.color));
gl.uniform1f(u("uHead"), a + len); gl.uniform1f(u("uLen"), len);
gl.uniform1f(u("uSurge"), Math.min(1, Math.max(0, sp.vHead / 700)));
gl.uniform1f(u("uMid"), sp.travel);
gl.uniform1f(u("uFlowA"), pa * Df); gl.uniform1f(u("uFlowB"), pb * Df);
gl.uniform1f(u("uFlowW"), 1 - Math.abs(2 * pb - 1));
for (let i = 0; i < BINS; i++) {
if (inside((i + 0.5) * PER / BINS, a, len) > -2) wetAt[i] = t;
wetTex[i] = Math.round(255 * Math.exp(-(t - wetAt[i]) / 1.1));
}
gl.texImage2D(gl.TEXTURE_2D, 0, gl.LUMINANCE, BINS, 1, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, wetTex);
} else if (kind === "smoke") {
gl.uniform3fv(u("uColor"), rgb(o.color));
const kIn = 1 - Math.exp(-dt * 20), kOut = Math.exp(-dt * 4.2);
for (let i = 0; i < NPUFF; i++) {
const s = (i + 0.5) * PER / NPUFF, cover = smooth(-6, 6, inside(s, a, len));
if (cover >= pDen[i]) { pDen[i] += (cover - pDen[i]) * kIn; pAge[i] *= Math.exp(-dt * 8); }
else { pDen[i] = Math.max(cover, pDen[i] * kOut); pAge[i] += dt; }
const w = W0 + 10 * pAge[i], [x, y] = pathP(s);
puff.set([x, y + 9 * pAge[i], w, pDen[i] * (W0 * 1.6 / (w + 0.6 * W0)) * (PER / NPUFF) / (1.7725 * w)], i * 4);
}
gl.uniform4fv(u("uPuff[0]"), puff);
} else {
const pal = o.colors.map(rgb), n = pal.length;
gl.uniform1f(u("uTR"), HW * o.tube);
gl.uniform1f(u("uHum"), 0.975 + 0.025 * Math.sin(t * 46) * Math.sin(t * 7.3) + (hash(Math.floor(t * 9)) > 0.985 ? -0.2 : 0));
gl.uniform1f(u("uSegA"), a); gl.uniform1f(u("uLen"), len);
gl.uniform3fv(u("uColB"), pal[sp.i % n]); gl.uniform3fv(u("uColA"), pal[(sp.moving ? sp.j : sp.i) % n]);
gl.uniform1f(u("uMix"), sp.moving ? smooth(0.05, 0.35, sp.f) : 1);
gl.uniform1f(u("uMove"), sp.moving ? Math.sin(Math.PI * sp.f) : 0);
}
gl.drawArrays(gl.TRIANGLES, 0, 3);
}
const inst = { frame };
live.add(inst);
if (!raf) raf = requestAnimationFrame(loop);
return {
el: wrap, canvas,
tick: frame,
setColor(c) { o.color = c; if (kind === "neon") o.colors = [c]; },
setColors(cs) { o.colors = cs.slice(); },
setTiming({ hold, morph }) { if (hold != null) o.hold = hold; if (morph != null) o.morph = morph; },
setSequence(seq) { o.sequence = seq; sp.reset(); },
setSpeed(s) { o.speed = s; },
setSize,
setTheme(th) { o.theme = th; dark = th === "light" ? false : th === "dark" ? true : bgIsDark(container); },
stop() { live.delete(inst); if (io) io.disconnect(); wrap.remove(); const ext = gl.getExtension("WEBGL_lose_context"); if (ext) ext.loseContext(); },
};
}
global.LucioLoaders = {
water: (el, opts) => create("water", el, opts),
smoke: (el, opts) => create("smoke", el, opts),
neon: (el, opts) => create("neon", el, opts),
geometry: { HB, CR, HW, PER, pathP, LET },
};
})(window);
+149
View File
@@ -481,6 +481,155 @@ html:not(.has-strips) .strip-subtitle {
line-height: 1.2;
}
.has-gate,
.has-gate body {
overflow: hidden;
}
.gate {
position: fixed;
inset: 0;
z-index: 20;
display: flex;
align-items: center;
justify-content: center;
box-sizing: border-box;
padding: var(--gutter);
background: var(--veil);
-webkit-backdrop-filter: blur(12px);
backdrop-filter: blur(12px);
transition: opacity var(--lucio-motion-base) var(--lucio-ease-base);
}
.gate.is-leaving {
opacity: 0;
pointer-events: none;
}
.gate-card {
display: flex;
flex-direction: column;
align-items: center;
gap: var(--lucio-space-4);
box-sizing: border-box;
width: 100%;
max-width: 320px;
padding: var(--lucio-space-6) var(--lucio-space-5);
background: var(--lucio-graphite-2);
border: 1px solid var(--lucio-graphite-3);
border-radius: var(--lucio-radius-lg);
text-align: center;
}
.gate-eyebrow {
margin: 0;
font-family: var(--lucio-font-mono);
font-size: 12px;
line-height: 1.4;
font-weight: 500;
letter-spacing: 0.08em;
text-transform: uppercase;
color: var(--lucio-ash-light);
}
.gate-line {
margin: 0 0 var(--lucio-space-2);
font-family: var(--lucio-font-display);
font-size: 20px;
font-weight: 600;
line-height: 1.3;
letter-spacing: -0.01em;
color: var(--lucio-paper);
}
.gate-hold {
display: block;
width: 88px;
height: 88px;
margin: 0;
padding: 0;
border: 0;
border-radius: 50%;
background: var(--lucio-graphite-3);
cursor: pointer;
touch-action: none;
user-select: none;
-webkit-user-select: none;
-webkit-touch-callout: none;
-webkit-tap-highlight-color: transparent;
transition: transform var(--lucio-motion-fast) var(--lucio-ease-fast), box-shadow var(--lucio-motion-fast) var(--lucio-ease-fast);
}
.gate-hold:hover,
.gate-hold.is-pressed {
box-shadow: var(--lucio-shadow-glow);
}
.gate-hold.is-pressed {
transform: scale(0.96);
}
.gate-hold:focus-visible {
outline-offset: 4px;
}
.gate-hold:disabled {
cursor: default;
box-shadow: none;
}
.gate-hold svg {
display: block;
width: 100%;
height: 100%;
transform: rotate(-90deg);
}
.gate-track,
.gate-ring {
fill: none;
stroke-width: 3;
}
.gate-track {
stroke: var(--lucio-ash-dark);
}
.gate-ring {
stroke: var(--lucio-beam);
stroke-linecap: round;
stroke-dasharray: 100;
stroke-dashoffset: 100;
transition: stroke-dashoffset var(--lucio-motion-base) var(--lucio-ease-base);
}
.gate-hold.is-pressed .gate-ring {
transition: none;
}
.gate-dot {
fill: var(--lucio-paper);
transform-origin: 32px 32px;
transition: transform var(--lucio-motion-fast) var(--lucio-ease-fast);
}
.gate-hold.is-pressed .gate-dot {
transform: scale(1.5);
}
.gate.is-waiting .gate-hold svg {
animation: gate-spin 900ms linear infinite;
}
@keyframes gate-spin {
from {
transform: rotate(-90deg);
}
to {
transform: rotate(270deg);
}
}
@media (prefers-reduced-motion: reduce) {
*,
*::before,
+61 -7
View File
@@ -1,6 +1,9 @@
import { mountWordmark } from "./brand";
import { mountSignoffMark, mountWordmark } from "./brand";
import { TileCache, cacheBudget } from "./cache";
import { entropyScore, startEntropy } from "./entropy";
import { guardLink, takeNav, type GuardOptions } from "./gate";
import { IndexPage } from "./index";
import { AlbumKeys, fixedKeys } from "./keys";
import { Scheduler } from "./scheduler";
import { readSettings, type Manifest, type Settings, type SiteIndex } from "./types";
import { Viewer } from "./viewer";
@@ -17,20 +20,37 @@ function shared(settings: Settings): { scheduler: Scheduler; cache: TileCache }
return { scheduler: new Scheduler(settings.concurrency, settings.workerUrl), cache: new TileCache(cacheBudget()) };
}
async function startAlbum(stage: HTMLElement, settings: Settings): Promise<void> {
function guardOptions(settings: Settings, minEntropy: () => number): GuardOptions | null {
if (settings.gate === "off") {
return null;
}
return { build: settings.build, workerUrl: settings.workerUrl, minEntropy, score: entropyScore };
}
async function startAlbum(stage: HTMLElement, settings: Settings, nav: boolean): Promise<void> {
const manifest = await fetchJSON<Manifest>(settings.manifestUrl);
if (manifest.photos.length === 0) {
return;
}
const keys = new AlbumKeys(manifest.gate, manifest.slug, nav ? "nav" : "land", settings.workerUrl);
const { scheduler, cache } = shared(settings);
document.documentElement.classList.add("has-viewer");
lifecycle(new Viewer(stage, manifest, settings, { scheduler, cache, settings, tiles: manifest.tiles }));
const minEntropy = manifest.gate.min_entropy ?? settings.minEntropy;
lifecycle(
new Viewer(stage, manifest, settings, { scheduler, cache, settings, keys, tiles: manifest.tiles }, keys, guardOptions(settings, () => minEntropy)),
);
}
async function startIndex(root: HTMLElement, settings: Settings): Promise<void> {
async function startIndex(root: HTMLElement, settings: Settings, minEntropy: (value: number) => void): Promise<void> {
const index = await fetchJSON<SiteIndex>(settings.indexUrl);
if (typeof index.gate.min_entropy === "number") {
minEntropy(index.gate.min_entropy);
}
if (index.albums.length === 0) {
return;
}
const { scheduler, cache } = shared(settings);
lifecycle(new IndexPage(root, index, settings, { scheduler, cache, settings, tiles: index.tiles }));
lifecycle(new IndexPage(root, index, settings, { scheduler, cache, settings, keys: fixedKeys(index.gate.cover), tiles: index.tiles }));
}
interface Suspendable {
@@ -59,12 +79,37 @@ function showLoadError(): void {
document.querySelector<HTMLElement>(".load-error")?.removeAttribute("hidden");
}
function mountFooterMarks(): void {
const holders = Array.from(document.querySelectorAll<HTMLElement>(".site-footer .chop"));
if (holders.length === 0) {
return;
}
if (typeof IntersectionObserver !== "function") {
holders.forEach(mountSignoffMark);
return;
}
const observer = new IntersectionObserver(
(entries) => {
for (const entry of entries) {
if (entry.isIntersecting) {
observer.unobserve(entry.target);
mountSignoffMark(entry.target as HTMLElement);
}
}
},
{ rootMargin: "200px" },
);
holders.forEach((holder) => observer.observe(holder));
}
function boot(): void {
startEntropy();
mountFooterMarks();
const settings = readSettings(document.body);
if (settings.page === "album") {
const stage = document.getElementById("stage");
if (stage) {
startAlbum(stage, settings).catch(() => showLoadError());
startAlbum(stage, settings, takeNav(settings.slug)).catch(showLoadError);
}
} else if (settings.page === "notfound") {
const header = document.querySelector<HTMLElement>(".site-header .wordmark");
@@ -74,7 +119,16 @@ function boot(): void {
} else if (settings.page === "index") {
const root = document.getElementById("strips");
if (root) {
startIndex(root, settings).catch(() => {
let minEntropy = settings.minEntropy;
const options = guardOptions(settings, () => minEntropy);
if (options) {
for (const anchor of Array.from(root.querySelectorAll<HTMLAnchorElement>("a.strip"))) {
guardLink(anchor, () => anchor.dataset.slug ?? "", options);
}
}
startIndex(root, settings, (value) => {
minEntropy = value;
}).catch(() => {
document.documentElement.classList.remove("has-strips");
const header = document.querySelector<HTMLElement>(".site-header .wordmark");
if (header && !header.classList.contains("has-svg")) {
+67 -7
View File
@@ -1,4 +1,5 @@
import "../brand/lucio-morph.js";
import "../brand/lucio-loaders.js";
export interface MorphHandle {
play(): void;
@@ -25,7 +26,7 @@ export interface WordmarkOptions {
export interface LoaderOptions {
size?: number;
color?: string;
track?: string;
track?: string | null;
rays?: string;
hold?: number;
morph?: number;
@@ -36,11 +37,28 @@ interface LucioMorphApi {
loader(container: Element, options?: LoaderOptions): LoaderHandle;
}
interface SmokeOptions {
size?: number;
color?: string;
theme?: "dark" | "light" | "auto";
}
interface SmokeHandle {
el: HTMLElement;
setSize(px: number): void;
stop(): void;
}
interface LucioLoadersApi {
smoke(container: Element, options?: SmokeOptions): SmokeHandle | null;
}
export const palette = {
graphite: "#111114",
graphite3: "#26262D",
paper: "#F3F1EC",
beam: "#FFF3CF",
smoke: "#F5F5F2",
};
export function lucioMorph(): LucioMorphApi | null {
@@ -67,11 +85,53 @@ export function mountWordmark(link: HTMLElement, animated: boolean): MorphHandle
return handle;
}
export function cloneChop(): HTMLElement | null {
const template = document.getElementById("chop-template");
if (!(template instanceof HTMLTemplateElement)) {
return null;
const fallbackMarkSize = 44;
function markSize(holder: HTMLElement): number {
return Math.round(holder.getBoundingClientRect().width) || fallbackMarkSize;
}
// The sign-off mark: the LUCIO loader in smoke, or the plain SVG loader where WebGL is unavailable.
// Replaces whatever the holder contains (the server-rendered chop) once it can draw.
export function mountSignoffMark(holder: HTMLElement): void {
if (holder.dataset.mounted === "1") {
return;
}
const node = template.content.firstElementChild;
return node ? (node.cloneNode(true) as HTMLElement) : null;
const size = markSize(holder);
const loaders = (window as unknown as { LucioLoaders?: LucioLoadersApi }).LucioLoaders;
const fallback = Array.from(holder.childNodes);
holder.replaceChildren();
let smoke: SmokeHandle | null = null;
try {
smoke = loaders ? loaders.smoke(holder, { size, theme: "dark", color: palette.smoke }) : null;
} catch {
smoke = null;
}
if (smoke) {
smoke.el.removeAttribute("role");
smoke.el.removeAttribute("aria-label");
const handle = smoke;
if (typeof ResizeObserver === "function") {
let last = size;
new ResizeObserver(() => {
const next = markSize(holder);
if (next !== last) {
last = next;
handle.setSize(next);
}
}).observe(holder);
}
} else {
holder.replaceChildren();
const api = lucioMorph();
if (api) {
const svg = api.loader(holder, { size, color: palette.paper, track: null, rays: palette.beam }).svg;
svg.setAttribute("aria-hidden", "true");
svg.style.width = "100%";
svg.style.height = "auto";
} else {
holder.append(...fallback);
}
}
holder.dataset.mounted = "1";
}
+203
View File
@@ -0,0 +1,203 @@
const storageKey = "luphoto.entropy";
const segment = 8;
const turnCos = Math.cos(Math.PI / 6);
const scrollGapMs = 100;
const touchSlop = 10;
interface Saved {
p: number;
t: number;
c: number;
g: number;
s: number;
k: number;
}
class Tracker {
private path = 0;
private turns = 0;
private cells = 0;
private gestures = 0;
private scrolls = 0;
private keys = 0;
private readonly seen = new Uint32Array(128);
private lastX = 0;
private lastY = 0;
private hasLast = false;
private segX = 0;
private segY = 0;
private prevX = 0;
private prevY = 0;
private hasPrev = false;
private touchId = -1;
private touchX = 0;
private touchY = 0;
private touchMoved = false;
private lastScroll = -Infinity;
private memory: Saved | null = null;
constructor() {
this.load();
const options: AddEventListenerOptions = { passive: true, capture: true };
addEventListener("pointermove", (e) => this.onMove(e), options);
addEventListener("pointerdown", (e) => this.onDown(e), options);
addEventListener("pointerup", (e) => this.onUp(e), options);
addEventListener("pointercancel", (e) => this.onCancel(e), options);
addEventListener("wheel", (e) => this.onScroll(e), options);
addEventListener("scroll", (e) => this.onScroll(e), options);
addEventListener("keydown", (e) => this.onKey(e), options);
addEventListener("pagehide", () => this.save());
document.addEventListener("visibilitychange", () => {
if (document.visibilityState === "hidden") {
this.save();
}
});
}
private onMove(e: PointerEvent): void {
if (!e.isTrusted) {
return;
}
const x = e.clientX;
const y = e.clientY;
if (e.pointerType !== "mouse") {
if (e.pointerId === this.touchId && !this.touchMoved && Math.abs(x - this.touchX) + Math.abs(y - this.touchY) > touchSlop) {
this.touchMoved = true;
}
return;
}
const h = (((x >> 3) * 73856093) ^ ((y >> 3) * 19349663)) & 4095;
const bit = 1 << (h & 31);
if ((this.seen[h >>> 5] & bit) === 0) {
this.seen[h >>> 5] |= bit;
this.cells++;
}
if (!this.hasLast) {
this.lastX = x;
this.lastY = y;
this.hasLast = true;
return;
}
const dx = x - this.lastX;
const dy = y - this.lastY;
this.lastX = x;
this.lastY = y;
if (dx === 0 && dy === 0) {
return;
}
this.path += Math.sqrt(dx * dx + dy * dy);
this.segX += dx;
this.segY += dy;
const length = Math.sqrt(this.segX * this.segX + this.segY * this.segY);
if (length < segment) {
return;
}
if (this.hasPrev) {
const previous = Math.sqrt(this.prevX * this.prevX + this.prevY * this.prevY);
if ((this.segX * this.prevX + this.segY * this.prevY) / (length * previous) < turnCos) {
this.turns++;
}
}
this.prevX = this.segX;
this.prevY = this.segY;
this.hasPrev = true;
this.segX = 0;
this.segY = 0;
}
private onDown(e: PointerEvent): void {
if (!e.isTrusted || e.pointerType === "mouse") {
return;
}
this.touchId = e.pointerId;
this.touchX = e.clientX;
this.touchY = e.clientY;
this.touchMoved = false;
}
private onUp(e: PointerEvent): void {
if (e.pointerId !== this.touchId) {
return;
}
if (this.touchMoved) {
this.gestures++;
}
this.touchId = -1;
}
private onCancel(e: PointerEvent): void {
if (e.pointerId !== this.touchId) {
return;
}
this.gestures++;
this.touchId = -1;
}
private onScroll(e: Event): void {
if (e.isTrusted && e.timeStamp - this.lastScroll >= scrollGapMs) {
this.lastScroll = e.timeStamp;
this.scrolls++;
}
}
private onKey(e: KeyboardEvent): void {
if (e.isTrusted && !e.repeat) {
this.keys++;
}
}
score(): number {
const mouse = Math.min(25, this.path / 120) + Math.min(35, this.turns * 2.5) + Math.min(20, this.cells / 6);
const total = mouse + Math.min(45, this.gestures * 8) + Math.min(15, this.scrolls * 1.5) + Math.min(20, this.keys * 2);
this.save();
return Math.min(100, Math.round(total));
}
private load(): void {
let saved: Saved | null = null;
try {
const raw = sessionStorage.getItem(storageKey);
saved = raw ? (JSON.parse(raw) as Saved) : null;
} catch {
saved = this.memory;
}
if (!saved) {
return;
}
const n = (value: unknown) => (typeof value === "number" && Number.isFinite(value) && value > 0 ? value : 0);
this.path = n(saved.p);
this.turns = n(saved.t);
this.cells = n(saved.c);
this.gestures = n(saved.g);
this.scrolls = n(saved.s);
this.keys = n(saved.k);
}
save(): void {
const saved: Saved = {
p: Math.round(this.path),
t: this.turns,
c: this.cells,
g: this.gestures,
s: this.scrolls,
k: this.keys,
};
this.memory = saved;
try {
sessionStorage.setItem(storageKey, JSON.stringify(saved));
} catch {
return;
}
}
}
let tracker: Tracker | null = null;
export function startEntropy(): void {
tracker ??= new Tracker();
}
export function entropyScore(): number {
startEntropy();
return tracker ? tracker.score() : 0;
}
+483
View File
@@ -0,0 +1,483 @@
import { PowSearch, nonceSpan } from "./sha256";
const passKey = "luphoto.pass";
const navKey = "luphoto.nav";
const navTtlMs = 30000;
const holdMs = 900;
const sliceSize = 1 << 14;
const svgNS = "http://www.w3.org/2000/svg";
const line = "Press and hold to see the photos";
const passPattern = /^[A-Za-z0-9_-]{32}$/;
let memoryPass: string | null = null;
let memoryNav: string | null = null;
export type KeyContext = "nav" | "land";
export interface Answer {
token: string;
nonce: number;
}
export interface Puzzle {
token: string;
bits: number;
}
export interface KeyRequest {
build: string;
album: string;
photos: string[];
context: KeyContext;
entropy: number;
pass?: string;
page?: string;
challenge?: Answer;
}
export interface KeyReply {
keys?: Record<string, string>;
pass?: string;
page?: string;
stale?: boolean;
challenge?: Puzzle;
}
export class KeyError extends Error {
constructor(
readonly status: number,
readonly retryAfter: number,
) {
super("keys " + status);
}
}
export function readPass(): string {
let raw = memoryPass;
try {
raw = localStorage.getItem(passKey) ?? raw;
} catch {
raw = memoryPass;
}
return raw && passPattern.test(raw) ? raw : "";
}
export function writePass(pass: string | null): void {
memoryPass = pass;
try {
if (pass) {
localStorage.setItem(passKey, pass);
} else {
localStorage.removeItem(passKey);
}
} catch {
return;
}
}
export function markNav(slug: string): void {
memoryNav = JSON.stringify({ slug, at: Date.now() });
try {
sessionStorage.setItem(navKey, memoryNav);
} catch {
return;
}
}
export function takeNav(slug: string): boolean {
let raw = memoryNav;
try {
raw = sessionStorage.getItem(navKey) ?? raw;
sessionStorage.removeItem(navKey);
} catch {
raw = memoryNav;
}
memoryNav = null;
if (!raw) {
return false;
}
try {
const nav = JSON.parse(raw) as { slug?: unknown; at?: unknown };
const age = Date.now() - Number(nav.at);
return nav.slug === slug && age >= 0 && age <= navTtlMs;
} catch {
return false;
}
}
export async function requestKeys(body: KeyRequest): Promise<KeyReply> {
const response = await fetch("/k", {
method: "POST",
credentials: "same-origin",
cache: "no-store",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
if (!response.ok) {
throw new KeyError(response.status, Number(response.headers.get("Retry-After")) || 0);
}
return (await response.json()) as KeyReply;
}
function solveHere(puzzle: Puzzle): Promise<number> {
return new Promise((resolve) => {
const search = new PowSearch(puzzle.token, puzzle.bits);
let hi = 0;
let from = 0;
const step = () => {
const to = Math.min(nonceSpan, from + sliceSize);
const lo = search.run(hi, from, to);
if (lo >= 0) {
resolve(hi * nonceSpan + lo);
return;
}
from = to;
if (from >= nonceSpan) {
hi++;
from = 0;
}
setTimeout(step, 0);
};
setTimeout(step, 0);
});
}
export function solve(puzzle: Puzzle, workerUrl: string): Promise<number> {
if (puzzle.token.length !== 32 || !(puzzle.bits >= 1 && puzzle.bits <= 32)) {
return Promise.reject(new Error("puzzle"));
}
if (typeof Worker === "undefined" || !workerUrl) {
return solveHere(puzzle);
}
return new Promise((resolve, reject) => {
let worker: Worker;
try {
worker = new Worker(workerUrl);
} catch {
resolve(solveHere(puzzle));
return;
}
worker.onmessage = (event: MessageEvent<{ pow?: number }>) => {
const nonce = event.data.pow;
if (typeof nonce !== "number") {
return;
}
worker.terminate();
if (nonce < 0) {
reject(new Error("puzzle"));
} else {
resolve(nonce);
}
};
worker.onerror = () => {
worker.terminate();
resolve(solveHere(puzzle));
};
worker.postMessage({ type: "pow", token: puzzle.token, bits: puzzle.bits });
});
}
let active: Promise<KeyReply | null> | null = null;
export function challenge(
first: Promise<KeyReply>,
answer: (solution: Answer) => Promise<KeyReply>,
workerUrl: string,
cancellable: boolean,
): Promise<KeyReply | null> {
if (active) {
return active.then(() => null);
}
const run = new Promise<KeyReply | null>((resolve) => {
let held: () => void = () => undefined;
const holding = new Promise<void>((done) => {
held = done;
});
const card = new GateCard(
() => {
held();
card.wait();
},
cancellable ? () => resolve(null) : null,
);
const flow = async (): Promise<KeyReply> => {
let reply = await first;
while (reply.challenge) {
const puzzle = reply.challenge;
const nonce = solve(puzzle, workerUrl);
await holding;
reply = await answer({ token: puzzle.token, nonce: await nonce });
}
return reply;
};
flow().then(
(reply) => {
card.dismiss();
resolve(reply);
},
() => {
card.fail();
resolve(null);
},
);
});
active = run;
void run.then(() => {
active = null;
});
return run;
}
export interface GuardOptions {
build: string;
workerUrl: string;
minEntropy: () => number;
score: () => number;
}
export function guardLink(anchor: HTMLAnchorElement, slugOf: () => string, options: GuardOptions): void {
anchor.addEventListener("click", (e) => {
const slug = slugOf();
if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || !slug) {
return;
}
if (options.score() >= options.minEntropy() || readPass()) {
markNav(slug);
return;
}
e.preventDefault();
const href = anchor.href;
const base = (): KeyRequest => ({ build: options.build, album: slug, photos: [], context: "nav", entropy: options.score() });
void challenge(
requestKeys(base()),
(solution) => requestKeys({ ...base(), challenge: solution }),
options.workerUrl,
true,
).then((reply) => {
if (!reply) {
return;
}
if (reply.pass) {
writePass(reply.pass);
}
markNav(slug);
location.assign(href);
});
});
}
function capture(element: Element, pointerId: number): void {
try {
element.setPointerCapture(pointerId);
} catch {
return;
}
}
class GateCard {
private readonly root: HTMLElement;
private readonly button: HTMLButtonElement;
private readonly ring: SVGCircleElement;
private readonly status: HTMLElement;
private readonly text: HTMLElement;
private readonly inert: Element[] = [];
private readonly restore: Element | null;
private start = 0;
private frame = 0;
private holding = false;
private finished = false;
private gone = false;
constructor(
private readonly onHeld: () => void,
private readonly onCancel: (() => void) | null,
) {
this.restore = document.activeElement;
const root = document.createElement("div");
root.className = "gate";
root.setAttribute("role", "dialog");
root.setAttribute("aria-modal", "true");
root.setAttribute("aria-labelledby", "gate-line");
const card = document.createElement("div");
card.className = "gate-card";
const eyebrow = document.createElement("p");
eyebrow.className = "gate-eyebrow";
eyebrow.textContent = "Photos · Lucio";
const text = document.createElement("p");
text.className = "gate-line";
text.id = "gate-line";
text.textContent = line;
const button = document.createElement("button");
button.type = "button";
button.className = "gate-hold";
button.setAttribute("aria-label", "Hold to see the photos");
button.setAttribute("aria-describedby", "gate-status");
const svg = document.createElementNS(svgNS, "svg");
svg.setAttribute("viewBox", "0 0 64 64");
svg.setAttribute("aria-hidden", "true");
svg.setAttribute("focusable", "false");
const circle = (cls: string, r: string): SVGCircleElement => {
const c = document.createElementNS(svgNS, "circle");
c.setAttribute("class", cls);
c.setAttribute("cx", "32");
c.setAttribute("cy", "32");
c.setAttribute("r", r);
return c;
};
const ring = circle("gate-ring", "28");
ring.setAttribute("pathLength", "100");
svg.append(circle("gate-track", "28"), ring, circle("gate-dot", "6"));
button.appendChild(svg);
const status = document.createElement("p");
status.className = "visually-hidden";
status.id = "gate-status";
status.setAttribute("aria-live", "polite");
card.append(eyebrow, text, button, status);
root.appendChild(card);
this.root = root;
this.button = button;
this.ring = ring;
this.status = status;
this.text = text;
for (const child of Array.from(document.body.children)) {
if (!child.hasAttribute("inert")) {
child.setAttribute("inert", "");
this.inert.push(child);
}
}
document.body.appendChild(root);
document.documentElement.classList.add("has-gate");
this.bind();
button.focus({ preventScroll: true });
}
private bind(): void {
const button = this.button;
button.addEventListener("pointerdown", (e) => {
if (e.pointerType === "mouse" && e.button !== 0) {
return;
}
e.preventDefault();
capture(button, e.pointerId);
this.press();
});
for (const type of ["pointerup", "pointercancel", "lostpointercapture"]) {
button.addEventListener(type, () => this.release());
}
button.addEventListener("keydown", (e) => {
if (e.key === " " || e.key === "Enter") {
e.preventDefault();
if (!e.repeat) {
this.press();
}
}
});
button.addEventListener("keyup", (e) => {
if (e.key === " " || e.key === "Enter") {
e.preventDefault();
this.release();
}
});
button.addEventListener("blur", () => this.release());
button.addEventListener("click", (e) => e.preventDefault());
button.addEventListener("contextmenu", (e) => e.preventDefault());
this.root.addEventListener("transitionend", (e) => {
if (e.target === this.root && this.root.classList.contains("is-leaving")) {
this.root.remove();
}
});
if (this.onCancel) {
document.addEventListener("keydown", this.onEscape, true);
}
}
private readonly onEscape = (e: KeyboardEvent): void => {
if (e.key === "Escape" && !this.gone) {
e.preventDefault();
e.stopPropagation();
this.dismiss();
this.onCancel?.();
}
};
private setProgress(fraction: number): void {
this.ring.style.setProperty("stroke-dashoffset", String(100 - Math.max(0, Math.min(1, fraction)) * 100));
}
private press(): void {
if (this.holding || this.finished) {
return;
}
this.holding = true;
this.start = performance.now();
this.button.classList.add("is-pressed");
this.status.textContent = "Keep holding";
const tick = (now: number) => {
if (!this.holding) {
return;
}
const fraction = (now - this.start) / holdMs;
this.setProgress(fraction);
if (fraction >= 1) {
this.holding = false;
this.finished = true;
this.frame = 0;
this.button.classList.remove("is-pressed");
this.onHeld();
return;
}
this.frame = requestAnimationFrame(tick);
};
this.frame = requestAnimationFrame(tick);
}
private release(): void {
if (!this.holding) {
return;
}
this.holding = false;
cancelAnimationFrame(this.frame);
this.frame = 0;
this.button.classList.remove("is-pressed");
this.setProgress(0);
this.status.textContent = "";
}
wait(): void {
this.root.classList.add("is-waiting");
this.setProgress(0.28);
this.status.textContent = "One moment";
}
fail(): void {
this.root.classList.remove("is-waiting");
this.finished = true;
this.setProgress(0);
this.button.disabled = true;
this.text.textContent = "Something went wrong. Reload the page to try again.";
this.status.textContent = this.text.textContent;
}
dismiss(): void {
if (this.gone) {
return;
}
this.gone = true;
document.removeEventListener("keydown", this.onEscape, true);
cancelAnimationFrame(this.frame);
const hadFocus = this.root.contains(document.activeElement);
for (const element of this.inert) {
element.removeAttribute("inert");
}
document.documentElement.classList.remove("has-gate");
this.root.classList.add("is-leaving");
window.setTimeout(() => this.root.remove(), 400);
if (hadFocus) {
const target =
this.restore instanceof HTMLElement && this.restore !== document.body && this.restore.isConnected
? this.restore
: document.querySelector<HTMLElement>("main");
target?.focus({ preventScroll: true });
}
}
}
+26 -5
View File
@@ -32,7 +32,8 @@ export function neededLevel(pyramid: Pyramid, displayWidth: number, dpr: number)
return pyramid.levels.length - 1;
}
export function tileRange(level: Level, view: View, tileSize: number): TileRange | null {
export function tileRange(level: Level, view: View): TileRange | null {
const tileSize = level.tile_size;
const a = Math.max(0, view.u0 * level.width);
const b = Math.min(level.width, view.u1 * level.width);
const c = Math.max(0, view.v0 * level.height);
@@ -48,9 +49,10 @@ export function tileRange(level: Level, view: View, tileSize: number): TileRange
};
}
export function visibleTiles(pyramid: Pyramid, levelIndex: number, view: View, tileSize: number): TileRef[] {
export function visibleTiles(pyramid: Pyramid, levelIndex: number, view: View): TileRef[] {
const level = pyramid.levels[levelIndex];
const range = tileRange(level, view, tileSize);
const tileSize = level.tile_size;
const range = tileRange(level, view);
if (!range) {
return [];
}
@@ -68,18 +70,37 @@ export function visibleTiles(pyramid: Pyramid, levelIndex: number, view: View, t
return tiles.map(({ level: l, x, y, index }) => ({ level: l, x, y, index }));
}
export interface CellRect {
dx: number;
dy: number;
dw: number;
dh: number;
}
export function cellRect(level: Level, x: number, y: number, originX: number, originY: number, scale: number): CellRect | null {
const tileSize = level.tile_size;
const dx0 = Math.round(originX + x * tileSize * scale);
const dx1 = Math.round(originX + Math.min((x + 1) * tileSize, level.width) * scale);
const dy0 = Math.round(originY + y * tileSize * scale);
const dy1 = Math.round(originY + Math.min((y + 1) * tileSize, level.height) * scale);
if (dx1 <= dx0 || dy1 <= dy0) {
return null;
}
return { dx: dx0, dy: dy0, dw: dx1 - dx0, dh: dy1 - dy0 };
}
export function drawTile(
g: CanvasRenderingContext2D,
bitmap: { width: number; height: number } & CanvasImageSource,
level: Level,
x: number,
y: number,
tileSize: number,
overlap: number,
originX: number,
originY: number,
scale: number,
): void {
const tileSize = level.tile_size;
const overlap = level.overlap ?? 0;
const lx0 = x * tileSize;
const lx1 = Math.min((x + 1) * tileSize, level.width);
const ly0 = y * tileSize;
+6 -2
View File
@@ -1,7 +1,7 @@
import { mountWordmark, type MorphHandle } from "./brand";
import { BusyIndicator } from "./indicator";
import { Strip, type StripEnv } from "./strip";
import type { SiteIndex, Settings } from "./types";
import { poolUrl, type SiteIndex, type Settings } from "./types";
const hysteresis = 24;
@@ -30,7 +30,11 @@ export class IndexPage {
if (!album || !album.cover) {
continue;
}
this.strips.push(new Strip(anchor, album.cover, album.collapsed_focus_y ?? 0.5, env, (strip) => this.onStripStatus(strip)));
this.strips.push(
new Strip(anchor, album.cover, album.collapsed_focus_y ?? 0.5, poolUrl(index.build, album.slug, album.cover.hash), env, (strip) =>
this.onStripStatus(strip),
),
);
}
this.hoverMode = matchMedia("(hover: hover) and (pointer: fine)");
const header = document.querySelector<HTMLElement>(".site-header .wordmark");
+203
View File
@@ -0,0 +1,203 @@
import { entropyScore } from "./entropy";
import { KeyError, challenge, readPass, requestKeys, writePass, type KeyContext, type KeyReply, type KeyRequest } from "./gate";
import { fromHex } from "./sha256";
import type { GateInfo } from "./types";
export interface KeySource {
key(hash: string): Uint8Array | null;
settle(hash: string, signal: AbortSignal): Promise<void>;
}
export function fixedKeys(hex: string): KeySource {
const key = /^[0-9a-f]{64}$/.test(hex) ? fromHex(hex) : null;
return { key: () => key, settle: () => Promise.resolve() };
}
const batchSize = 8;
const settleMs = 400;
const retryMs = 2000;
const keyPattern = /^[0-9a-f]{64}$/;
export class AlbumKeys implements KeySource {
private readonly keys = new Map<string, Uint8Array>();
private readonly inflight = new Set<string>();
private readonly waiters = new Set<() => void>();
private readonly listeners: Array<(fresh: string[]) => void> = [];
private queue: string[] = [];
private busy = false;
private blocked = false;
private failed = false;
private pausedUntil = 0;
private page = "";
private readonly server: boolean;
constructor(
private readonly gate: GateInfo,
private readonly slug: string,
private readonly context: KeyContext,
private readonly workerUrl: string,
) {
this.server = gate.mode !== "off";
if (!this.server) {
for (const [hash, hex] of Object.entries(gate.keys ?? {})) {
if (keyPattern.test(hex)) {
this.keys.set(hash, fromHex(hex));
}
}
}
}
onKeys(listener: (fresh: string[]) => void): void {
this.listeners.push(listener);
}
key(hash: string): Uint8Array | null {
return this.keys.get(hash) ?? null;
}
has(hash: string): boolean {
return this.keys.has(hash);
}
want(near: string[], ahead: string[]): void {
if (!this.server || near.every((hash) => this.keys.has(hash) || this.inflight.has(hash))) {
return;
}
const missing = (hash: string) => !this.keys.has(hash) && !this.inflight.has(hash);
this.queue = Array.from(new Set(near.concat(ahead))).filter(missing);
this.pump();
}
settle(hash: string, signal: AbortSignal): Promise<void> {
return new Promise((resolve) => {
if (this.keys.has(hash) || this.blocked || this.failed || signal.aborted) {
resolve();
return;
}
const done = () => {
clearTimeout(timer);
this.waiters.delete(check);
signal.removeEventListener("abort", done);
resolve();
};
const check = () => {
if (this.keys.has(hash) || this.blocked || this.failed) {
done();
}
};
const timer = window.setTimeout(done, settleMs);
this.waiters.add(check);
signal.addEventListener("abort", done, { once: true });
});
}
private wake(): void {
for (const check of Array.from(this.waiters)) {
check();
}
}
private body(photos: string[], pass: string): KeyRequest {
const body: KeyRequest = { build: this.gate.build, album: this.slug, photos, context: this.context, entropy: entropyScore() };
if (pass) {
body.pass = pass;
}
if (this.page) {
body.page = this.page;
}
return body;
}
private pump(): void {
if (this.busy || this.blocked || this.failed || this.queue.length === 0 || performance.now() < this.pausedUntil) {
return;
}
const photos = this.queue.slice(0, batchSize);
this.queue = [];
void this.send(photos);
}
private pause(ms: number, photos: string[]): void {
this.pausedUntil = performance.now() + ms;
window.setTimeout(() => {
this.queue = Array.from(new Set(photos.concat(this.queue))).filter((hash) => !this.keys.has(hash) && !this.inflight.has(hash));
this.pump();
}, ms);
}
private async send(photos: string[]): Promise<void> {
this.busy = true;
for (const hash of photos) {
this.inflight.add(hash);
}
let pending: string[] = [];
let delay = 0;
try {
const pass = readPass();
const reply = await requestKeys(this.body(photos, pass));
this.absorb(reply, pass);
if (reply.challenge) {
this.blocked = true;
this.wake();
const solved = await challenge(
Promise.resolve(reply),
(solution) => requestKeys({ ...this.body(photos, ""), challenge: solution }),
this.workerUrl,
false,
);
this.blocked = false;
if (solved) {
this.absorb(solved, "");
} else {
this.failed = true;
}
}
} catch (error) {
if (error instanceof KeyError && error.status === 429) {
delay = Math.max(1, error.retryAfter) * 1000;
pending = photos;
} else if (error instanceof KeyError && error.status >= 400 && error.status < 500) {
this.failed = true;
} else {
delay = retryMs;
pending = photos;
}
} finally {
for (const hash of photos) {
this.inflight.delete(hash);
}
this.busy = false;
this.wake();
}
if (delay > 0) {
this.pause(delay, pending.filter((hash) => !this.keys.has(hash)));
} else {
this.pump();
}
}
private absorb(reply: KeyReply, sent: string): void {
if (reply.stale && sent && readPass() === sent) {
writePass(null);
}
if (reply.pass) {
writePass(reply.pass);
}
if (reply.page) {
this.page = reply.page;
}
const fresh: string[] = [];
for (const [hash, hex] of Object.entries(reply.keys ?? {})) {
if (keyPattern.test(hex) && !this.keys.has(hash)) {
this.keys.set(hash, fromHex(hex));
fresh.push(hash);
}
}
if (fresh.length > 0) {
this.wake();
for (const listener of this.listeners) {
listener(fresh);
}
}
}
}
+417 -65
View File
@@ -1,15 +1,18 @@
import type { TileCache } from "./cache";
import { drawTile, neededLevel, tileRange, visibleTiles, type TileRef, type View } from "./geometry";
import type { KeySource } from "./keys";
import { cellRect, drawTile, neededLevel, tileRange, visibleTiles, type TileRef, type View } from "./geometry";
import { AbortError, PRIORITY_CURRENT, PRIORITY_PREFETCH, decodeBlob, releaseImage, type Scheduler, type TileResult } from "./scheduler";
import type { ScrambleSpec } from "./scramble";
import { fromBase64, unseal } from "./sha256";
import { currentThroughput, recordThroughput } from "./throughput";
import type { Pyramid, Settings, Tiles } from "./types";
import type { PoolFile, Pyramid, Sealed, Settings, Tiles } from "./types";
export interface LoaderEnv {
scheduler: Scheduler;
cache: TileCache;
settings: Settings;
tiles: Tiles;
keys: KeySource;
requestDraw: () => void;
onStatus?: (loader: PhotoLoader) => void;
}
@@ -24,6 +27,9 @@ export interface LoadStatus {
const fadeMs = 180;
const retryMs = 400;
const poolRetryMs = 2000;
const idWidth = 16;
const jumbleKey = "j:";
function wait(ms: number, signal: AbortSignal): Promise<void> {
return new Promise((resolve, reject) => {
@@ -42,8 +48,63 @@ function wait(ms: number, signal: AbortSignal): Promise<void> {
signal.addEventListener("abort", stop, { once: true });
});
}
function until<T>(promise: Promise<T>, signal: AbortSignal, fallback: T): Promise<T> {
if (signal.aborted) {
return Promise.resolve(fallback);
}
return new Promise((resolve) => {
const stop = () => resolve(fallback);
signal.addEventListener("abort", stop, { once: true });
void promise.then((value) => {
signal.removeEventListener("abort", stop);
resolve(value);
});
});
}
const probeStep = 3;
const seedUpscale = 4;
const fillBudgetMs = 6000;
const enhanceBudgetMs = 4000;
const goodThroughput = 1500;
const enhanceMemoryShare = 0.35;
interface Outcome {
needed: number;
final: number;
throughput: number;
}
interface NetworkHints {
saveData?: boolean;
effectiveType?: string;
}
type HintedNavigator = Navigator & { connection?: NetworkHints; deviceMemory?: number };
function saveData(): boolean {
const connection = (navigator as HintedNavigator).connection;
return !!connection && (connection.saveData === true || /2g|3g/.test(connection.effectiveType ?? ""));
}
function capableDevice(): boolean {
const nav = navigator as HintedNavigator;
if ((nav.hardwareConcurrency ?? 4) < 4) {
return false;
}
return typeof nav.deviceMemory !== "number" || nav.deviceMemory >= 4;
}
function batchRate(results: PromiseSettledResult<TileResult>[], ms: number): number {
let bytes = 0;
for (const result of results) {
if (result.status === "fulfilled") {
bytes += result.value.bytes;
}
}
return bytes > 0 && ms > 0 ? bytes / ms : 0;
}
export interface DrawTarget {
g: CanvasRenderingContext2D;
@@ -61,23 +122,140 @@ export interface DrawTarget {
export class PhotoLoader {
private seedImage: CanvasImageSource | null = null;
private seedPromise: Promise<void> | null = null;
private seedAt = 0;
private pool: string[] | null = null;
private sealed = "";
private poolPromise: Promise<boolean> | null = null;
private poolRetryAt = 0;
private opened: Sealed | null = null;
private ids: string[][] | null = null;
private triedKey: Uint8Array | null = null;
private jumbleLevel = -1;
private jumble: string[] = [];
private settling = false;
private session: AbortController | null = null;
private prefetchController: AbortController | null = null;
private enhancer: AbortController | null = null;
private enhanceLevel = -1;
finalLevel = -1;
private targetLevel = -1;
readonly status: LoadStatus = { active: false, started: 0, planned: 0, done: 0, sharp: false };
constructor(readonly pyramid: Pyramid, private readonly env: LoaderEnv) {}
constructor(
readonly pyramid: Pyramid,
private readonly poolUrl: string,
private readonly env: LoaderEnv,
) {}
get stalled(): boolean {
return !this.opened && !this.settling;
}
private tileUrl(id: string): string {
const tiles = this.env.tiles;
return tiles.path + this.pyramid.hash + "/" + id + "." + tiles.format;
}
private ensurePool(): Promise<boolean> {
if (this.pool) {
return Promise.resolve(true);
}
if (!this.poolPromise) {
this.poolPromise = fetch(this.poolUrl, { credentials: "same-origin" })
.then((response) => (response.ok ? (response.json() as Promise<PoolFile>) : Promise.reject(new Error("pool"))))
.then((file) => {
const levels = this.pyramid.levels;
if (!Array.isArray(file.levels) || file.levels.length !== levels.length || typeof file.sealed !== "string") {
throw new Error("pool");
}
for (let i = 0; i < levels.length; i++) {
if (typeof file.levels[i] !== "string" || file.levels[i].length < levels[i].cols * levels[i].rows * idWidth) {
throw new Error("pool");
}
}
this.pool = file.levels;
this.sealed = file.sealed;
this.env.requestDraw();
return true;
})
.catch(() => {
this.poolPromise = null;
this.poolRetryAt = performance.now() + poolRetryMs;
return false;
});
}
return this.poolPromise;
}
private open(): boolean {
if (this.opened) {
return true;
}
const key = this.env.keys.key(this.pyramid.hash);
const pool = this.pool;
if (!key || !pool || key === this.triedKey) {
return false;
}
this.triedKey = key;
const plain = unseal(key, this.sealed);
let sealed: Sealed | null = null;
if (plain) {
try {
sealed = JSON.parse(new TextDecoder().decode(plain)) as Sealed;
} catch {
sealed = null;
}
}
const levels = this.pyramid.levels;
if (!sealed || !Array.isArray(sealed.levels) || sealed.levels.length !== levels.length) {
return false;
}
const ids: string[][] = [];
for (let l = 0; l < levels.length; l++) {
const map = sealed.levels[l].map;
const entries = pool[l].length / idWidth;
if (!Array.isArray(map) || map.length !== levels[l].cols * levels[l].rows) {
return false;
}
const row = new Array<string>(map.length);
for (let i = 0; i < map.length; i++) {
const at = map[i];
if (!(at >= 0 && at < entries)) {
return false;
}
row[i] = pool[l].substr(at * idWidth, idWidth);
}
ids.push(row);
}
this.opened = sealed;
this.ids = ids;
this.sealed = "";
void this.ensureSeed();
return true;
}
private prepare(): void {
if (!this.pool) {
if (!this.poolPromise && performance.now() >= this.poolRetryAt) {
void this.ensurePool();
}
return;
}
if (!this.opened) {
this.open();
}
}
ensureSeed(): Promise<void> {
if (!this.opened) {
return Promise.resolve();
}
if (!this.seedPromise) {
this.seedPromise = this.decodeSeed().then(
() => this.env.requestDraw(),
() => {
this.seedAt = performance.now();
this.env.requestDraw();
},
() => undefined,
);
}
@@ -85,15 +263,11 @@ export class PhotoLoader {
}
private async decodeSeed(): Promise<void> {
if (!this.pyramid.seed) {
const seed = this.opened?.seed;
if (!seed) {
return;
}
const raw = atob(this.pyramid.seed);
const bytes = new Uint8Array(raw.length);
for (let i = 0; i < raw.length; i++) {
bytes[i] = raw.charCodeAt(i);
}
const bitmap = await decodeBlob(new Blob([bytes], { type: "image/" + this.env.tiles.format }));
const bitmap = await decodeBlob(new Blob([fromBase64(seed)], { type: "image/" + this.env.tiles.format }));
const canvas = document.createElement("canvas");
canvas.width = bitmap.width * seedUpscale;
canvas.height = bitmap.height * seedUpscale;
@@ -113,45 +287,78 @@ export class PhotoLoader {
this.seedImage = canvas;
}
private async fetchTile(tile: TileRef, priority: number, signal: AbortSignal): Promise<TileResult> {
const level = this.pyramid.levels[tile.level];
const id = level.tiles[tile.index];
const tiles = this.env.tiles;
const scramble: ScrambleSpec | undefined =
tiles.scrambled && this.pyramid.scramble
? { seed: this.pyramid.scramble, level: tile.level, x: tile.x, y: tile.y, cell: tiles.cell ?? 64 }
: undefined;
private async request(key: string, id: string, priority: number, signal: AbortSignal, scramble?: ScrambleSpec): Promise<TileResult> {
const url = this.tileUrl(id);
let result: TileResult;
try {
result = await this.env.scheduler.request(id, this.tileUrl(id), priority, signal, scramble);
result = await this.env.scheduler.request(key, url, priority, signal, scramble);
} catch (error) {
if (signal.aborted || error instanceof AbortError) {
throw error;
}
await wait(retryMs + Math.random() * retryMs, signal);
result = await this.env.scheduler.request(id, this.tileUrl(id), priority, signal, scramble);
result = await this.env.scheduler.request(key, url, priority, signal, scramble);
}
this.env.cache.put(id, result.bitmap);
this.env.cache.put(key, result.bitmap);
this.env.requestDraw();
return result;
}
private fetchTile(tile: TileRef, priority: number, signal: AbortSignal): Promise<TileResult> {
const ids = this.ids;
const opened = this.opened;
if (!ids || !opened) {
return Promise.reject(new AbortError());
}
const id = ids[tile.level][tile.index];
const tiles = this.env.tiles;
const cell = tiles.cell ?? 64;
const scramble: ScrambleSpec | undefined =
tiles.scrambled && opened.scramble && this.pyramid.levels[tile.level].tile_size >= 2 * cell
? { seed: opened.scramble, level: tile.level, x: tile.x, y: tile.y, cell }
: undefined;
return this.request(id, id, priority, signal, scramble);
}
private fetchJumble(id: string, priority: number, signal: AbortSignal): Promise<TileResult> {
return this.request(jumbleKey + id, id, priority, signal);
}
private uncached(level: number, view: View): TileRef[] {
const ids = this.pyramid.levels[level].tiles;
return visibleTiles(this.pyramid, level, view, this.env.tiles.tile_size).filter((t) => !this.env.cache.has(ids[t.index]));
const ids = this.ids;
if (!ids) {
return [];
}
return visibleTiles(this.pyramid, level, view).filter((t) => !this.env.cache.has(ids[level][t.index]));
}
private uncachedBytes(level: number, view: View): number {
const bytes = this.pyramid.levels[level].bytes;
const bytes = this.opened?.levels[level].bytes ?? [];
let total = 0;
for (const tile of this.uncached(level, view)) {
total += bytes[tile.index];
total += bytes[tile.index] ?? 0;
}
return total;
}
private fetchAll(tiles: TileRef[], priority: number, signal: AbortSignal): Promise<PromiseSettledResult<TileResult>[]> {
return Promise.allSettled(tiles.map((tile) => this.fetchTile(tile, priority, signal)));
private chooseJumble(view: View, dpr: number): string[] {
const pool = this.pool;
if (!pool) {
return [];
}
if (this.jumbleLevel < 0) {
const level = this.probeLevel(view, dpr);
const grid = this.pyramid.levels[level].cols * this.pyramid.levels[level].rows;
const entries = pool[level].length / idWidth;
const picks = new Array<string>(grid);
for (let i = 0; i < grid; i++) {
const at = Math.floor(Math.random() * entries);
picks[i] = pool[level].substr(at * idWidth, idWidth);
}
this.jumbleLevel = level;
this.jumble = picks;
}
return Array.from(new Set(this.jumble)).filter((id) => !this.env.cache.has(jumbleKey + id));
}
probeLevel(view: View, dpr: number): number {
@@ -162,12 +369,12 @@ export class PhotoLoader {
this.env.onStatus?.(this);
}
private track(tiles: TileRef[], controller: AbortController, signal: AbortSignal): Promise<PromiseSettledResult<TileResult>[]> {
this.status.planned += tiles.length;
private track(jobs: Array<() => Promise<TileResult>>, controller: AbortController): Promise<PromiseSettledResult<TileResult>[]> {
this.status.planned += jobs.length;
this.notify();
return Promise.allSettled(
tiles.map((tile) =>
this.fetchTile(tile, PRIORITY_CURRENT, signal).finally(() => {
jobs.map((job) =>
job().finally(() => {
if (this.session === controller) {
this.status.done++;
this.notify();
@@ -177,7 +384,7 @@ export class PhotoLoader {
);
}
start(view: View, dpr: number, onSettled: () => void): void {
start(view: View, dpr: number, onSettled: () => void, enhance = false): void {
this.stopSession();
const controller = new AbortController();
this.session = controller;
@@ -188,8 +395,9 @@ export class PhotoLoader {
this.status.done = 0;
this.status.sharp = false;
this.notify();
void this.run(view, dpr, controller).then(() => {
if (this.session === controller) {
void this.run(view, dpr, controller).then((outcome) => {
const current = this.session === controller;
if (current) {
this.session = null;
this.status.active = false;
this.notify();
@@ -197,24 +405,50 @@ export class PhotoLoader {
if (!controller.signal.aborted || controller.signal.reason === "deadline") {
onSettled();
}
if (enhance && current && outcome && !controller.signal.aborted) {
void this.enhance(view, outcome);
}
});
}
private async run(view: View, dpr: number, controller: AbortController): Promise<void> {
private async run(view: View, dpr: number, controller: AbortController): Promise<Outcome | null> {
const signal = controller.signal;
const started = performance.now();
const budget = this.env.settings.budgetMs;
const timer = setTimeout(() => controller.abort("deadline"), budget);
try {
const ready = await until(this.ensurePool(), signal, false);
if (signal.aborted) {
return null;
}
if (ready && !this.open()) {
this.settling = true;
await this.env.keys.settle(this.pyramid.hash, signal);
this.settling = false;
if (signal.aborted) {
return null;
}
}
if (!ready || !this.open()) {
const ids = this.chooseJumble(view, dpr);
await this.track(
ids.map((id) => () => this.fetchJumble(id, PRIORITY_CURRENT, signal)),
controller,
);
return null;
}
await this.ensureSeed();
if (signal.aborted) {
return;
return null;
}
const needed = neededLevel(this.pyramid, view.displayWidth, dpr);
const probe = Math.max(0, needed - probeStep);
const probeTiles = this.uncached(probe, view).slice(0, 2);
if (probeTiles.length > 0) {
const results = await this.track(probeTiles, controller, signal);
const results = await this.track(
probeTiles.map((tile) => () => this.fetchTile(tile, PRIORITY_CURRENT, signal)),
controller,
);
let bytes = 0;
let ms = 0;
for (const result of results) {
@@ -228,7 +462,7 @@ export class PhotoLoader {
}
}
if (signal.aborted) {
return;
return null;
}
this.finalLevel = Math.max(this.finalLevel, probe);
const throughput = currentThroughput();
@@ -250,32 +484,104 @@ export class PhotoLoader {
this.finalLevel = final;
this.targetLevel = final;
this.env.requestDraw();
let measured = 0;
for (const level of plan) {
await this.track(this.uncached(level, view), controller, signal);
const tiles = this.uncached(level, view);
const at = performance.now();
const results = await this.track(
tiles.map((tile) => () => this.fetchTile(tile, PRIORITY_CURRENT, signal)),
controller,
);
if (signal.aborted) {
return;
return null;
}
const rate = tiles.length >= 2 ? batchRate(results, performance.now() - at) : 0;
if (rate > 0) {
measured = recordThroughput(rate);
}
}
return { needed, final, throughput: measured || currentThroughput() };
} finally {
clearTimeout(timer);
}
}
private async enhance(view: View, outcome: Outcome): Promise<void> {
if (!this.opened || saveData()) {
return;
}
const levels = this.pyramid.levels;
const { needed } = outcome;
const top = capableDevice() ? Math.min(levels.length - 1, needed + 1) : needed;
if (outcome.final >= top) {
return;
}
this.enhancer?.abort();
const controller = new AbortController();
this.enhancer = controller;
const signal = controller.signal;
const memory = this.env.cache.budget * enhanceMemoryShare;
let throughput = outcome.throughput;
let spent = 0;
for (let level = Math.max(outcome.final + 1, needed); level <= top; level++) {
const extra = level > needed;
if (extra) {
const info = levels[level];
const decoded = info.width * (view.u1 - view.u0) * info.height * (view.v1 - view.v0) * 4;
if (throughput < goodThroughput || decoded > memory) {
break;
}
}
spent += this.uncachedBytes(level, view) / throughput;
if (spent > (extra ? enhanceBudgetMs : fillBudgetMs)) {
break;
}
if (extra) {
this.enhanceLevel = Math.max(this.enhanceLevel, level);
}
const tiles = this.uncached(level, view);
const at = performance.now();
const results = await Promise.allSettled(tiles.map((tile) => this.fetchTile(tile, PRIORITY_PREFETCH, signal)));
if (signal.aborted) {
return;
}
const rate = tiles.length >= 2 ? batchRate(results, performance.now() - at) : 0;
if (rate > 0) {
throughput = recordThroughput(rate);
}
if (!extra) {
this.finalLevel = Math.max(this.finalLevel, level);
}
}
if (this.enhancer === controller) {
this.enhancer = null;
}
}
prefetchProbe(view: View, dpr: number): void {
const controller = this.resetPrefetch();
void this.ensureSeed().then(() => {
if (!controller.signal.aborted) {
void this.fetchAll(this.uncached(this.probeLevel(view, dpr), view), PRIORITY_PREFETCH, controller.signal);
const signal = controller.signal;
void this.ensurePool().then(async (ready) => {
if (signal.aborted || !ready || !this.open()) {
return;
}
await this.ensureSeed();
if (!signal.aborted) {
for (const tile of this.uncached(this.probeLevel(view, dpr), view)) {
void this.fetchTile(tile, PRIORITY_PREFETCH, signal).catch(() => undefined);
}
}
});
}
prefetchLevel(view: View, level: number): void {
if (level < 0) {
if (level < 0 || !this.opened) {
return;
}
const controller = this.resetPrefetch();
void this.fetchAll(this.uncached(level, view), PRIORITY_PREFETCH, controller.signal);
const signal = this.resetPrefetch().signal;
for (const tile of this.uncached(level, view)) {
void this.fetchTile(tile, PRIORITY_PREFETCH, signal).catch(() => undefined);
}
}
private resetPrefetch(): AbortController {
@@ -290,6 +596,8 @@ export class PhotoLoader {
}
stopSession(): void {
this.enhancer?.abort();
this.enhancer = null;
if (this.session) {
this.session.abort("superseded");
this.session = null;
@@ -303,6 +611,40 @@ export class PhotoLoader {
this.stopPrefetch();
}
private drawJumble(target: DrawTarget, view: View): boolean {
if (this.jumbleLevel < 0) {
return false;
}
const { g, originX, originY, width, now } = target;
const level = this.pyramid.levels[this.jumbleLevel];
const range = tileRange(level, view);
if (!range) {
return false;
}
const scale = width / level.width;
const cache = this.env.cache;
let animating = false;
g.imageSmoothingEnabled = true;
g.imageSmoothingQuality = "medium";
for (let y = range.y0; y <= range.y1; y++) {
for (let x = range.x0; x <= range.x1; x++) {
const entry = cache.get(jumbleKey + this.jumble[y * level.cols + x]);
const rect = entry ? cellRect(level, x, y, originX, originY, scale) : null;
if (!entry || !rect) {
continue;
}
const age = now - entry.at;
if (age < fadeMs) {
g.globalAlpha = Math.max(0, age / fadeMs);
animating = true;
}
g.drawImage(entry.bitmap, 0, 0, entry.bitmap.width, entry.bitmap.height, rect.dx, rect.dy, rect.dw, rect.dh);
g.globalAlpha = 1;
}
}
return animating;
}
draw(target: DrawTarget): boolean {
const { g, originX, originY, width, height, canvasWidth, canvasHeight } = target;
const left = Math.max(0, originX);
@@ -312,9 +654,7 @@ export class PhotoLoader {
if (right <= left || bottom <= top) {
return false;
}
if (!this.seedPromise) {
void this.ensureSeed();
}
this.prepare();
const view: View = {
displayWidth: target.displayWidth,
u0: (left - originX) / width,
@@ -322,22 +662,22 @@ export class PhotoLoader {
v0: (top - originY) / height,
v1: (bottom - originY) / height,
};
const tileSize = this.env.tiles.tile_size;
const overlap = this.env.tiles.overlap;
const cache = this.env.cache;
const levels = this.pyramid.levels;
const ids = this.ids;
const needed = neededLevel(this.pyramid, target.displayWidth, target.dpr);
const topLevel = Math.max(needed, Math.min(this.enhanceLevel, needed + 1));
let base = -1;
for (let l = needed; l >= 0 && base < 0; l--) {
const range = tileRange(levels[l], view, tileSize);
for (let l = topLevel; ids && l >= 0 && base < 0; l--) {
const range = tileRange(levels[l], view);
if (!range) {
continue;
}
let complete = true;
for (let y = range.y0; y <= range.y1 && complete; y++) {
for (let x = range.x0; x <= range.x1; x++) {
const entry = cache.get(levels[l].tiles[y * levels[l].cols + x]);
const entry = cache.get(ids[l][y * levels[l].cols + x]);
if (!entry || target.now - entry.at < fadeMs) {
complete = false;
break;
@@ -349,28 +689,40 @@ export class PhotoLoader {
}
}
if (base < 0 && this.seedImage) {
let animating = false;
if (base < 0) {
g.save();
g.beginPath();
g.rect(left, top, right - left, bottom - top);
g.clip();
g.imageSmoothingEnabled = true;
g.imageSmoothingQuality = "low";
g.drawImage(this.seedImage, originX, originY, width, height);
animating = this.drawJumble(target, view);
if (this.seedImage) {
const age = target.now - this.seedAt;
if (this.jumbleLevel >= 0 && age < fadeMs) {
g.globalAlpha = Math.max(0, age / fadeMs);
animating = true;
}
g.imageSmoothingEnabled = true;
g.imageSmoothingQuality = "low";
g.drawImage(this.seedImage, originX, originY, width, height);
g.globalAlpha = 1;
}
g.restore();
}
const sharpLevel = this.targetLevel >= 0 ? Math.min(this.targetLevel, needed) : needed;
const sharp = base >= sharpLevel;
const sharp = ids !== null && base >= sharpLevel;
if (sharp !== this.status.sharp) {
this.status.sharp = sharp;
queueMicrotask(() => this.notify());
}
if (!ids) {
return animating;
}
let animating = false;
for (let l = Math.max(0, base); l <= needed; l++) {
for (let l = Math.max(0, base); l <= topLevel; l++) {
const level = levels[l];
const range = tileRange(level, view, tileSize);
const range = tileRange(level, view);
if (!range) {
continue;
}
@@ -379,7 +731,7 @@ export class PhotoLoader {
g.imageSmoothingQuality = scale < 1 ? "high" : "medium";
for (let y = range.y0; y <= range.y1; y++) {
for (let x = range.x0; x <= range.x1; x++) {
const entry = cache.get(level.tiles[y * level.cols + x]);
const entry = cache.get(ids[l][y * level.cols + x]);
if (!entry) {
continue;
}
@@ -388,7 +740,7 @@ export class PhotoLoader {
g.globalAlpha = Math.max(0, age / fadeMs);
animating = true;
}
drawTile(g, entry.bitmap, level, x, y, tileSize, overlap, originX, originY, scale);
drawTile(g, entry.bitmap, level, x, y, originX, originY, scale);
g.globalAlpha = 1;
}
}
+2 -2
View File
@@ -46,10 +46,10 @@ export function unscramble(g: CellCanvas, image: CanvasImageSource, width: numbe
const cell = spec.cell;
const cols = Math.floor(width / cell);
const rows = Math.floor(height / cell);
const n = cols * rows;
if (n < 2) {
if (cols < 2 || rows < 2) {
return;
}
const n = cols * rows;
const perm = cellPermutation(n, tileSeed(spec));
for (let i = 0; i < n; i++) {
const source = perm[i];
+198
View File
@@ -0,0 +1,198 @@
const K = new Int32Array([
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be,
0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa,
0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85,
0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f,
0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
]);
const IV = new Int32Array([0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]);
function expand(w: Int32Array, from: number): void {
for (let i = from; i < 64; i++) {
const x = w[i - 15];
const y = w[i - 2];
const s0 = ((x >>> 7) | (x << 25)) ^ ((x >>> 18) | (x << 14)) ^ (x >>> 3);
const s1 = ((y >>> 17) | (y << 15)) ^ ((y >>> 19) | (y << 13)) ^ (y >>> 10);
w[i] = (w[i - 16] + s0 + w[i - 7] + s1) | 0;
}
}
function rounds(s: Int32Array, w: Int32Array, from: number, to: number): void {
let a = s[0];
let b = s[1];
let c = s[2];
let d = s[3];
let e = s[4];
let f = s[5];
let g = s[6];
let h = s[7];
for (let i = from; i < to; i++) {
const t1 =
(h + (((e >>> 6) | (e << 26)) ^ ((e >>> 11) | (e << 21)) ^ ((e >>> 25) | (e << 7))) + ((e & f) ^ (~e & g)) + K[i] + w[i]) | 0;
const t2 = ((((a >>> 2) | (a << 30)) ^ ((a >>> 13) | (a << 19)) ^ ((a >>> 22) | (a << 10))) + ((a & b) ^ (a & c) ^ (b & c))) | 0;
h = g;
g = f;
f = e;
e = (d + t1) | 0;
d = c;
c = b;
b = a;
a = (t1 + t2) | 0;
}
s[0] = a;
s[1] = b;
s[2] = c;
s[3] = d;
s[4] = e;
s[5] = f;
s[6] = g;
s[7] = h;
}
const W = new Int32Array(64);
const S = new Int32Array(8);
const H = new Int32Array(8);
export function sha256(message: Uint8Array, out: Uint8Array = new Uint8Array(32)): Uint8Array {
H.set(IV);
const length = message.length;
const blocks = Math.ceil((length + 9) / 64);
for (let block = 0; block < blocks; block++) {
const base = block * 64;
for (let i = 0; i < 16; i++) {
let word = 0;
for (let j = 0; j < 4; j++) {
const at = base + i * 4 + j;
let byte = 0;
if (at < length) {
byte = message[at];
} else if (at === length) {
byte = 0x80;
} else if (block === blocks - 1 && at >= base + 56) {
const bits = at - base - 56;
byte = bits < 3 ? 0 : bits === 3 ? (length >>> 29) & 255 : ((length * 8) >>> ((7 - bits) * 8)) & 255;
}
word = (word << 8) | byte;
}
W[i] = word;
}
expand(W, 16);
S.set(H);
rounds(S, W, 0, 64);
for (let i = 0; i < 8; i++) {
H[i] = (H[i] + S[i]) | 0;
}
}
for (let i = 0; i < 8; i++) {
out[i * 4] = H[i] >>> 24;
out[i * 4 + 1] = (H[i] >>> 16) & 255;
out[i * 4 + 2] = (H[i] >>> 8) & 255;
out[i * 4 + 3] = H[i] & 255;
}
return out;
}
export const nonceSpan = 4294967296;
export class PowSearch {
private readonly w = new Int32Array(64);
private readonly mid = new Int32Array(8);
private readonly s = new Int32Array(8);
private readonly shift: number;
constructor(token: string, bits: number) {
const w = this.w;
for (let i = 0; i < 8; i++) {
w[i] =
(token.charCodeAt(i * 4) << 24) |
(token.charCodeAt(i * 4 + 1) << 16) |
(token.charCodeAt(i * 4 + 2) << 8) |
token.charCodeAt(i * 4 + 3);
}
w[10] = 0x80000000 | 0;
w[15] = 320;
this.mid.set(IV);
rounds(this.mid, w, 0, 8);
this.shift = 32 - Math.max(1, Math.min(32, bits));
}
run(hi: number, from: number, to: number): number {
const w = this.w;
const s = this.s;
const mid = this.mid;
const shift = this.shift;
const h0 = IV[0];
w[8] = hi | 0;
for (let lo = from; lo < to; lo++) {
w[9] = lo | 0;
expand(w, 16);
s.set(mid);
rounds(s, w, 8, 64);
if ((h0 + s[0]) >>> shift === 0) {
return lo;
}
}
return -1;
}
}
export const sealMagic = "luphoto-sealed-1";
const nonceSize = 12;
export function fromHex(text: string): Uint8Array {
const out = new Uint8Array(text.length >>> 1);
for (let i = 0; i < out.length; i++) {
out[i] = parseInt(text.substr(i * 2, 2), 16);
}
return out;
}
export function toHex(bytes: Uint8Array): string {
let text = "";
for (let i = 0; i < bytes.length; i++) {
text += (bytes[i] < 16 ? "0" : "") + bytes[i].toString(16);
}
return text;
}
export function fromBase64(text: string): Uint8Array {
const raw = atob(text);
const out = new Uint8Array(raw.length);
for (let i = 0; i < raw.length; i++) {
out[i] = raw.charCodeAt(i);
}
return out;
}
export function unseal(key: Uint8Array, sealed: string): Uint8Array | null {
const data = fromBase64(sealed);
if (data.length < nonceSize + sealMagic.length) {
return null;
}
const block = new Uint8Array(32 + nonceSize + 4);
block.set(key.subarray(0, 32));
block.set(data.subarray(0, nonceSize), 32);
const stream = new Uint8Array(32);
const body = data.subarray(nonceSize);
for (let i = 0, at = 0; at < body.length; i++, at += 32) {
block[44] = i >>> 24;
block[45] = (i >>> 16) & 255;
block[46] = (i >>> 8) & 255;
block[47] = i & 255;
sha256(block, stream);
const end = Math.min(32, body.length - at);
for (let j = 0; j < end; j++) {
body[at + j] ^= stream[j];
}
if (i === 0) {
for (let j = 0; j < sealMagic.length; j++) {
if (body[j] !== sealMagic.charCodeAt(j)) {
return null;
}
}
}
}
return body.subarray(sealMagic.length);
}
+2 -1
View File
@@ -40,10 +40,11 @@ export class Strip {
readonly element: HTMLElement,
readonly cover: Pyramid,
private readonly focusY: number,
poolUrl: string,
env: StripEnv,
private readonly onStatus: (strip: Strip) => void,
) {
this.loader = new PhotoLoader(cover, {
this.loader = new PhotoLoader(cover, poolUrl, {
...env,
requestDraw: () => this.requestDraw(),
onStatus: () => this.onStatus(this),
+34 -5
View File
@@ -1,11 +1,10 @@
export interface Level {
width: number;
height: number;
tile_size: number;
overlap?: number;
cols: number;
rows: number;
quality: number;
tiles: string[];
bytes: number[];
}
export interface Pyramid {
@@ -13,8 +12,30 @@ export interface Pyramid {
width: number;
height: number;
levels: Level[];
}
export interface GateInfo {
build: string;
mode: string;
cover: string;
min_entropy: number;
keys?: Record<string, string>;
}
export interface PoolFile {
levels: string[];
sealed: string;
}
export interface SealedLevel {
map: number[];
bytes: number[];
}
export interface Sealed {
seed: string;
scramble?: string;
levels: SealedLevel[];
}
export interface Exif {
@@ -38,8 +59,6 @@ export interface Photo extends Pyramid {
export interface Tiles {
format: string;
tile_size: number;
overlap: number;
path: string;
scrambled?: boolean;
cell?: number;
@@ -54,6 +73,7 @@ export interface Manifest {
collapsed_focus_y: number;
show_exif: boolean;
tiles: Tiles;
gate: GateInfo;
cover: Pyramid;
og?: string;
photos: Photo[];
@@ -74,6 +94,7 @@ export interface IndexAlbum {
export interface SiteIndex {
build: string;
tiles: Tiles;
gate: GateInfo;
albums: IndexAlbum[];
}
@@ -88,6 +109,8 @@ export interface Settings {
maxDpr: number;
concurrency: number;
blockContextMenu: boolean;
gate: string;
minEntropy: number;
}
export function readSettings(body: HTMLElement): Settings {
@@ -107,5 +130,11 @@ export function readSettings(body: HTMLElement): Settings {
maxDpr: num(data.maxDpr, 2),
concurrency: Math.max(1, Math.round(num(data.concurrency, 6))),
blockContextMenu: data.blockContextMenu !== "false",
gate: data.gate === "off" ? "off" : "server",
minEntropy: data.minEntropy && Number.isFinite(Number(data.minEntropy)) ? Number(data.minEntropy) : 20,
};
}
export function poolUrl(build: string, slug: string, hash: string): string {
return "/a/" + encodeURIComponent(slug) + "/p/" + hash + "." + build + ".json";
}
+357 -20
View File
@@ -1,10 +1,12 @@
import { cloneChop, mountWordmark } from "./brand";
import { mountSignoffMark, mountWordmark } from "./brand";
import { CaptionPanel, setLang } from "./caption";
import type { View } from "./geometry";
import { guardLink, type GuardOptions } from "./gate";
import { BusyIndicator, ProgressLine } from "./indicator";
import { fixedKeys, type AlbumKeys } from "./keys";
import { PhotoLoader, type LoaderEnv } from "./loader";
import { Strip } from "./strip";
import type { Manifest, Settings, SiteIndex } from "./types";
import { poolUrl, type Manifest, type Settings, type SiteIndex } from "./types";
interface PhotoLayout {
scale: number;
@@ -42,6 +44,10 @@ const flickSpeed = 0.35;
const rubberBand = 0.35;
const captionZone = 0.2;
const idleMs = 2500;
const zoomSettleMs = 120;
const wheelLine = 16;
const wheelRate = 0.002;
const pinchWheelRate = 0.01;
function cubicBezier(x1: number, y1: number, x2: number, y2: number): (t: number) => number {
const cx = 3 * x1;
@@ -104,7 +110,9 @@ export class Viewer {
private readonly indicator: BusyIndicator;
private readonly progress: ProgressLine;
private readonly homeMark: HTMLElement | null;
private readonly signoffMark: HTMLElement;
private nextStrip: Strip | null = null;
private nextSlug = "";
private idleTimer = 0;
private announceTimer = 0;
private suspended = false;
@@ -133,12 +141,32 @@ export class Viewer {
private pinned = false;
private resizeTimer = 0;
private indexRequested = false;
private ox = 0;
private oy = 0;
private secondId: number | null = null;
private ax = 0;
private ay = 0;
private bx = 0;
private by = 0;
private pinching = false;
private stale = false;
private zoom = 1;
private zoomMax = 1;
private zoomPhoto = -1;
private zx = 0;
private zy = 0;
private slackX = 0;
private slackY = 0;
private zoomTimer = 0;
private gestureZoom = 1;
constructor(
private readonly stage: HTMLElement,
private readonly manifest: Manifest,
private readonly settings: Settings,
private readonly env: Omit<LoaderEnv, "requestDraw" | "onStatus">,
private readonly keys: AlbumKeys,
guard: GuardOptions | null,
) {
this.canvas = document.createElement("canvas");
this.canvas.className = "stage-canvas";
@@ -157,6 +185,9 @@ export class Viewer {
throw new Error("canvas 2d unavailable");
}
this.g = g;
this.signoffMark = document.createElement("span");
this.signoffMark.className = "chop";
this.signoffMark.setAttribute("aria-hidden", "true");
this.endCard = this.buildEndCard();
this.nextLink = this.endCard.querySelector("a.next-album") as HTMLAnchorElement;
this.nextFrame = this.endCard.querySelector(".next-strip") as HTMLElement;
@@ -175,6 +206,10 @@ export class Viewer {
this.measure();
this.current = this.stopForHash();
this.camera = this.stops[this.current].camera;
keys.onKeys((fresh) => this.onKeys(fresh));
if (guard) {
guardLink(this.nextLink, () => this.nextSlug, guard);
}
this.bind();
this.activate(-1);
this.requestDraw();
@@ -203,10 +238,7 @@ export class Viewer {
next.appendChild(frame);
const signoff = document.createElement("div");
signoff.className = "signoff";
const chop = cloneChop();
if (chop) {
signoff.appendChild(chop);
}
signoff.appendChild(this.signoffMark);
const signature = document.createElement("p");
signature.className = "signature";
signature.textContent = "— Lucio";
@@ -218,7 +250,8 @@ export class Viewer {
private loader(index: number): PhotoLoader {
let loader = this.loaders[index];
if (!loader) {
loader = new PhotoLoader(this.manifest.photos[index], {
const photo = this.manifest.photos[index];
loader = new PhotoLoader(photo, poolUrl(this.manifest.build, this.manifest.slug, photo.hash), {
...this.env,
requestDraw: () => this.requestDraw(),
onStatus: (changed) => {
@@ -235,6 +268,8 @@ export class Viewer {
const rect = this.stage.getBoundingClientRect();
this.vw = Math.max(1, rect.width);
this.vh = Math.max(1, rect.height);
this.ox = rect.left;
this.oy = rect.top;
this.dpr = Math.min(window.devicePixelRatio || 1, this.settings.maxDpr);
const cw = Math.max(1, Math.round(this.vw * this.dpr));
const ch = Math.max(1, Math.round(this.vh * this.dpr));
@@ -322,6 +357,13 @@ export class Viewer {
this.updateCaption();
}
});
stage.addEventListener("wheel", (e) => this.onWheel(e), { passive: false });
stage.addEventListener("gesturestart", (e) => {
e.preventDefault();
this.gestureZoom = this.zoom;
});
stage.addEventListener("gesturechange", (e) => this.onGesture(e as Event & { scale?: number; clientX?: number; clientY?: number }));
stage.addEventListener("gestureend", (e) => e.preventDefault());
stage.addEventListener("dragstart", (e) => e.preventDefault());
stage.addEventListener("selectstart", (e) => e.preventDefault());
if (this.settings.blockContextMenu) {
@@ -332,6 +374,9 @@ export class Viewer {
const target = this.stopForHash();
if (this.stops[target].photo !== this.stops[this.current].photo) {
this.jump(target);
} else if (this.clearZoom()) {
this.startSession();
this.updateCaption();
}
});
new ResizeObserver(() => this.onResize()).observe(stage);
@@ -349,6 +394,7 @@ export class Viewer {
if (before === this.vw + "x" + this.vh + "@" + this.dpr) {
return;
}
this.clearZoom();
this.tween = null;
this.camera = this.stops[this.current].camera;
this.requestDraw();
@@ -379,7 +425,11 @@ export class Viewer {
this.go(this.stops.length - 2);
break;
case "Escape":
location.assign("/");
if (this.zoomPhoto >= 0) {
this.go(this.current);
} else {
location.assign("/");
}
break;
case "i":
case "I":
@@ -393,7 +443,24 @@ export class Viewer {
}
private onPointerDown(e: PointerEvent): void {
if (this.pointerId !== null || (e.pointerType === "mouse" && e.button !== 0)) {
if (e.pointerType === "mouse" && e.button !== 0) {
return;
}
if (this.pointerId !== null) {
if (
this.secondId === null &&
e.pointerType !== "mouse" &&
this.pointerType !== "mouse" &&
!this.stale &&
(this.zoomPhoto >= 0 || (!this.dragging && this.enterZoom()))
) {
this.secondId = e.pointerId;
this.bx = e.clientX;
this.by = e.clientY;
this.pinching = true;
this.dragging = true;
this.stage.setPointerCapture(e.pointerId);
}
return;
}
if ((e.target as Element).closest("a, button")) {
@@ -402,8 +469,11 @@ export class Viewer {
this.pointerId = e.pointerId;
this.pointerType = e.pointerType;
this.dragging = false;
this.stale = false;
this.downX = e.clientX;
this.downY = e.clientY;
this.ax = e.clientX;
this.ay = e.clientY;
this.downT = e.timeStamp;
this.tween = null;
this.downCamera = this.camera;
@@ -422,7 +492,11 @@ export class Viewer {
}
return;
}
if (e.pointerId !== this.pointerId) {
if (this.pinching && (e.pointerId === this.pointerId || e.pointerId === this.secondId)) {
this.pinchMove(e.pointerId, e.clientX, e.clientY);
return;
}
if (e.pointerId !== this.pointerId || this.stale) {
return;
}
const dx = e.clientX - this.downX;
@@ -433,6 +507,16 @@ export class Viewer {
this.updateCaption();
}
if (!this.dragging) {
this.ax = e.clientX;
this.ay = e.clientY;
return;
}
if (this.zoomPhoto >= 0) {
this.zx += e.clientX - this.ax;
this.zy += e.clientY - this.ay;
this.ax = e.clientX;
this.ay = e.clientY;
this.settleZoom();
return;
}
this.samples.push({ t: e.timeStamp, x: e.clientX });
@@ -444,6 +528,10 @@ export class Viewer {
}
private onPointerUp(e: PointerEvent, cancelled: boolean): void {
if (this.pinching && (e.pointerId === this.pointerId || e.pointerId === this.secondId)) {
this.endPinch(e.pointerId);
return;
}
if (e.pointerId !== this.pointerId) {
return;
}
@@ -454,12 +542,16 @@ export class Viewer {
const wasDragging = this.dragging;
this.dragging = false;
this.stage.classList.remove("is-dragging");
if (this.stale) {
this.stale = false;
return;
}
const moved = Math.hypot(e.clientX - this.downX, e.clientY - this.downY);
if (!cancelled && !wasDragging && moved < tapDistance && e.timeStamp - this.downT < tapMs) {
this.onTap(e);
return;
}
if (!wasDragging) {
if (!wasDragging || this.zoomPhoto >= 0) {
return;
}
let velocity = 0;
@@ -491,7 +583,7 @@ export class Viewer {
private onTap(e: PointerEvent): void {
const stop = this.stops[this.current];
if (stop.photo < 0) {
if (stop.photo < 0 || this.zoomPhoto >= 0) {
return;
}
const rect = this.photoRect(stop.photo);
@@ -501,6 +593,178 @@ export class Viewer {
}
}
private onWheel(e: WheelEvent): void {
e.preventDefault();
if (this.pinching || (this.dragging && this.zoomPhoto < 0)) {
return;
}
let delta = e.deltaY;
if (e.deltaMode === 1) {
delta *= wheelLine;
} else if (e.deltaMode === 2) {
delta *= this.vh;
}
if (delta === 0) {
return;
}
const step = Math.max(-1, Math.min(1, delta * (e.ctrlKey ? pinchWheelRate : wheelRate)));
const x = e.clientX - this.ox;
const y = e.clientY - this.oy;
this.zoomTo(this.zoom * Math.exp(-step), x, y, x, y);
}
private onGesture(e: Event & { scale?: number; clientX?: number; clientY?: number }): void {
e.preventDefault();
if (this.pointerId !== null || !e.scale) {
return;
}
const x = (e.clientX ?? this.ox + this.vw / 2) - this.ox;
const y = (e.clientY ?? this.oy + this.vh / 2) - this.oy;
this.zoomTo(this.gestureZoom * e.scale, x, y, x, y);
}
private pinchMove(id: number, x: number, y: number): void {
const px = (this.ax + this.bx) / 2 - this.ox;
const py = (this.ay + this.by) / 2 - this.oy;
const before = Math.hypot(this.ax - this.bx, this.ay - this.by);
if (id === this.pointerId) {
this.ax = x;
this.ay = y;
} else {
this.bx = x;
this.by = y;
}
const after = Math.hypot(this.ax - this.bx, this.ay - this.by);
const target = before > 1 && after > 1 ? (this.zoom * after) / before : this.zoom;
this.zoomTo(target, px, py, (this.ax + this.bx) / 2 - this.ox, (this.ay + this.by) / 2 - this.oy);
}
private endPinch(id: number): void {
if (this.stage.hasPointerCapture(id)) {
this.stage.releasePointerCapture(id);
}
if (id === this.pointerId) {
this.pointerId = this.secondId;
this.ax = this.bx;
this.ay = this.by;
}
this.secondId = null;
this.pinching = false;
this.dragging = true;
if (this.zoomPhoto >= 0) {
this.settleZoom();
}
}
private enterZoom(): boolean {
const stop = this.stops[this.current];
if (stop.photo < 0 || this.suspended) {
return false;
}
const layout = this.layouts[stop.photo];
const max = this.manifest.photos[stop.photo].width / (window.devicePixelRatio || 1) / layout.width;
if (max <= 1.001) {
return false;
}
this.tween = null;
this.camera = stop.camera;
this.zoomPhoto = stop.photo;
this.zoomMax = max;
this.zoom = 1;
this.zx = layout.left - (this.camera - this.vw / 2);
this.zy = layout.top;
this.slackX = this.zx - this.clampAxis(this.zx, layout.width, this.vw, 0);
this.slackY = this.zy - this.clampAxis(this.zy, layout.height, this.vh, 0);
this.updateCaption();
return true;
}
private zoomTo(target: number, px: number, py: number, qx: number, qy: number): void {
if (this.zoomPhoto < 0 && (target <= 1 || !this.enterZoom())) {
return;
}
const zoom = Math.max(1, Math.min(this.zoomMax, target));
const f = zoom / this.zoom;
this.zx = qx - (px - this.zx) * f;
this.zy = qy - (py - this.zy) * f;
this.zoom = zoom;
this.settleZoom();
}
private settleZoom(): void {
const layout = this.layouts[this.zoomPhoto];
this.zx = this.clampAxis(this.zx, layout.width * this.zoom, this.vw, this.slackX);
this.zy = this.clampAxis(this.zy, layout.height * this.zoom, this.vh, this.slackY);
this.requestDraw();
if (this.zoom <= 1 && !this.pinching) {
this.camera = layout.left + this.vw / 2 - this.zx;
this.go(this.nearestStop(this.camera));
return;
}
clearTimeout(this.zoomTimer);
this.zoomTimer = window.setTimeout(() => this.startZoomSession(), zoomSettleMs);
}
private clampAxis(position: number, size: number, view: number, slack: number): number {
const centre = (view - size) / 2;
let lo = Math.min(view - size, centre);
let hi = Math.max(0, centre);
const extra = slack * Math.max(0, 2 - this.zoom);
if (extra > 0) {
hi += extra;
} else {
lo += extra;
}
return Math.min(hi, Math.max(lo, position));
}
private clearZoom(): boolean {
if (this.zoomPhoto < 0) {
return false;
}
this.zoomPhoto = -1;
this.zoom = 1;
this.gestureZoom = 1;
clearTimeout(this.zoomTimer);
this.zoomTimer = 0;
if (this.pointerId !== null) {
this.stale = true;
this.pinching = false;
this.secondId = null;
}
this.requestDraw();
return true;
}
private levelDpr(): number {
if (this.zoomPhoto >= 0 && this.zoom >= this.zoomMax * 0.999) {
return Math.max(this.dpr, window.devicePixelRatio || 1);
}
return this.dpr;
}
private startZoomSession(): void {
this.zoomTimer = 0;
if (this.suspended || this.zoomPhoto < 0) {
return;
}
const layout = this.layouts[this.zoomPhoto];
const w = layout.width * this.zoom;
const h = layout.height * this.zoom;
const a = Math.max(0, this.zx);
const b = Math.min(this.vw, this.zx + w);
const c = Math.max(0, this.zy);
const d = Math.min(this.vh, this.zy + h);
if (b <= a || d <= c) {
return;
}
this.loader(this.zoomPhoto).start(
{ displayWidth: w, u0: (a - this.zx) / w, u1: (b - this.zx) / w, v0: (c - this.zy) / h, v1: (d - this.zy) / h },
this.levelDpr(),
() => undefined,
);
}
private rubber(camera: number): number {
const min = this.stops[0].camera;
const max = this.stops[this.stops.length - 1].camera;
@@ -526,6 +790,7 @@ export class Viewer {
private go(index: number): void {
const target = Math.max(0, Math.min(this.stops.length - 1, index));
const previous = this.current;
const unzoomed = this.clearZoom();
const to = this.stops[target].camera;
if (this.reducedMotion.matches) {
this.crossfade(() => {
@@ -549,6 +814,9 @@ export class Viewer {
if (target !== previous) {
this.activate(previous);
} else {
if (unzoomed) {
this.startSession();
}
this.updateCaption();
}
this.requestDraw();
@@ -556,6 +824,7 @@ export class Viewer {
private jump(index: number): void {
const previous = this.current;
this.clearZoom();
this.tween = null;
this.crossfade(() => {
this.current = index;
@@ -609,8 +878,14 @@ export class Viewer {
if ((previousStop >= 0 || location.hash !== "") && location.hash !== "#" + (stop.photo + 1)) {
history.replaceState(history.state, "", "#" + (stop.photo + 1));
}
}
this.wantKeys();
if (stop.photo >= 0) {
this.startSession();
}
if (stop.photo < 0 || stop.photo === this.manifest.photos.length - 1) {
mountSignoffMark(this.signoffMark);
}
this.syncNextStrip();
this.updateCaption();
}
@@ -661,6 +936,7 @@ export class Viewer {
return;
}
this.suspended = false;
this.clearZoom();
this.canvas.width = 0;
this.measure();
this.camera = this.stops[this.current].camera;
@@ -669,6 +945,42 @@ export class Viewer {
this.requestDraw();
}
private wantKeys(): void {
const photos = this.manifest.photos;
const stop = this.stops[this.current];
const at = stop.photo < 0 ? photos.length - 1 : stop.photo;
const pick = (offsets: number[]): string[] => {
const out: string[] = [];
for (const offset of offsets) {
const i = at + offset;
if (i >= 0 && i < photos.length) {
out.push(photos[i].hash);
}
}
return out;
};
this.keys.want(pick([0, 1, -1, 2, 3]), pick([4, 5, 6, 7, -2, 8, 9]));
}
private onKeys(fresh: string[]): void {
if (this.suspended) {
return;
}
const photos = this.manifest.photos;
const got = (i: number) => i >= 0 && i < photos.length && fresh.includes(photos[i].hash);
const stop = this.stops[this.current];
if (this.zoomPhoto >= 0) {
if (got(this.zoomPhoto) && this.loader(this.zoomPhoto).stalled) {
this.startZoomSession();
}
} else if (stop.photo >= 0 && got(stop.photo) && this.loader(stop.photo).stalled) {
this.startSession();
} else if (stop.photo >= 0 && got(stop.photo + 1) && !this.loader(stop.photo).status.active) {
this.prefetchAround(this.current);
}
this.requestDraw();
}
private startSession(): void {
const stop = this.stops[this.current];
if (stop.photo < 0) {
@@ -676,11 +988,16 @@ export class Viewer {
}
const index = this.current;
const loader = this.loader(stop.photo);
loader.start(this.viewAt(stop), this.dpr, () => {
if (this.current === index) {
this.prefetchAround(index);
}
});
loader.start(
this.viewAt(stop),
this.dpr,
() => {
if (this.current === index) {
this.prefetchAround(index);
}
},
true,
);
this.indicator.watch(loader);
this.progress.watch(loader);
}
@@ -746,7 +1063,7 @@ export class Viewer {
private updateCaption(): void {
const stop = this.stops[this.current];
const visible = stop.photo >= 0 && !this.dragging && (this.pinned || this.hover);
const visible = stop.photo >= 0 && this.zoomPhoto < 0 && !this.dragging && (this.pinned || this.hover);
if (visible) {
const rect = this.photoRect(stop.photo);
this.caption.place(rect.left, rect.right - rect.left, this.vh - rect.bottom);
@@ -779,6 +1096,7 @@ export class Viewer {
return;
}
this.nextLink.href = "/a/" + encodeURIComponent(next.slug) + "/";
this.nextSlug = next.slug;
const eyebrow = this.nextLink.querySelector(".next-eyebrow");
const title = this.nextLink.querySelector(".next-title");
if (eyebrow) {
@@ -793,7 +1111,8 @@ export class Viewer {
this.nextFrame,
next.cover,
next.collapsed_focus_y ?? 0.5,
{ ...this.env, tiles: index.tiles },
poolUrl(index.build, next.slug, next.cover.hash),
{ ...this.env, keys: fixedKeys(index.gate.cover), tiles: index.tiles },
() => undefined,
);
this.nextLink.classList.add("has-strip");
@@ -835,7 +1154,25 @@ export class Viewer {
const dpr = this.dpr;
const near = this.stops[this.current].photo;
const from = Math.max(0, (near < 0 ? this.layouts.length - 1 : near) - 2);
const to = Math.min(this.layouts.length - 1, (near < 0 ? this.layouts.length - 1 : near) + 2);
const to = this.zoomPhoto >= 0 ? -1 : Math.min(this.layouts.length - 1, (near < 0 ? this.layouts.length - 1 : near) + 2);
if (this.zoomPhoto >= 0) {
const layout = this.layouts[this.zoomPhoto];
const w = layout.width * this.zoom;
if (this.loader(this.zoomPhoto).draw({
g,
originX: this.zx * dpr,
originY: this.zy * dpr,
width: w * dpr,
height: layout.height * this.zoom * dpr,
canvasWidth: cw,
canvasHeight: ch,
displayWidth: w,
dpr: this.levelDpr(),
now,
})) {
again = true;
}
}
for (let i = from; i <= to; i++) {
const layout = this.layouts[i];
if (layout.left + layout.width < left || layout.left > right) {
+25 -3
View File
@@ -1,4 +1,5 @@
import { unscramble, type ScrambleSpec } from "./scramble";
import { PowSearch, nonceSpan } from "./sha256";
interface FetchMessage {
type: "fetch";
@@ -12,7 +13,13 @@ interface AbortMessage {
key: number;
}
type Incoming = FetchMessage | AbortMessage;
interface PowMessage {
type: "pow";
token: string;
bits: number;
}
type Incoming = FetchMessage | AbortMessage | PowMessage;
interface Outgoing {
key: number;
@@ -23,9 +30,13 @@ interface Outgoing {
error?: string;
}
interface PowReply {
pow: number;
}
interface WorkerScope {
onmessage: ((event: MessageEvent<Incoming>) => void) | null;
postMessage(message: Outgoing, transfer?: Transferable[]): void;
postMessage(message: Outgoing | PowReply, transfer?: Transferable[]): void;
}
interface OffscreenLike {
@@ -42,6 +53,18 @@ const Offscreen = (self as unknown as { OffscreenCanvas?: OffscreenConstructor }
scope.onmessage = (event) => {
const message = event.data;
if (message.type === "pow") {
const search = new PowSearch(message.token, message.bits);
for (let hi = 0; hi < 2097152; hi++) {
const lo = search.run(hi, 0, nonceSpan);
if (lo >= 0) {
scope.postMessage({ pow: hi * nonceSpan + lo });
return;
}
}
scope.postMessage({ pow: -1 });
return;
}
if (message.type === "abort") {
controllers.get(message.key)?.abort();
controllers.delete(message.key);
@@ -49,7 +72,6 @@ scope.onmessage = (event) => {
}
void load(message);
};
function restore(bitmap: ImageBitmap, spec: ScrambleSpec): ImageBitmap {
if (!Offscreen) {
throw new Error("unsupported-offscreen");