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]>
This commit is contained in:
1 parent
aaf7cafdf9
commit
f5152fb709
30 files changed
+2136
-203
No files matched your search
@@ -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. A one-time robot check unlocks the tile maps; see [Protection](#protection). Design: [docs/DESIGN.md](docs/DESIGN.md).
|
||||
|
||||
## Commands
|
||||
|
||||
@@ -79,26 +79,42 @@ Unknown fields are errors, so typos are caught.
|
||||
| `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 = 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.decoys` | `4` | Decoy tiles per real tile in each photo folder (0–16); 0 turns decoys off. |
|
||||
| `protection.gate` | `true` | Show the press-and-hold robot check before photos unlock. `false` publishes the key in the clear and shows no check. |
|
||||
| `protection.pow_bits` | `20` | Proof-of-work size for the robot check (10–26); each extra bit doubles the average work. |
|
||||
|
||||
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 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.
|
||||
- **Robot check.** Each build picks a random salt and a random `n` below 2^`pow_bits`. The key is SHA-256("luphoto-key" | salt | n); only a 16-byte check value is published. On the first visit a small card asks the visitor to press and hold for 0.9 s while a Web Worker finds `n` (at 20 bits about 0.1–0.25 s in desktop V8; phones are several times slower). The pass is kept in `localStorage` for that build. Until it is unlocked, each photo shows a jumble of tiles drawn from its pool.
|
||||
- **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. A determined scraper that drives a real browser, or reimplements the client, can solve the check in a fraction of a second, 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 +151,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`. 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
|
||||
@@ -173,8 +189,10 @@ 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)
|
||||
t/<photo-hash>/<tile-id>.webp real tiles and decoys (hard links), unordered
|
||||
og/<hash>.jpg
|
||||
state/
|
||||
site.key
|
||||
|
||||
+28
-11
@@ -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 a sealed tile map behind a one-time robot check, JPEGs not listed in album.json are hidden.
|
||||
|
||||
## Architecture
|
||||
|
||||
@@ -53,20 +53,29 @@ 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.
|
||||
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, base64 inside the album manifest.
|
||||
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. 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. Each build writes `builds/<id>/` (HTML, manifests, per-photo pool files, assets, `404.html`, `robots.txt`, `.refs`, 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. Gate: random 16-byte salt and random n < 2^`pow_bits`. Key s = SHA-256("luphoto-key" | salt | n as 4 bytes big-endian). Published in the index and every manifest: `{build, salt, bits, check}` with check = first 16 bytes of SHA-256("luphoto-check" | salt | n). With `gate = false`: `{build, key}` and no robot check, 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(s | nonce | i as 4 bytes big-endian), 12-byte random nonce in front, base64.
|
||||
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.
|
||||
|
||||
## Loading in the browser
|
||||
|
||||
1. Seed (≈0 ms): the manifest is loaded; draw the seed scaled and blurred.
|
||||
0. Gate: if the gate is on and `localStorage` has no pass for this build, the robot-check card is shown at once and a Web Worker (the tile worker script, a separate instance) brute-forces n with an allocation-free SHA-256 (midstate of the first 7 rounds and the constant schedule words precomputed). Each photo's pool file is fetched when the photo or cover is near. Until unlocked, or when a pool cannot be opened, the photo shows its probe level filled with random pool entries drawn into the grid cells (one fetch per cell at most). After unlocking, pools are decrypted lazily on the main thread (a few hundred SHA-256 blocks per photo), the seed fades in over the jumble, and the real tiles follow as below.
|
||||
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.
|
||||
@@ -87,7 +96,11 @@ Lucio brand (source of truth: ../LUCIO_ip): graphite #111114 ground, paper #F3F1
|
||||
|
||||
## 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 sealed maps behind the robot check (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/`.
|
||||
|
||||
Robot check card (index and album pages, only without a pass for the current build): 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. If the worker is still searching, the ring turns indeterminate until it finishes. 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 `{build, s}` is kept in `localStorage` (memory if storage is blocked); a pass that fails to open a pool is dropped and the card comes back. 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, and decoys are byte-identical to tiles of other photos, so crawling every folder reveals which files are shared.
|
||||
|
||||
## Config `/etc/luphoto/config.toml`
|
||||
|
||||
@@ -110,7 +123,8 @@ 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 +140,9 @@ keep_builds = 3
|
||||
[protection]
|
||||
block_context_menu = true
|
||||
hotlink_allow = ["photos.luciochen.com"]
|
||||
decoys = 4
|
||||
gate = true
|
||||
pow_bits = 20
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
+119
-38
@@ -7,6 +7,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"log"
|
||||
"math"
|
||||
"os"
|
||||
@@ -21,6 +22,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 +39,8 @@ type Summary struct {
|
||||
BytesWritten int64
|
||||
BuildsRemoved int
|
||||
TilesRemoved int
|
||||
DecoysLinked int
|
||||
DecoysRemoved int
|
||||
Duration time.Duration
|
||||
}
|
||||
|
||||
@@ -52,6 +56,7 @@ type albumPlan struct {
|
||||
failed []string
|
||||
problem string
|
||||
manifest *site.Manifest
|
||||
records []*process.Record
|
||||
carriedOut bool
|
||||
}
|
||||
|
||||
@@ -253,8 +258,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 +269,57 @@ 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 {
|
||||
gate, err := protect.NewGate(b.cfg.Protection.PowBits, b.cfg.Protection.Gate)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
poolStart := time.Now()
|
||||
pools, linked, err := b.pools(lives, gate)
|
||||
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, gate, 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 +367,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 +381,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 +392,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 +414,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,17 +430,35 @@ 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) {
|
||||
@@ -428,7 +469,7 @@ func newBuildID() (string, error) {
|
||||
return time.Now().UTC().Format("20060102-150405") + "-" + hex.EncodeToString(suffix[:]), nil
|
||||
}
|
||||
|
||||
func (b *builder) writeBuild(id string, manifests []*site.Manifest) error {
|
||||
func (b *builder) writeBuild(id string, manifests []*site.Manifest, gate *protect.Gate, 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 +495,26 @@ 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: gate.Enabled,
|
||||
BaseURL: strings.TrimRight(b.cfg.Server.BaseURL, "/"),
|
||||
}
|
||||
|
||||
index := &site.Index{Build: id, Tiles: b.tiles(), Albums: []site.IndexAlbum{}}
|
||||
public := &site.Gate{Build: id}
|
||||
if gate.Enabled {
|
||||
public.Salt, public.Bits, public.Check = gate.SaltHex(), gate.Bits, gate.CheckHex()
|
||||
} else {
|
||||
public.Key = gate.KeyHex()
|
||||
}
|
||||
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 m.Hidden {
|
||||
continue
|
||||
}
|
||||
@@ -485,10 +541,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 +606,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 +646,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 +656,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 +739,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))
|
||||
}
|
||||
@@ -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, gate *protect.Gate) (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, gate)
|
||||
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, gate *protect.Gate) (*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(gate.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...)
|
||||
}
|
||||
@@ -54,6 +54,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 +73,9 @@ type Build struct {
|
||||
type Protection struct {
|
||||
BlockContextMenu bool `toml:"block_context_menu"`
|
||||
HotlinkAllow []string `toml:"hotlink_allow"`
|
||||
Decoys int `toml:"decoys"`
|
||||
Gate bool `toml:"gate"`
|
||||
PowBits int `toml:"pow_bits"`
|
||||
}
|
||||
|
||||
type Duration struct {
|
||||
@@ -102,13 +106,15 @@ func Defaults() Config {
|
||||
Albums: "/srv/luphoto/albums",
|
||||
},
|
||||
Images: Images{
|
||||
TileSize: 512,
|
||||
Overlap: 1,
|
||||
Format: "webp",
|
||||
Quality: Quality{Top: 90, Mid: 88, 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 +130,9 @@ func Defaults() Config {
|
||||
Protection: Protection{
|
||||
BlockContextMenu: true,
|
||||
HotlinkAllow: []string{"photos.luciochen.com"},
|
||||
Decoys: 4,
|
||||
Gate: true,
|
||||
PowBits: 20,
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -255,6 +264,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 +285,12 @@ 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")
|
||||
}
|
||||
if c.Protection.PowBits < 10 || c.Protection.PowBits > 26 {
|
||||
add("protection.pow_bits must be between 10 and 26")
|
||||
}
|
||||
for _, host := range c.Protection.HotlinkAllow {
|
||||
if host == "" || strings.ContainsAny(host, "/ ") {
|
||||
add("protection.hotlink_allow entry %q is not a host name", host)
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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 {
|
||||
@@ -124,6 +126,7 @@ func New(ctx context.Context, cfg *config.Config) (*Processor, error) {
|
||||
"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),
|
||||
|
||||
+30
-15
@@ -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]
|
||||
@@ -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
|
||||
}
|
||||
@@ -368,11 +381,12 @@ 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()),
|
||||
"--tile-size", strconv.Itoa(ts),
|
||||
"--overlap", strconv.Itoa(overlap),
|
||||
"--suffix", ext+p.vips.SaveOptions(p.images.Format, quality)); err != nil {
|
||||
return Level{}, err
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
package protect
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/binary"
|
||||
"encoding/hex"
|
||||
)
|
||||
|
||||
const (
|
||||
SealMagic = "luphoto-sealed-1"
|
||||
NonceSize = 12
|
||||
keyLabel = "luphoto-key"
|
||||
chkLabel = "luphoto-check"
|
||||
)
|
||||
|
||||
type Gate struct {
|
||||
Salt [16]byte
|
||||
N uint32
|
||||
Bits int
|
||||
Key [32]byte
|
||||
Check [16]byte
|
||||
Enabled bool
|
||||
}
|
||||
|
||||
func NewGate(bits int, enabled bool) (*Gate, error) {
|
||||
g := &Gate{Bits: bits, Enabled: enabled}
|
||||
var raw [4]byte
|
||||
if _, err := rand.Read(g.Salt[:]); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err := rand.Read(raw[:]); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
g.N = binary.BigEndian.Uint32(raw[:]) & (uint32(1)<<bits - 1)
|
||||
g.Key = Derive(keyLabel, g.Salt[:], g.N)
|
||||
check := Derive(chkLabel, g.Salt[:], g.N)
|
||||
copy(g.Check[:], check[:16])
|
||||
return g, nil
|
||||
}
|
||||
|
||||
func Derive(label string, salt []byte, n uint32) [32]byte {
|
||||
buf := make([]byte, 0, len(label)+len(salt)+4)
|
||||
buf = append(buf, label...)
|
||||
buf = append(buf, salt...)
|
||||
buf = binary.BigEndian.AppendUint32(buf, n)
|
||||
return sha256.Sum256(buf)
|
||||
}
|
||||
|
||||
func (g *Gate) SaltHex() string {
|
||||
return hex.EncodeToString(g.Salt[:])
|
||||
}
|
||||
|
||||
func (g *Gate) CheckHex() string {
|
||||
return hex.EncodeToString(g.Check[:])
|
||||
}
|
||||
|
||||
func (g *Gate) KeyHex() string {
|
||||
return hex.EncodeToString(g.Key[:])
|
||||
}
|
||||
|
||||
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:]
|
||||
}
|
||||
}
|
||||
+82
-25
@@ -32,15 +32,61 @@ 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
|
||||
}
|
||||
|
||||
type Gate struct {
|
||||
Build string `json:"build"`
|
||||
Salt string `json:"salt,omitempty"`
|
||||
Bits int `json:"bits,omitempty"`
|
||||
Check string `json:"check,omitempty"`
|
||||
Key string `json:"key,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 +95,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 +150,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 +171,7 @@ type Page struct {
|
||||
MaxDPR float64
|
||||
Concurrency int
|
||||
BlockContextMenu bool
|
||||
Gate bool
|
||||
BaseURL string
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -1 +1 @@
|
||||
"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=(d,x)=>{let c=document.createElementNS(i,d);for(let u in x)c.setAttribute(u,x[u]);return c},n=()=>r.matchMedia&&r.matchMedia("(prefers-reduced-motion: reduce)").matches,o=d=>Math.max(0,Math.min(1,d)),a=d=>d*d*(3-2*d),h=.5;function l(d,x){let c=0,u=0,f=null,g=0;function A(y){let b=(y-g)/x;g=y,c=c<u?Math.min(u,c+b):Math.max(u,c-b),d(c),f=c===u?null:requestAnimationFrame(A)}function v(y){if(u=y,n()){c=y,d(c);return}f===null&&(g=performance.now(),f=requestAnimationFrame(A))}return{play:()=>v(1),reverse:()=>v(0),toggle:()=>v(u?0:1),set:y=>{cancelAnimationFrame(f),f=null,u=c=y,d(c)},stop:()=>{cancelAnimationFrame(f),f=null},get t(){return c}}}function m(d,x,c,u){let f=o(u)*x;if(d.style.visibility=f<.05?"hidden":"visible",c==="both"){let g=f/2;d.setAttribute("stroke-dasharray",g.toFixed(2)+" "+Math.max(0,x-2*g).toFixed(2)+" "+g.toFixed(2)),d.setAttribute("stroke-dashoffset","0")}else c==="end"?(d.setAttribute("stroke-dasharray",f.toFixed(2)+" "+(2*x+20).toFixed(2)),d.setAttribute("stroke-dashoffset",(-(x-f)).toFixed(2))):(d.setAttribute("stroke-dasharray",f.toFixed(2)+" "+(2*x+20).toFixed(2)),d.setAttribute("stroke-dashoffset","0"))}function L(d,x={}){let c=Object.assign({trigger:"hover",color:"currentColor",rays:"#FFF3CF",duration:450,autoDelay:1800},x),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 f=sLine truncated
|
||||
"use strict";(()=>{(function(n){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=(u,g)=>{let d=document.createElementNS(i,u);for(let v in g)d.setAttribute(v,g[v]);return d},r=()=>n.matchMedia&&n.matchMedia("(prefers-reduced-motion: reduce)").matches,o=u=>Math.max(0,Math.min(1,u)),a=u=>u*u*(3-2*u),h=.5;function l(u,g){let d=0,v=0,f=null,M=0;function S(L){let w=(L-M)/g;M=L,d=d<v?Math.min(v,d+w):Math.max(v,d-w),u(d),f=d===v?null:requestAnimationFrame(S)}function p(L){if(v=L,r()){d=L,u(d);return}f===null&&(M=performance.now(),f=requestAnimationFrame(S))}return{play:()=>p(1),reverse:()=>p(0),toggle:()=>p(v?0:1),set:L=>{cancelAnimationFrame(f),f=null,v=d=L,u(d)},stop:()=>{cancelAnimationFrame(f),f=null},get t(){return d}}}function c(u,g,d,v){let f=o(v)*g;if(u.style.visibility=f<.05?"hidden":"visible",d==="both"){let M=f/2;u.setAttribute("stroke-dasharray",M.toFixed(2)+" "+Math.max(0,g-2*M).toFixed(2)+" "+M.toFixed(2)),u.setAttribute("stroke-dashoffset","0")}else d==="end"?(u.setAttribute("stroke-dasharray",f.toFixed(2)+" "+(2*g+20).toFixed(2)),u.setAttribute("stroke-dashoffset",(-(g-f)).toFixed(2))):(u.setAttribute("stroke-dasharray",f.toFixed(2)+" "+(2*g+20).toFixed(2)),u.setAttribute("stroke-dashoffset","0"))}function b(u,g={}){let d=Object.assign({trigger:"hover",color:"currentColor",rays:"#FFF3CF",duration:450,autoDelay:1800},g),v=s("svg",{viewBox:"0 0 "+t.vbw+" "+t.vbh,role:"img","aria-label":"Guoliang Chen, Lucio"});v.style.display="block",v.style.width="100%",v.style.height="auto";let f=sLine truncated
|
||||
@@ -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 v(t){let a=t.seed+"|"+t.level+"|"+t.x+"|"+t.y,o=2166136261;for(let r=0;r<a.length;r++)o=Math.imul(o^a.charCodeAt(r),16777619)>>>0;return o}function M(t,a){let o=new Array(t);for(let e=0;e<t;e++)o[e]=e;let r=a|0,n=()=>{r=r+1831565813|0;let e=Math.imul(r^r>>>15,1|r);return e=e+Math.imul(e^e>>>7,61|e)^e,((e^e>>>14)>>>0)/4294967296};for(let e=t-1;e>0;e--){let s=Math.floor(n()*(e+1)),i=o[e];o[e]=o[s],o[s]=i}return o}function A(t,a,o,r,n){t.drawImage(a,0,0);let e=n.cell,s=Math.floor(o/e),i=Math.floor(r/e);if(s<2||i<2)return;let c=s*i,f=M(c,v(n));for(let l=0;l<c;l++){let b=f[l];if(b===l)continue;let u=l%s*e,d=Math.floor(l/s)*e,h=b%s*e,I=Math.floor(b/s)*e;t.drawImage(a,u,d,e,e,h,I,e,e)}}var U=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]),m=new Int32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);function S(t,a){for(let o=a;o<64;o++){let r=t[o-15],n=t[o-2],e=(r>>>7|r<<25)^(r>>>18|r<<14)^r>>>3,s=(n>>>17|n<<15)^(n>>>19|n<<13)^n>>>10;t[o]=t[o-16]+e+t[o-7]+s|0}}function k(t,a,o,r){let n=t[0],e=t[1],s=t[2],i=t[3],c=t[4],f=t[5],l=t[6],b=t[7];for(let u=o;u<r;u++){let d=b+((c>>>6|c<<26)^(c>>>11|c<<21)^(c>>>25|c<<7))+(c&f^~c&l)+U[u]+a[u]|0,h=((n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10))+(n&e^n&s^e&s)|0;b=l,l=f,f=c,c=i+d|0,i=s,s=e,e=n,n=d+h|0}t[0]=n,t[1]=e,t[2]=s,t[3]=i,t[4]=c,t[5]=f,t[6]=l,t[7]=b}var H=new Int32Array(64),j=new Int32Array(8),F=new Int32Array(8);var C=new TextEncoder;function B(t,a,o){let r=C.encode(t),n=new Uint8Array(r.length+a.length+4);n.set(r),n.set(a,r.length);let e=r.length+a.length;return n[e]=o>>>24,n[e+1]=o>>>16&255,n[e+2]=o>>>8&255,n[e+3]=o&255,n}var y=class{constructor(a,o){this.w=new Int32Array(64);this.mid=new Int32Array(8);this.s=new Int32Array(8);this.target=new Int32Array(4);let r=new Uint8Array(64);r.set(B("luphoto-check",a,0)),r[33]=128,r[62]=33*8>>>8,r[63]=33*8&255;let n=this.w;for(let e=0;e<16;e++)n[e]=r[e*4]<<24|r[e*4+1]<<16|r[e*4+2]<<8|r[e*4+3];this.saltTail=r[28]<<24;for(let e=16;e<22;e++){let s=n[e-15],i=n[e-2],c=(s>>>7|s<<25)^(s>>>18|s<<14)^s>>>3,f=(i>>>17|i<<15)^(i>>>19|i<<13)^i>>>10;n[e]=n[e-16]+c+n[e-7]+f|0}this.mid.set(m),k(this.mid,n,0,7);for(let e=0;e<4;e++)this.target[e]=o[e*4]<<24|o[e*4+1]<<16|o[e*4+2]<<8|o[e*4+3]}run(a,o){let r=this.w,n=this.s,e=this.mid,s=this.target[0],i=this.saltTail;for(let c=a;c<o;c++)if(r[7]=i|c>>>8,r[8]=(c&255)<<24|8388608,S(r,22),n.set(e),k(n,r,7,64),(m[0]+n[0]|0)===s&&(m[1]+n[1]|0)===this.target[1]&&(m[2]+n[2]|0)===this.target[2]&&(m[3]+n[3]|0)===this.target[3])return c;return-1}};function p(t){let a=new Uint8Array(t.length>>>1);for(let o=0;o<a.length;o++)a[o]=parseInt(t.substr(o*2,2),16);return a}var x=self,g=new Map,O=typeof createImageBitmap=="function",w=self.OffscreenCanvas;x.onmessage=t=>{let a=t.data;if(a.type==="pow"){let o=new y(p(a.salt),p(a.check));x.postMessage({pow:o.run(0,2**a.bits)});return}if(a.type==="abort"){g.get(a.key)?.abort(),g.delete(a.key);return}E(a)};function T(t,a){if(!w)throw new Error("unsupported-offscreen");let o=new w(t.width,t.height),r=o.getContext("2d");if(!r)throw new Error("unsupported-offscreen");return A(r,t,t.width,t.height,a),t.close(),o.transferToImageBitmap()}async function E(t){if(!O){x.postMessage({key:t.key,ok:!1,bytes:0,ms:0,error:"unsupported-bitmap"});return}if(t.scramble&&!w){x.postMessage({key:t.key,ok:!1,bytes:0,ms:0,error:"unsupported-offscreen"});return}let a=new AbortController;g.set(t.key,a);let o=performance.now();try{let r=await fetch(t.url,{signal:a.signal,credentials:"same-origin"});if(!r.ok)throw new Error("HTTP "+r.status);let n=await r.blob(),e=performance.now()-o,s=await createImageBitmap(n);if(t.scramble&&(s=T(s,t.scramble)),a.signal.aborted)throw s.close(),new Error("aborted");x.postMessage({key:t.key,ok:!0,bitmap:s,bytes:n.size,ms:e},[s])}catch(r){let n=r instanceof Error?r.message:String(r);x.postMessage({key:t.key,ok:!1,bytes:0,ms:0,error:n})}finally{g.delete(t.key)}}})();
|
||||
@@ -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}}"{{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>
|
||||
|
||||
@@ -5,6 +5,6 @@ Run the site behind a Cloudflare Tunnel (`cloudflared.yml` in this folder). In s
|
||||
Cache rules (Caching → Cache Rules), in this order:
|
||||
|
||||
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.
|
||||
2. 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 1 holds for them.
|
||||
|
||||
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.
|
||||
@@ -16,7 +16,8 @@ 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 +33,6 @@ keep_builds = 3
|
||||
[protection]
|
||||
block_context_menu = true
|
||||
hotlink_allow = ["photos.luciochen.com"]
|
||||
decoys = 4
|
||||
gate = true
|
||||
pow_bits = 20
|
||||
+149
@@ -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,
|
||||
|
||||
+20
-6
@@ -1,5 +1,6 @@
|
||||
import { mountWordmark } from "./brand";
|
||||
import { TileCache, cacheBudget } from "./cache";
|
||||
import { Gate } from "./gate";
|
||||
import { IndexPage } from "./index";
|
||||
import { Scheduler } from "./scheduler";
|
||||
import { readSettings, type Manifest, type Settings, type SiteIndex } from "./types";
|
||||
@@ -17,20 +18,27 @@ 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> {
|
||||
async function startAlbum(stage: HTMLElement, settings: Settings, gate: Gate): Promise<void> {
|
||||
const manifest = await fetchJSON<Manifest>(settings.manifestUrl);
|
||||
if (manifest.photos.length === 0) {
|
||||
gate.abandon();
|
||||
return;
|
||||
}
|
||||
gate.configure(manifest.gate);
|
||||
const { scheduler, cache } = shared(settings);
|
||||
document.documentElement.classList.add("has-viewer");
|
||||
lifecycle(new Viewer(stage, manifest, settings, { scheduler, cache, settings, tiles: manifest.tiles }));
|
||||
lifecycle(new Viewer(stage, manifest, settings, { scheduler, cache, settings, gate, tiles: manifest.tiles }));
|
||||
}
|
||||
|
||||
async function startIndex(root: HTMLElement, settings: Settings): Promise<void> {
|
||||
async function startIndex(root: HTMLElement, settings: Settings, gate: Gate): Promise<void> {
|
||||
const index = await fetchJSON<SiteIndex>(settings.indexUrl);
|
||||
if (index.albums.length === 0) {
|
||||
gate.abandon();
|
||||
return;
|
||||
}
|
||||
gate.configure(index.gate);
|
||||
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, gate, tiles: index.tiles }));
|
||||
}
|
||||
|
||||
interface Suspendable {
|
||||
@@ -64,7 +72,11 @@ function boot(): void {
|
||||
if (settings.page === "album") {
|
||||
const stage = document.getElementById("stage");
|
||||
if (stage) {
|
||||
startAlbum(stage, settings).catch(() => showLoadError());
|
||||
const gate = new Gate(settings.build, settings.gate, settings.workerUrl);
|
||||
startAlbum(stage, settings, gate).catch(() => {
|
||||
gate.abandon();
|
||||
showLoadError();
|
||||
});
|
||||
}
|
||||
} else if (settings.page === "notfound") {
|
||||
const header = document.querySelector<HTMLElement>(".site-header .wordmark");
|
||||
@@ -74,7 +86,9 @@ function boot(): void {
|
||||
} else if (settings.page === "index") {
|
||||
const root = document.getElementById("strips");
|
||||
if (root) {
|
||||
startIndex(root, settings).catch(() => {
|
||||
const gate = new Gate(settings.build, settings.gate, settings.workerUrl);
|
||||
startIndex(root, settings, gate).catch(() => {
|
||||
gate.abandon();
|
||||
document.documentElement.classList.remove("has-strips");
|
||||
const header = document.querySelector<HTMLElement>(".site-header .wordmark");
|
||||
if (header && !header.classList.contains("has-svg")) {
|
||||
|
||||
+400
@@ -0,0 +1,400 @@
|
||||
import { PowSearch, deriveKey, fromHex, toHex } from "./sha256";
|
||||
import type { GateInfo } from "./types";
|
||||
|
||||
const storageKey = "luphoto.pass";
|
||||
const holdMs = 900;
|
||||
const sliceSize = 1 << 14;
|
||||
const svgNS = "http://www.w3.org/2000/svg";
|
||||
const line = "Press and hold to see the photos";
|
||||
|
||||
let memoryPass: string | null = null;
|
||||
|
||||
interface Pass {
|
||||
build: string;
|
||||
s: string;
|
||||
}
|
||||
|
||||
function readPass(): Pass | null {
|
||||
let raw = memoryPass;
|
||||
try {
|
||||
raw = localStorage.getItem(storageKey) ?? raw;
|
||||
} catch {
|
||||
raw = memoryPass;
|
||||
}
|
||||
if (!raw) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
const pass = JSON.parse(raw) as Partial<Pass>;
|
||||
if (typeof pass.build === "string" && typeof pass.s === "string" && /^[0-9a-f]{64}$/.test(pass.s)) {
|
||||
return { build: pass.build, s: pass.s };
|
||||
}
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function writePass(pass: Pass | null): void {
|
||||
memoryPass = pass ? JSON.stringify(pass) : null;
|
||||
try {
|
||||
if (memoryPass) {
|
||||
localStorage.setItem(storageKey, memoryPass);
|
||||
} else {
|
||||
localStorage.removeItem(storageKey);
|
||||
}
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
export class Gate {
|
||||
key: Uint8Array | null = null;
|
||||
private stored = false;
|
||||
private found: Uint8Array | null = null;
|
||||
private held = false;
|
||||
private info: GateInfo | null = null;
|
||||
private card: GateCard | null = null;
|
||||
private worker: Worker | null = null;
|
||||
private readonly listeners: Array<() => void> = [];
|
||||
|
||||
constructor(
|
||||
private readonly build: string,
|
||||
private readonly enabled: boolean,
|
||||
private readonly workerUrl: string,
|
||||
) {
|
||||
if (!enabled) {
|
||||
return;
|
||||
}
|
||||
const pass = readPass();
|
||||
if (pass && pass.build === build) {
|
||||
this.key = fromHex(pass.s);
|
||||
this.stored = true;
|
||||
return;
|
||||
}
|
||||
this.card = new GateCard(() => this.onHeld());
|
||||
}
|
||||
|
||||
onUnlock(listener: () => void): void {
|
||||
this.listeners.push(listener);
|
||||
}
|
||||
|
||||
configure(info: GateInfo): void {
|
||||
if (this.info) {
|
||||
return;
|
||||
}
|
||||
this.info = info;
|
||||
if (info.key) {
|
||||
this.found = fromHex(info.key);
|
||||
this.unlock(false);
|
||||
return;
|
||||
}
|
||||
if (this.key && info.build !== this.build) {
|
||||
this.reset();
|
||||
return;
|
||||
}
|
||||
if (!this.key) {
|
||||
this.search();
|
||||
}
|
||||
}
|
||||
|
||||
reject(key: Uint8Array): void {
|
||||
if (key !== this.key || !this.stored || !this.info || this.info.key) {
|
||||
return;
|
||||
}
|
||||
this.reset();
|
||||
}
|
||||
|
||||
abandon(): void {
|
||||
this.card?.dismiss();
|
||||
this.card = null;
|
||||
this.worker?.terminate();
|
||||
this.worker = null;
|
||||
}
|
||||
|
||||
private reset(): void {
|
||||
writePass(null);
|
||||
this.key = null;
|
||||
this.stored = false;
|
||||
this.held = false;
|
||||
this.found = null;
|
||||
if (!this.card) {
|
||||
this.card = new GateCard(() => this.onHeld());
|
||||
}
|
||||
this.search();
|
||||
}
|
||||
|
||||
private search(): void {
|
||||
const info = this.info;
|
||||
if (!info || !info.salt || !info.check || !info.bits || this.worker) {
|
||||
return;
|
||||
}
|
||||
const salt = fromHex(info.salt);
|
||||
const done = (n: number) => {
|
||||
this.worker?.terminate();
|
||||
this.worker = null;
|
||||
if (n < 0) {
|
||||
this.card?.fail();
|
||||
return;
|
||||
}
|
||||
this.found = deriveKey(salt, n);
|
||||
if (this.held) {
|
||||
this.unlock(true);
|
||||
}
|
||||
};
|
||||
const fallback = () => this.searchHere(salt, fromHex(info.check ?? ""), info.bits ?? 0, done);
|
||||
if (typeof Worker === "undefined" || !this.workerUrl) {
|
||||
fallback();
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const worker = new Worker(this.workerUrl);
|
||||
this.worker = worker;
|
||||
worker.onmessage = (event: MessageEvent<{ pow?: number }>) => {
|
||||
if (typeof event.data.pow === "number" && this.worker === worker) {
|
||||
done(event.data.pow);
|
||||
}
|
||||
};
|
||||
worker.onerror = () => {
|
||||
if (this.worker === worker) {
|
||||
worker.terminate();
|
||||
this.worker = null;
|
||||
fallback();
|
||||
}
|
||||
};
|
||||
worker.postMessage({ type: "pow", salt: info.salt, check: info.check, bits: info.bits });
|
||||
} catch {
|
||||
this.worker = null;
|
||||
fallback();
|
||||
}
|
||||
}
|
||||
|
||||
private searchHere(salt: Uint8Array, check: Uint8Array, bits: number, done: (n: number) => void): void {
|
||||
const search = new PowSearch(salt, check);
|
||||
const end = 2 ** bits;
|
||||
let from = 0;
|
||||
const step = () => {
|
||||
const to = Math.min(end, from + sliceSize);
|
||||
const n = search.run(from, to);
|
||||
from = to;
|
||||
if (n >= 0 || from >= end) {
|
||||
done(n);
|
||||
return;
|
||||
}
|
||||
setTimeout(step, 0);
|
||||
};
|
||||
setTimeout(step, 0);
|
||||
}
|
||||
|
||||
private onHeld(): void {
|
||||
this.held = true;
|
||||
if (this.found) {
|
||||
this.unlock(true);
|
||||
} else {
|
||||
this.card?.wait();
|
||||
}
|
||||
}
|
||||
|
||||
private unlock(remember: boolean): void {
|
||||
if (!this.found) {
|
||||
return;
|
||||
}
|
||||
this.key = this.found;
|
||||
this.stored = false;
|
||||
if (remember && this.enabled) {
|
||||
writePass({ build: this.info?.build ?? this.build, s: toHex(this.key) });
|
||||
}
|
||||
this.card?.dismiss();
|
||||
this.card = null;
|
||||
for (const listener of this.listeners) {
|
||||
listener();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
constructor(private readonly onHeld: () => void) {
|
||||
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();
|
||||
button.setPointerCapture(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();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
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 {
|
||||
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
@@ -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;
|
||||
|
||||
+17
-2
@@ -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");
|
||||
@@ -52,6 +56,17 @@ export class IndexPage {
|
||||
this.measure();
|
||||
this.observe();
|
||||
this.bind();
|
||||
env.gate.onUnlock(() => {
|
||||
if (this.suspended) {
|
||||
return;
|
||||
}
|
||||
for (const strip of this.strips) {
|
||||
if (strip.isNear) {
|
||||
strip.startSession();
|
||||
}
|
||||
strip.requestDraw();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
suspend(hidden: boolean): void {
|
||||
|
||||
+294
-57
@@ -1,15 +1,18 @@
|
||||
import type { TileCache } from "./cache";
|
||||
import { drawTile, neededLevel, tileRange, visibleTiles, type TileRef, type View } from "./geometry";
|
||||
import type { Gate } from "./gate";
|
||||
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;
|
||||
gate: Gate;
|
||||
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,6 +48,21 @@ 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;
|
||||
|
||||
@@ -61,23 +82,134 @@ 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 session: AbortController | null = null;
|
||||
private prefetchController: AbortController | null = null;
|
||||
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,
|
||||
) {}
|
||||
|
||||
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.gate.key;
|
||||
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) {
|
||||
this.env.gate.reject(key);
|
||||
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 +217,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 +241,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 +323,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();
|
||||
@@ -206,6 +367,18 @@ export class PhotoLoader {
|
||||
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;
|
||||
}
|
||||
if (!ready || !this.open()) {
|
||||
const ids = this.chooseJumble(view, dpr);
|
||||
await this.track(
|
||||
ids.map((id) => () => this.fetchJumble(id, PRIORITY_CURRENT, signal)),
|
||||
controller,
|
||||
);
|
||||
return;
|
||||
}
|
||||
await this.ensureSeed();
|
||||
if (signal.aborted) {
|
||||
return;
|
||||
@@ -214,7 +387,10 @@ export class PhotoLoader {
|
||||
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) {
|
||||
@@ -251,7 +427,10 @@ export class PhotoLoader {
|
||||
this.targetLevel = final;
|
||||
this.env.requestDraw();
|
||||
for (const level of plan) {
|
||||
await this.track(this.uncached(level, view), controller, signal);
|
||||
await this.track(
|
||||
this.uncached(level, view).map((tile) => () => this.fetchTile(tile, PRIORITY_CURRENT, signal)),
|
||||
controller,
|
||||
);
|
||||
if (signal.aborted) {
|
||||
return;
|
||||
}
|
||||
@@ -263,19 +442,34 @@ export class PhotoLoader {
|
||||
|
||||
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) {
|
||||
return;
|
||||
}
|
||||
if (!this.open()) {
|
||||
for (const id of this.chooseJumble(view, dpr)) {
|
||||
void this.fetchJumble(id, PRIORITY_PREFETCH, signal).catch(() => undefined);
|
||||
}
|
||||
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 {
|
||||
@@ -303,6 +497,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 +540,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 +548,21 @@ 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);
|
||||
|
||||
let base = -1;
|
||||
for (let l = needed; l >= 0 && base < 0; l--) {
|
||||
const range = tileRange(levels[l], view, tileSize);
|
||||
for (let l = needed; 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 +574,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++) {
|
||||
const level = levels[l];
|
||||
const range = tileRange(level, view, tileSize);
|
||||
const range = tileRange(level, view);
|
||||
if (!range) {
|
||||
continue;
|
||||
}
|
||||
@@ -379,7 +616,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 +625,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
@@ -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];
|
||||
|
||||
@@ -0,0 +1,236 @@
|
||||
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;
|
||||
}
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
function labelled(label: string, salt: Uint8Array, n: number): Uint8Array {
|
||||
const prefix = encoder.encode(label);
|
||||
const message = new Uint8Array(prefix.length + salt.length + 4);
|
||||
message.set(prefix);
|
||||
message.set(salt, prefix.length);
|
||||
const at = prefix.length + salt.length;
|
||||
message[at] = n >>> 24;
|
||||
message[at + 1] = (n >>> 16) & 255;
|
||||
message[at + 2] = (n >>> 8) & 255;
|
||||
message[at + 3] = n & 255;
|
||||
return message;
|
||||
}
|
||||
|
||||
export function deriveKey(salt: Uint8Array, n: number): Uint8Array {
|
||||
return sha256(labelled("luphoto-key", salt, n));
|
||||
}
|
||||
|
||||
export function checkFor(salt: Uint8Array, n: number): Uint8Array {
|
||||
return sha256(labelled("luphoto-check", salt, n)).subarray(0, 16);
|
||||
}
|
||||
|
||||
export class PowSearch {
|
||||
private readonly w = new Int32Array(64);
|
||||
private readonly mid = new Int32Array(8);
|
||||
private readonly s = new Int32Array(8);
|
||||
private readonly target = new Int32Array(4);
|
||||
private readonly saltTail: number;
|
||||
|
||||
constructor(salt: Uint8Array, check: Uint8Array) {
|
||||
const block = new Uint8Array(64);
|
||||
block.set(labelled("luphoto-check", salt, 0));
|
||||
block[33] = 0x80;
|
||||
block[62] = (33 * 8) >>> 8;
|
||||
block[63] = (33 * 8) & 255;
|
||||
const w = this.w;
|
||||
for (let i = 0; i < 16; i++) {
|
||||
w[i] = (block[i * 4] << 24) | (block[i * 4 + 1] << 16) | (block[i * 4 + 2] << 8) | block[i * 4 + 3];
|
||||
}
|
||||
this.saltTail = block[28] << 24;
|
||||
for (let i = 16; i < 22; 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;
|
||||
}
|
||||
this.mid.set(IV);
|
||||
rounds(this.mid, w, 0, 7);
|
||||
for (let i = 0; i < 4; i++) {
|
||||
this.target[i] = (check[i * 4] << 24) | (check[i * 4 + 1] << 16) | (check[i * 4 + 2] << 8) | check[i * 4 + 3];
|
||||
}
|
||||
}
|
||||
|
||||
run(from: number, to: number): number {
|
||||
const w = this.w;
|
||||
const s = this.s;
|
||||
const mid = this.mid;
|
||||
const t0 = this.target[0];
|
||||
const tail = this.saltTail;
|
||||
for (let n = from; n < to; n++) {
|
||||
w[7] = tail | (n >>> 8);
|
||||
w[8] = ((n & 255) << 24) | 0x800000;
|
||||
expand(w, 22);
|
||||
s.set(mid);
|
||||
rounds(s, w, 7, 64);
|
||||
if (((IV[0] + s[0]) | 0) !== t0) {
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
((IV[1] + s[1]) | 0) === this.target[1] &&
|
||||
((IV[2] + s[2]) | 0) === this.target[2] &&
|
||||
((IV[3] + s[3]) | 0) === this.target[3]
|
||||
) {
|
||||
return n;
|
||||
}
|
||||
}
|
||||
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
@@ -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),
|
||||
|
||||
+32
-5
@@ -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;
|
||||
salt?: string;
|
||||
bits?: number;
|
||||
check?: string;
|
||||
key?: 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,7 @@ export interface Settings {
|
||||
maxDpr: number;
|
||||
concurrency: number;
|
||||
blockContextMenu: boolean;
|
||||
gate: boolean;
|
||||
}
|
||||
|
||||
export function readSettings(body: HTMLElement): Settings {
|
||||
@@ -107,5 +129,10 @@ 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 !== "false",
|
||||
};
|
||||
}
|
||||
|
||||
export function poolUrl(build: string, slug: string, hash: string): string {
|
||||
return "/a/" + encodeURIComponent(slug) + "/p/" + hash + "." + build + ".json";
|
||||
}
|
||||
+23
-2
@@ -4,7 +4,7 @@ import type { View } from "./geometry";
|
||||
import { BusyIndicator, ProgressLine } from "./indicator";
|
||||
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;
|
||||
@@ -202,6 +202,7 @@ export class Viewer {
|
||||
this.requestDraw();
|
||||
this.wake();
|
||||
this.loadNextAlbum();
|
||||
env.gate.onUnlock(() => this.onUnlock());
|
||||
}
|
||||
|
||||
private buildEndCard(): HTMLElement {
|
||||
@@ -240,7 +241,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) => {
|
||||
@@ -928,6 +930,24 @@ export class Viewer {
|
||||
this.requestDraw();
|
||||
}
|
||||
|
||||
private onUnlock(): void {
|
||||
if (this.suspended) {
|
||||
return;
|
||||
}
|
||||
if (this.zoomPhoto >= 0) {
|
||||
this.startZoomSession();
|
||||
} else {
|
||||
this.startSession();
|
||||
}
|
||||
if (this.nextStrip) {
|
||||
if (this.nextStrip.isNear) {
|
||||
this.nextStrip.startSession();
|
||||
}
|
||||
this.nextStrip.requestDraw();
|
||||
}
|
||||
this.requestDraw();
|
||||
}
|
||||
|
||||
private startSession(): void {
|
||||
const stop = this.stops[this.current];
|
||||
if (stop.photo < 0) {
|
||||
@@ -1052,6 +1072,7 @@ export class Viewer {
|
||||
this.nextFrame,
|
||||
next.cover,
|
||||
next.collapsed_focus_y ?? 0.5,
|
||||
poolUrl(index.build, next.slug, next.cover.hash),
|
||||
{ ...this.env, tiles: index.tiles },
|
||||
() => undefined,
|
||||
);
|
||||
|
||||
+19
-3
@@ -1,4 +1,5 @@
|
||||
import { unscramble, type ScrambleSpec } from "./scramble";
|
||||
import { PowSearch, fromHex } from "./sha256";
|
||||
|
||||
interface FetchMessage {
|
||||
type: "fetch";
|
||||
@@ -12,7 +13,14 @@ interface AbortMessage {
|
||||
key: number;
|
||||
}
|
||||
|
||||
type Incoming = FetchMessage | AbortMessage;
|
||||
interface PowMessage {
|
||||
type: "pow";
|
||||
salt: string;
|
||||
check: string;
|
||||
bits: number;
|
||||
}
|
||||
|
||||
type Incoming = FetchMessage | AbortMessage | PowMessage;
|
||||
|
||||
interface Outgoing {
|
||||
key: number;
|
||||
@@ -23,9 +31,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 +54,11 @@ const Offscreen = (self as unknown as { OffscreenCanvas?: OffscreenConstructor }
|
||||
|
||||
scope.onmessage = (event) => {
|
||||
const message = event.data;
|
||||
if (message.type === "pow") {
|
||||
const search = new PowSearch(fromHex(message.salt), fromHex(message.check));
|
||||
scope.postMessage({ pow: search.run(0, 2 ** message.bits) });
|
||||
return;
|
||||
}
|
||||
if (message.type === "abort") {
|
||||
controllers.get(message.key)?.abort();
|
||||
controllers.delete(message.key);
|
||||
@@ -49,7 +66,6 @@ scope.onmessage = (event) => {
|
||||
}
|
||||
void load(message);
|
||||
};
|
||||
|
||||
function restore(bitmap: ImageBitmap, spec: ScrambleSpec): ImageBitmap {
|
||||
if (!Offscreen) {
|
||||
throw new Error("unsupported-offscreen");
|
||||
|
||||
Reference in new issue
Block a user