commit
18a397653a
21 files changed
+2775
No files matched your search
@@ -0,0 +1 @@
|
||||
* text=auto eol=lf
|
||||
@@ -0,0 +1,7 @@
|
||||
/bin/
|
||||
/out/
|
||||
/site/
|
||||
/cache/
|
||||
/albums/
|
||||
/dist/
|
||||
*.tmp-*
|
||||
@@ -0,0 +1,14 @@
|
||||
GO ?= go
|
||||
BIN := bin/luphoto
|
||||
|
||||
.PHONY: build deb clean
|
||||
|
||||
build:
|
||||
$(GO) build -trimpath -o $(BIN) ./cmd/luphoto
|
||||
|
||||
deb:
|
||||
@echo "deb packaging arrives in milestone M6" >&2
|
||||
@exit 1
|
||||
|
||||
clean:
|
||||
rm -rf bin
|
||||
@@ -0,0 +1,43 @@
|
||||
# LuPhoto
|
||||
|
||||
LuPhoto serves photos.luciochen.com. It is one Go program that reads album folders, cuts every photo into 512 px tiles at several resolutions with libvips, and publishes a static site that the browser stitches back together on a canvas. See [docs/DESIGN.md](docs/DESIGN.md).
|
||||
|
||||
Status: milestone M1, the processor CLI. `luphoto build` scans the albums, builds tile pyramids, writes manifests and switches the `current` build. `serve` and `export` run one build and exit until M6.
|
||||
|
||||
## Develop
|
||||
|
||||
All builds and runs happen in Docker (Ubuntu 24.04 with Go and libvips-tools); the Windows host has no libvips. From Git Bash or any POSIX shell:
|
||||
|
||||
```sh
|
||||
scripts/dev.sh go build -o bin/luphoto ./cmd/luphoto
|
||||
scripts/dev.sh go vet ./...
|
||||
scripts/dev.sh
|
||||
```
|
||||
|
||||
The image has no make; the `Makefile` is for hosts that have Go and make. The first call builds the `luphoto-dev` image. The repository is mounted at `/src`; Go module and build caches live in the `luphoto-gomod` and `luphoto-gocache` volumes. Extra `docker run` arguments, such as a mount for sample albums, go in `LUPHOTO_DEV_ARGS`:
|
||||
|
||||
```sh
|
||||
LUPHOTO_DEV_ARGS="-v /path/to/work:/work" scripts/dev.sh bin/luphoto -config /work/config.toml build
|
||||
```
|
||||
|
||||
`LUPHOTO_DEV_REBUILD=1` rebuilds the image.
|
||||
|
||||
## Run
|
||||
|
||||
```sh
|
||||
luphoto [-config /etc/luphoto/config.toml] build
|
||||
```
|
||||
|
||||
A missing config file means all defaults. Paths default to `/srv/luphoto/albums`, `/var/lib/luphoto/site` and `/var/cache/luphoto` when running as root or under systemd, otherwise to the XDG data and cache folders. The site key and per-photo records live in `state/` next to the output folder.
|
||||
|
||||
Output layout:
|
||||
|
||||
```
|
||||
site/
|
||||
current -> builds/<id>
|
||||
builds/<id>/index.html, index.<id>.json, a/<slug>/index.html, a/<slug>/manifest.<id>.json, t -> ../../t
|
||||
t/<photo-hash>/<tile-id>.webp
|
||||
state/
|
||||
site.key
|
||||
pyramids/<photo-hash>.json
|
||||
```
|
||||
@@ -0,0 +1,95 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
|
||||
"github.com/luciochen233/luphoto/internal/build"
|
||||
"github.com/luciochen233/luphoto/internal/config"
|
||||
)
|
||||
|
||||
const usage = `usage: luphoto [-config path] <command>
|
||||
|
||||
commands:
|
||||
build process albums once and publish a new build
|
||||
serve build, watch and serve over HTTP
|
||||
export build into the output folder and keep watching
|
||||
|
||||
flags:
|
||||
-config path config file (default /etc/luphoto/config.toml; a missing file means all defaults)
|
||||
`
|
||||
|
||||
func main() {
|
||||
os.Exit(run(os.Args[1:]))
|
||||
}
|
||||
|
||||
func run(args []string) int {
|
||||
logger := log.New(os.Stderr, "", 0)
|
||||
global := flag.NewFlagSet("luphoto", flag.ContinueOnError)
|
||||
global.SetOutput(os.Stderr)
|
||||
global.Usage = func() { fmt.Fprint(os.Stderr, usage) }
|
||||
configPath := global.String("config", config.DefaultPath, "config file")
|
||||
if err := global.Parse(args); err != nil {
|
||||
if errors.Is(err, flag.ErrHelp) {
|
||||
return 0
|
||||
}
|
||||
return 2
|
||||
}
|
||||
rest := global.Args()
|
||||
if len(rest) == 0 {
|
||||
fmt.Fprint(os.Stderr, usage)
|
||||
return 2
|
||||
}
|
||||
command := rest[0]
|
||||
sub := flag.NewFlagSet("luphoto "+command, flag.ContinueOnError)
|
||||
sub.SetOutput(os.Stderr)
|
||||
sub.Usage = global.Usage
|
||||
sub.StringVar(configPath, "config", *configPath, "config file")
|
||||
if err := sub.Parse(rest[1:]); err != nil {
|
||||
if errors.Is(err, flag.ErrHelp) {
|
||||
return 0
|
||||
}
|
||||
return 2
|
||||
}
|
||||
if sub.NArg() > 0 {
|
||||
fmt.Fprintf(os.Stderr, "luphoto %s: unexpected arguments %v\n", command, sub.Args())
|
||||
return 2
|
||||
}
|
||||
switch command {
|
||||
case "build", "serve", "export":
|
||||
default:
|
||||
fmt.Fprintf(os.Stderr, "luphoto: unknown command %q\n\n%s", command, usage)
|
||||
return 2
|
||||
}
|
||||
|
||||
cfg, err := config.Load(*configPath)
|
||||
if err != nil {
|
||||
logger.Printf("luphoto: %v", err)
|
||||
return 1
|
||||
}
|
||||
if cfg.Source == "" {
|
||||
logger.Printf("luphoto: config %s not found, using defaults", *configPath)
|
||||
}
|
||||
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
|
||||
summary, err := build.Run(ctx, cfg, logger)
|
||||
if err != nil {
|
||||
logger.Printf("luphoto: build failed: %v", err)
|
||||
return 1
|
||||
}
|
||||
logger.Print(summary.String())
|
||||
|
||||
if command != "build" {
|
||||
logger.Printf("luphoto %s: not implemented yet (arrives in milestone M6); built once, exiting", command)
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
+155
@@ -0,0 +1,155 @@
|
||||
# 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.
|
||||
|
||||
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.
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
uploads (rsync/SFTP) -> /srv/luphoto/albums -> watcher (debounce) -> processor (libvips) -> build swap (builds/<id>, flip current)
|
||||
-> serve mode (built-in HTTP) or export mode (folder for Caddy/nginx) -> Cloudflare Tunnel + cache -> browser canvas stitches visible tiles
|
||||
```
|
||||
|
||||
- Commands: `luphoto build` runs once; `luphoto serve` builds, watches and serves; `luphoto export` builds into the output folder and keeps watching. `-config` flag, default `/etc/luphoto/config.toml`.
|
||||
- Tiling with libvips CLI (`vips`), installed by `apt install libvips-tools`. Support libvips 8.12 (Ubuntu 22.04) and 8.15 (Ubuntu 24.04): metadata stripping is `strip` on 8.12 and `keep=none` on 8.15+.
|
||||
- Front-end: plain TypeScript, no framework, bundled with esbuild, embedded in the binary with `go:embed`. Fixed Lucio brand.
|
||||
- Speed and memory matter: photos are processed in parallel by a bounded worker pool; hashing, EXIF reading and tile renaming run concurrently; the browser fetches tiles concurrently and decodes off the main thread.
|
||||
|
||||
## Album folders
|
||||
|
||||
```
|
||||
/srv/luphoto/albums/
|
||||
2026-10-iceland/
|
||||
album.json
|
||||
DSC_0001.jpg
|
||||
PANO_0007.jpg
|
||||
```
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"title": "Iceland, in October",
|
||||
"subtitle": "冰岛 · 十月",
|
||||
"date": "2026-10",
|
||||
"order": 10,
|
||||
"hidden": false,
|
||||
"cover": { "photo": "PANO_0007.jpg", "crop": [0, 410, 8256, 2322] },
|
||||
"collapsed_focus_y": 0.5,
|
||||
"show_exif": true,
|
||||
"photos": [
|
||||
{ "file": "DSC_0001.jpg", "title": "Vík", "caption": "Black sand, 7 a.m.", "alt": "…" },
|
||||
{ "file": "PANO_0007.jpg", "caption": "…", "slides": 2 }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
- Order follows `photos`. JPEGs not listed are hidden: never processed, never shown.
|
||||
- `cover.crop` is `[x, y, w, h]` in original pixels; or `cover.focus_y` (0–1) picks a 32:9 band at full width. Default: first photo, focus_y 0.5.
|
||||
- `order` sorts ascending; albums without it sort newest `date` first, after ordered ones. `hidden: true` builds the album but leaves it off the index.
|
||||
- Album slug = folder name. Captions are plain text with `*emphasis*` and line breaks only.
|
||||
- A broken album.json makes the build skip that album and log why; the previous build stays live.
|
||||
|
||||
## Processing each photo
|
||||
|
||||
1. Autorotate by EXIF orientation, convert to sRGB from the embedded profile.
|
||||
2. Read camera, lens, focal length, aperture, shutter, ISO and date into the manifest. Drop everything else, including GPS. Tiles carry no metadata.
|
||||
3. Pyramid: tiles 512 px, 1 px overlap; each level halves the previous one until the long edge is under 100 px. Level 0 is the smallest.
|
||||
4. WebP by default (AVIF optional). Quality per level: `top` for the top two levels, `low` for levels whose long edge is at most 1100 px, `mid` otherwise.
|
||||
5. Seed: a 48 px (long edge) WebP, base64 inside the album manifest.
|
||||
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`.
|
||||
|
||||
Incremental: a photo is reprocessed only when its photo-hash is new. Each build writes `builds/<id>/` (HTML, manifests, assets) next to a shared `t/` tile folder; 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.
|
||||
|
||||
Storage: about 1.33× the top level, roughly 6–10 MB of tiles per Z8 photo.
|
||||
|
||||
## Loading in the browser
|
||||
|
||||
1. Seed (≈0 ms): the manifest is loaded; draw the seed scaled and blurred.
|
||||
2. Needed level: smallest level whose width ≥ displayed width × min(devicePixelRatio, max_dpr).
|
||||
3. Probe: fetch 1–2 tiles of the level about 1/8 of the needed one; measure throughput; blend with earlier measurements kept in sessionStorage.
|
||||
4. Final level: highest level up to the needed one whose visible-tile bytes ÷ throughput ≤ (budget − elapsed) × 0.8. If it is 2+ levels above the probe, fetch one intermediate level first.
|
||||
5. Fetch only visible tiles, centre outwards, `concurrency` at a time; each tile fades in over the lower layer as it decodes.
|
||||
6. Deadline `budget_ms` (3000): abort unfinished upgrades and keep what is on screen.
|
||||
|
||||
Moving to another photo aborts that photo's requests. Prefetch the next photo's seed and probe level and, for multi-slide photos, the next slide's tiles. Decoded tiles live in an LRU cache capped at about 250 MB on desktop and 120 MB on phones. Decode with `createImageBitmap` (in a worker where supported). The canvas is always viewport-sized. Pixel density capped at `max_dpr` (2).
|
||||
|
||||
## Screens
|
||||
|
||||
Album index: full-width strips, 8 px apart on phones, 16 px on desktop. Header with the Lucio wordmark (Guoliang → Lucio morph on hover, the only animation on this screen); footer with the chop. Closed strip 32:6 showing the `collapsed_focus_y` band of the 32:9 cover, height `min(100vw*6/32, 28vh)`; open 32:9, height `min(100vw*9/32, 62vh)`; wider screens crop left/right, never stretch. Desktop: hover opens. Touch: the strip nearest the vertical centre opens while scrolling; tap enters. On open the height animates 240 ms, then the title fades in (light-on): mono date line, then the title in Bricolage Grotesque, bottom-left. Covers use the tile loader; closed strips load only the visible band; only strips near the viewport load.
|
||||
|
||||
Album viewer: one photo at a time, contained in the viewport (fills height or width, never stretched), centred on graphite. Swipe right-to-left, ←/→, click-and-drag; one pointer-events handler for mouse and touch with flick velocity and rubber-band ends; Home/End; Esc returns to the index. `slides: N`: the photo is scaled so a 1/N-wide section fits the viewport; moving between its slides is a continuous pan. `/a/<slug>/#7` opens photo 7. End card: chop, "— Lucio", the next album's strip. Reduced motion: crossfades.
|
||||
|
||||
Captions: hidden by default; shown while the pointer is in the bottom 20% of the photo; click or tap pins/unpins; `i` toggles. A tap is < 10 px movement and < 300 ms. Panel: mono line `03 / 12 · Z8 · 24-70 f/2.8 · 35mm · f/8 · 1/250 · ISO 64` (EXIF only when `show_exif`), then the caption in IBM Plex Sans over a graphite fade. Captions are real DOM text.
|
||||
|
||||
Lucio brand (source of truth: ../LUCIO_ip): graphite #111114 ground, paper #F3F1EC text, beam #FFF3CF only on focus and a thin progress line, steel for secondary text, cinnabar only in the chop. Bricolage Grotesque display, IBM Plex Sans body, IBM Plex Mono eyebrows (uppercase, +0.08em). Fonts self-hosted woff2, nothing from Google. If a photo has nothing sharp after 400 ms, the L→U→C→I→O loader (LucioMorph.loader) appears on the right edge, vertically centred, inset ≥ 32 px. One animated element per screen. Motion: 120 ms hover, 240 ms reveals, 900 ms light-on with cubic-bezier(0.16, 1, 0.3, 1). Brand files are copied from LUCIO_ip by `scripts/sync-brand.sh`.
|
||||
|
||||
## 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 64 px cells inside each tile with a per-photo key and reorder when drawing. Hotlink: Referer check on `/t/*` in the built-in server and the Caddy/nginx examples.
|
||||
|
||||
## Config `/etc/luphoto/config.toml`
|
||||
|
||||
```toml
|
||||
[server]
|
||||
mode = "export"
|
||||
listen = "127.0.0.1:8080"
|
||||
base_url = "https://photos.luciochen.com"
|
||||
|
||||
[paths]
|
||||
albums = "/srv/luphoto/albums"
|
||||
output = "/var/lib/luphoto/site"
|
||||
cache = "/var/cache/luphoto"
|
||||
|
||||
[images]
|
||||
tile_size = 512
|
||||
overlap = 1
|
||||
format = "webp"
|
||||
quality = { top = 82, mid = 85, low = 88 }
|
||||
min_levels = 6
|
||||
seed_px = 48
|
||||
tile_names = "hashed"
|
||||
scramble_cells = false
|
||||
|
||||
[loading]
|
||||
budget_ms = 3000
|
||||
max_dpr = 2.0
|
||||
concurrency = 6
|
||||
|
||||
[build]
|
||||
watch = true
|
||||
debounce = "30s"
|
||||
workers = 2
|
||||
keep_builds = 3
|
||||
|
||||
[protection]
|
||||
block_context_menu = true
|
||||
hotlink_allow = ["photos.luciochen.com"]
|
||||
```
|
||||
|
||||
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 lives in the state folder next to the output. SIGHUP re-reads the config and rebuilds. The watcher ignores `.part`, `.tmp`, dotfiles and rsync temp names.
|
||||
|
||||
## Deployment
|
||||
|
||||
- `.deb` via nfpm: binary, `/etc/luphoto/config.toml`, systemd unit, `luphoto` user, `/srv/luphoto/albums`. Depends on `libvips-tools`. Ubuntu 22.04/24.04, Debian 12; other distros: tarball + unit file.
|
||||
- systemd: read-only albums, read-write output and cache only, NoNewPrivileges, ProtectSystem=strict.
|
||||
- Cloudflare Tunnel; cache rule `/t/*` for a month; HTML and manifests short TTL; manifests are build-named, so no purging.
|
||||
- Caddy (export): root `/var/lib/luphoto/site/current`, `/t/*` `public, max-age=31536000, immutable`, `/a/*` `max-age=60`, CSP `default-src 'self'; img-src 'self' blob: data:; frame-ancestors 'none'`, hotlink 403 on `/t/*`. Serve mode: `reverse_proxy 127.0.0.1:8080`, the built-in server sends the same headers. nginx equivalent provided.
|
||||
|
||||
## Milestones
|
||||
|
||||
| # | Deliverable |
|
||||
|---|---|
|
||||
| M1 | Processor CLI: scan, validate album.json, vips pyramids, hashed tile names, EXIF without GPS, manifests, incremental, atomic switch, cleanup |
|
||||
| M2 | Loader and canvas for a single photo, within the time budget |
|
||||
| M3 | Album viewer: swipe, keys, drag, multi-slide, captions, `#n` links, prefetch |
|
||||
| M4 | Index strips: closed/open, title reveal, lazy covers |
|
||||
| M5 | Lucio branding pass: brand files synced, loader, chop, wordmark |
|
||||
| M6 | Serve and export modes, config, systemd, `.deb`, Caddy/nginx/Cloudflare docs |
|
||||
| M7 | Hardening: hotlink rule, optional cell scrambling, memory caps, iOS Safari, accessibility |
|
||||
|
||||
## Repository rules
|
||||
|
||||
- No comments in code. No test code.
|
||||
- Development and runs happen in Docker (`scripts/dev.sh` runs commands in an Ubuntu 24.04 image with Go and libvips-tools); the Windows host has no libvips.
|
||||
@@ -0,0 +1,8 @@
|
||||
module github.com/luciochen233/luphoto
|
||||
|
||||
go 1.22
|
||||
|
||||
require (
|
||||
github.com/BurntSushi/toml v1.4.0
|
||||
github.com/rwcarlsen/goexif v0.0.0-20190401172101-9e8deecbddbd
|
||||
)
|
||||
@@ -0,0 +1,4 @@
|
||||
github.com/BurntSushi/toml v1.4.0 h1:kuoIxZQy2WRRk1pttg9asf+WVv6tWQuBNVmK8+nqPr0=
|
||||
github.com/BurntSushi/toml v1.4.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
|
||||
github.com/rwcarlsen/goexif v0.0.0-20190401172101-9e8deecbddbd h1:CmH9+J6ZSsIjUK3dcGsnCnO41eRBOnY12zwkn5qVwgc=
|
||||
github.com/rwcarlsen/goexif v0.0.0-20190401172101-9e8deecbddbd/go.mod h1:hPqNNc0+uJM6H+SuU8sEs5K5IQeKccPqeSjfgcKGgPk=
|
||||
@@ -0,0 +1,296 @@
|
||||
package album
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"runtime"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
)
|
||||
|
||||
const FileName = "album.json"
|
||||
|
||||
type Cover struct {
|
||||
Photo string `json:"photo"`
|
||||
Crop []int `json:"crop,omitempty"`
|
||||
FocusY *float64 `json:"focus_y,omitempty"`
|
||||
}
|
||||
|
||||
type Photo struct {
|
||||
File string `json:"file"`
|
||||
Title string `json:"title,omitempty"`
|
||||
Caption string `json:"caption,omitempty"`
|
||||
Alt string `json:"alt,omitempty"`
|
||||
Slides int `json:"slides,omitempty"`
|
||||
Path string `json:"-"`
|
||||
}
|
||||
|
||||
type Album struct {
|
||||
Slug string `json:"-"`
|
||||
Dir string `json:"-"`
|
||||
Unlisted int `json:"-"`
|
||||
Title string `json:"title"`
|
||||
Subtitle string `json:"subtitle,omitempty"`
|
||||
Date string `json:"date,omitempty"`
|
||||
Order *int `json:"order,omitempty"`
|
||||
Hidden bool `json:"hidden,omitempty"`
|
||||
Cover *Cover `json:"cover,omitempty"`
|
||||
CollapsedFocusY *float64 `json:"collapsed_focus_y,omitempty"`
|
||||
ShowEXIF *bool `json:"show_exif,omitempty"`
|
||||
Photos []Photo `json:"photos"`
|
||||
}
|
||||
|
||||
type Problem struct {
|
||||
Slug string
|
||||
Reason string
|
||||
}
|
||||
|
||||
func (p Problem) Error() string {
|
||||
return p.Slug + ": " + p.Reason
|
||||
}
|
||||
|
||||
type SortKey struct {
|
||||
Order *int
|
||||
Date string
|
||||
Slug string
|
||||
}
|
||||
|
||||
func (a *Album) Key() SortKey {
|
||||
return SortKey{Order: a.Order, Date: a.Date, Slug: a.Slug}
|
||||
}
|
||||
|
||||
func Before(a, b SortKey) bool {
|
||||
switch {
|
||||
case a.Order != nil && b.Order != nil:
|
||||
if *a.Order != *b.Order {
|
||||
return *a.Order < *b.Order
|
||||
}
|
||||
case a.Order != nil:
|
||||
return true
|
||||
case b.Order != nil:
|
||||
return false
|
||||
default:
|
||||
if a.Date != b.Date {
|
||||
return a.Date > b.Date
|
||||
}
|
||||
}
|
||||
return a.Slug < b.Slug
|
||||
}
|
||||
|
||||
func Sort(albums []*Album) {
|
||||
sort.SliceStable(albums, func(i, j int) bool {
|
||||
return Before(albums[i].Key(), albums[j].Key())
|
||||
})
|
||||
}
|
||||
|
||||
func Scan(root string) ([]*Album, []Problem, error) {
|
||||
entries, err := os.ReadDir(root)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("albums folder: %w", err)
|
||||
}
|
||||
var dirs []string
|
||||
for _, entry := range entries {
|
||||
name := entry.Name()
|
||||
if strings.HasPrefix(name, ".") {
|
||||
continue
|
||||
}
|
||||
info, err := os.Stat(filepath.Join(root, name))
|
||||
if err != nil || !info.IsDir() {
|
||||
continue
|
||||
}
|
||||
dirs = append(dirs, name)
|
||||
}
|
||||
albums := make([]*Album, len(dirs))
|
||||
problems := make([]error, len(dirs))
|
||||
jobs := make(chan int)
|
||||
var wg sync.WaitGroup
|
||||
for w := 0; w < min(runtime.NumCPU(), len(dirs)); w++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for i := range jobs {
|
||||
albums[i], problems[i] = Load(root, dirs[i])
|
||||
}
|
||||
}()
|
||||
}
|
||||
for i := range dirs {
|
||||
jobs <- i
|
||||
}
|
||||
close(jobs)
|
||||
wg.Wait()
|
||||
var ok []*Album
|
||||
var bad []Problem
|
||||
for i := range dirs {
|
||||
if problems[i] != nil {
|
||||
bad = append(bad, Problem{Slug: dirs[i], Reason: problems[i].Error()})
|
||||
continue
|
||||
}
|
||||
ok = append(ok, albums[i])
|
||||
}
|
||||
Sort(ok)
|
||||
return ok, bad, nil
|
||||
}
|
||||
|
||||
var datePattern = regexp.MustCompile(`^\d{4}(-(0[1-9]|1[0-2])(-(0[1-9]|[12]\d|3[01]))?)?$`)
|
||||
|
||||
func Load(root, slug string) (*Album, error) {
|
||||
dir := filepath.Join(root, slug)
|
||||
if strings.ContainsAny(slug, "/\\?#%\"<>") || strings.TrimSpace(slug) != slug || slug == "" {
|
||||
return nil, errors.New("folder name is not usable as a URL slug")
|
||||
}
|
||||
data, err := os.ReadFile(filepath.Join(dir, FileName))
|
||||
if err != nil {
|
||||
if errors.Is(err, fs.ErrNotExist) {
|
||||
return nil, errors.New("no " + FileName)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
a := &Album{}
|
||||
dec := json.NewDecoder(bytes.NewReader(data))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(a); err != nil {
|
||||
return nil, fmt.Errorf("%s: %w", FileName, err)
|
||||
}
|
||||
if _, err := dec.Token(); err != io.EOF {
|
||||
return nil, fmt.Errorf("%s: trailing data after the album object", FileName)
|
||||
}
|
||||
a.Slug = slug
|
||||
a.Dir = dir
|
||||
if err := a.validate(); err != nil {
|
||||
return nil, fmt.Errorf("%s: %w", FileName, err)
|
||||
}
|
||||
if err := a.matchFiles(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return a, nil
|
||||
}
|
||||
|
||||
func (a *Album) validate() error {
|
||||
a.Title = strings.TrimSpace(a.Title)
|
||||
if a.Title == "" {
|
||||
a.Title = a.Slug
|
||||
}
|
||||
if a.Date != "" && !datePattern.MatchString(a.Date) {
|
||||
return fmt.Errorf("date %q must be YYYY, YYYY-MM or YYYY-MM-DD", a.Date)
|
||||
}
|
||||
if a.CollapsedFocusY == nil {
|
||||
half := 0.5
|
||||
a.CollapsedFocusY = &half
|
||||
} else if *a.CollapsedFocusY < 0 || *a.CollapsedFocusY > 1 {
|
||||
return errors.New("collapsed_focus_y must be between 0 and 1")
|
||||
}
|
||||
if a.ShowEXIF == nil {
|
||||
yes := true
|
||||
a.ShowEXIF = &yes
|
||||
}
|
||||
if len(a.Photos) == 0 {
|
||||
return errors.New("photos is empty")
|
||||
}
|
||||
seen := make(map[string]bool, len(a.Photos))
|
||||
for i := range a.Photos {
|
||||
p := &a.Photos[i]
|
||||
if p.File == "" {
|
||||
return fmt.Errorf("photos[%d]: file is empty", i)
|
||||
}
|
||||
if p.File != filepath.Base(p.File) || strings.ContainsAny(p.File, "/\\") || strings.HasPrefix(p.File, ".") {
|
||||
return fmt.Errorf("photos[%d]: file %q must be a plain file name in the album folder", i, p.File)
|
||||
}
|
||||
if !IsJPEG(p.File) {
|
||||
return fmt.Errorf("photos[%d]: file %q is not a JPEG", i, p.File)
|
||||
}
|
||||
if seen[p.File] {
|
||||
return fmt.Errorf("photos[%d]: file %q is listed twice", i, p.File)
|
||||
}
|
||||
seen[p.File] = true
|
||||
if p.Slides < 0 {
|
||||
return fmt.Errorf("photos[%d]: slides must be at least 1", i)
|
||||
}
|
||||
if p.Slides == 0 {
|
||||
p.Slides = 1
|
||||
}
|
||||
p.Path = filepath.Join(a.Dir, p.File)
|
||||
}
|
||||
if a.Cover == nil {
|
||||
a.Cover = &Cover{Photo: a.Photos[0].File}
|
||||
}
|
||||
if a.Cover.Photo == "" {
|
||||
a.Cover.Photo = a.Photos[0].File
|
||||
}
|
||||
if !seen[a.Cover.Photo] {
|
||||
return fmt.Errorf("cover.photo %q is not listed in photos", a.Cover.Photo)
|
||||
}
|
||||
if a.Cover.Crop != nil && a.Cover.FocusY != nil {
|
||||
return errors.New("cover takes either crop or focus_y, not both")
|
||||
}
|
||||
if a.Cover.Crop != nil {
|
||||
c := a.Cover.Crop
|
||||
if len(c) != 4 || c[0] < 0 || c[1] < 0 || c[2] <= 0 || c[3] <= 0 {
|
||||
return errors.New("cover.crop must be [x, y, w, h] with x, y >= 0 and w, h > 0")
|
||||
}
|
||||
} else {
|
||||
if a.Cover.FocusY == nil {
|
||||
half := 0.5
|
||||
a.Cover.FocusY = &half
|
||||
}
|
||||
if *a.Cover.FocusY < 0 || *a.Cover.FocusY > 1 {
|
||||
return errors.New("cover.focus_y must be between 0 and 1")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *Album) matchFiles() error {
|
||||
entries, err := os.ReadDir(a.Dir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
present := make(map[string]fs.DirEntry, len(entries))
|
||||
for _, entry := range entries {
|
||||
present[entry.Name()] = entry
|
||||
}
|
||||
listed := make(map[string]bool, len(a.Photos))
|
||||
for _, p := range a.Photos {
|
||||
listed[p.File] = true
|
||||
entry, ok := present[p.File]
|
||||
if !ok {
|
||||
return fmt.Errorf("listed photo %q is missing", p.File)
|
||||
}
|
||||
if entry.Type()&fs.ModeSymlink != 0 || !entry.Type().IsRegular() {
|
||||
info, err := os.Stat(p.Path)
|
||||
if err != nil || !info.Mode().IsRegular() {
|
||||
return fmt.Errorf("listed photo %q is not a regular file", p.File)
|
||||
}
|
||||
}
|
||||
}
|
||||
for name := range present {
|
||||
if !listed[name] && IsJPEG(name) && !strings.HasPrefix(name, ".") {
|
||||
a.Unlisted++
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func IsJPEG(name string) bool {
|
||||
switch strings.ToLower(filepath.Ext(name)) {
|
||||
case ".jpg", ".jpeg":
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (a *Album) Photo(file string) *Photo {
|
||||
for i := range a.Photos {
|
||||
if a.Photos[i].File == file {
|
||||
return &a.Photos[i]
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,589 @@
|
||||
package build
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"math"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/luciochen233/luphoto/internal/album"
|
||||
"github.com/luciochen233/luphoto/internal/config"
|
||||
"github.com/luciochen233/luphoto/internal/fsutil"
|
||||
"github.com/luciochen233/luphoto/internal/process"
|
||||
"github.com/luciochen233/luphoto/internal/site"
|
||||
)
|
||||
|
||||
type Summary struct {
|
||||
ID string
|
||||
Albums int
|
||||
Hidden int
|
||||
Skipped int
|
||||
Carried int
|
||||
Processed int
|
||||
Cached int
|
||||
Failed int
|
||||
TilesWritten int
|
||||
BytesWritten int64
|
||||
BuildsRemoved int
|
||||
TilesRemoved int
|
||||
Duration time.Duration
|
||||
}
|
||||
|
||||
type albumPlan struct {
|
||||
album *album.Album
|
||||
coverHash string
|
||||
coverCrop [4]int
|
||||
hashes []string
|
||||
pending int
|
||||
fresh int
|
||||
reused int
|
||||
failed []string
|
||||
problem string
|
||||
manifest *site.Manifest
|
||||
carriedOut bool
|
||||
}
|
||||
|
||||
type builder struct {
|
||||
cfg *config.Config
|
||||
proc *process.Processor
|
||||
log *log.Logger
|
||||
start time.Time
|
||||
builds string
|
||||
current string
|
||||
}
|
||||
|
||||
func Run(ctx context.Context, cfg *config.Config, logger *log.Logger) (*Summary, error) {
|
||||
start := time.Now()
|
||||
if info, err := os.Stat(cfg.Paths.Albums); err != nil || !info.IsDir() {
|
||||
return nil, fmt.Errorf("albums folder %s is missing or not a folder", cfg.Paths.Albums)
|
||||
}
|
||||
proc, err := process.New(ctx, cfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
b := &builder{
|
||||
cfg: cfg,
|
||||
proc: proc,
|
||||
log: logger,
|
||||
start: start,
|
||||
builds: filepath.Join(cfg.Paths.Output, "builds"),
|
||||
current: filepath.Join(cfg.Paths.Output, "current"),
|
||||
}
|
||||
if err := os.MkdirAll(b.builds, 0o755); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
proc.CleanWork()
|
||||
logger.Printf("luphoto: libvips %s, %d workers x %d vips threads, albums %s, output %s", proc.VipsVersion(), cfg.Build.Workers, proc.Threads, cfg.Paths.Albums, cfg.Paths.Output)
|
||||
return b.run(ctx)
|
||||
}
|
||||
|
||||
func (b *builder) run(ctx context.Context) (*Summary, error) {
|
||||
sum := &Summary{}
|
||||
albums, problems, err := album.Scan(b.cfg.Paths.Albums)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
plans := make([]*albumPlan, 0, len(albums)+len(problems))
|
||||
for _, a := range albums {
|
||||
plans = append(plans, &albumPlan{album: a})
|
||||
}
|
||||
for _, p := range problems {
|
||||
plans = append(plans, &albumPlan{album: &album.Album{Slug: p.Slug}, problem: p.Reason})
|
||||
}
|
||||
|
||||
var paths []string
|
||||
seen := map[string]bool{}
|
||||
for _, plan := range plans {
|
||||
if plan.problem != "" {
|
||||
continue
|
||||
}
|
||||
for _, photo := range plan.album.Photos {
|
||||
if !seen[photo.Path] {
|
||||
seen[photo.Path] = true
|
||||
paths = append(paths, photo.Path)
|
||||
}
|
||||
}
|
||||
}
|
||||
inspectStart := time.Now()
|
||||
sources, failures := b.proc.Inspect(ctx, paths)
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
b.log.Printf("inspect: %d photos hashed in %s", len(paths), round(time.Since(inspectStart)))
|
||||
|
||||
jobs := map[string]*process.Job{}
|
||||
records := map[string]*process.Record{}
|
||||
users := map[string][]*albumPlan{}
|
||||
var order []*process.Job
|
||||
for _, plan := range plans {
|
||||
if plan.problem != "" {
|
||||
continue
|
||||
}
|
||||
a := plan.album
|
||||
for _, photo := range a.Photos {
|
||||
if err := failures[photo.Path]; err != nil {
|
||||
plan.problem = fmt.Sprintf("%s: %v", photo.File, err)
|
||||
break
|
||||
}
|
||||
}
|
||||
if plan.problem != "" {
|
||||
continue
|
||||
}
|
||||
coverSrc := sources[filepath.Join(a.Dir, a.Cover.Photo)]
|
||||
crop, err := coverCrop(a.Cover, coverSrc.Width, coverSrc.Height)
|
||||
if err != nil {
|
||||
plan.problem = err.Error()
|
||||
continue
|
||||
}
|
||||
plan.coverCrop = crop
|
||||
plan.coverHash = b.proc.CoverHash(coverSrc, crop)
|
||||
type need struct {
|
||||
hash string
|
||||
kind string
|
||||
label string
|
||||
src *process.Source
|
||||
crop *[4]int
|
||||
record *process.Record
|
||||
}
|
||||
var needs []need
|
||||
for _, photo := range a.Photos {
|
||||
src := sources[photo.Path]
|
||||
needs = append(needs, need{hash: src.Hash, kind: "photo", label: a.Slug + "/" + photo.File, src: src, record: src.Record})
|
||||
}
|
||||
coverRecord, _ := b.proc.Lookup(plan.coverHash)
|
||||
c := crop
|
||||
needs = append(needs, need{hash: plan.coverHash, kind: "cover", label: a.Slug + "/" + a.Cover.Photo, src: coverSrc, crop: &c, record: coverRecord})
|
||||
for _, n := range needs {
|
||||
plan.hashes = append(plan.hashes, n.hash)
|
||||
if n.record != nil {
|
||||
records[n.hash] = n.record
|
||||
plan.reused++
|
||||
continue
|
||||
}
|
||||
if _, ok := records[n.hash]; ok {
|
||||
plan.reused++
|
||||
continue
|
||||
}
|
||||
plan.fresh++
|
||||
plan.pending++
|
||||
users[n.hash] = append(users[n.hash], plan)
|
||||
if _, ok := jobs[n.hash]; !ok {
|
||||
job := &process.Job{Hash: n.hash, Kind: n.kind, Label: n.label, Source: n.src, Crop: n.crop}
|
||||
jobs[n.hash] = job
|
||||
order = append(order, job)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for _, plan := range plans {
|
||||
if plan.problem == "" && plan.pending == 0 {
|
||||
b.logAlbum(plan)
|
||||
}
|
||||
}
|
||||
|
||||
b.proc.Run(ctx, order, b.cfg.Build.Workers, func(res process.Result) {
|
||||
job := res.Job
|
||||
if res.Err != nil {
|
||||
sum.Failed++
|
||||
if ctx.Err() == nil {
|
||||
b.log.Printf("%s %s: failed after %s: %v", job.Kind, job.Label, round(res.Duration), res.Err)
|
||||
}
|
||||
} else {
|
||||
sum.Processed++
|
||||
records[job.Hash] = res.Record
|
||||
sum.TilesWritten += res.Record.TileCount()
|
||||
sum.BytesWritten += res.Record.TileBytes()
|
||||
b.log.Printf("%s %s: %dx%d, %d levels, %d tiles, %s in %s", job.Kind, job.Label,
|
||||
res.Record.Width, res.Record.Height, len(res.Record.Levels), res.Record.TileCount(),
|
||||
megabytes(res.Record.TileBytes()), round(res.Duration))
|
||||
}
|
||||
for _, plan := range users[job.Hash] {
|
||||
if res.Err != nil {
|
||||
plan.failed = append(plan.failed, fmt.Sprintf("%s: %v", job.Label, res.Err))
|
||||
}
|
||||
plan.pending--
|
||||
if plan.pending == 0 {
|
||||
if len(plan.failed) > 0 {
|
||||
plan.problem = strings.Join(plan.failed, "; ")
|
||||
} else {
|
||||
b.logAlbum(plan)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sum.Cached = len(records) - sum.Processed
|
||||
|
||||
id, err := newBuildID()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sum.ID = id
|
||||
previous := b.previousBuild()
|
||||
for _, plan := range plans {
|
||||
if plan.problem == "" {
|
||||
plan.manifest = b.manifest(id, plan, records)
|
||||
continue
|
||||
}
|
||||
sum.Skipped++
|
||||
if m := b.carryOver(previous, plan.album.Slug, id); m != nil {
|
||||
plan.manifest = m
|
||||
plan.carriedOut = true
|
||||
sum.Carried++
|
||||
b.log.Printf("skip album %s: %s (previous version stays live)", plan.album.Slug, plan.problem)
|
||||
} else {
|
||||
b.log.Printf("skip album %s: %s", plan.album.Slug, plan.problem)
|
||||
}
|
||||
}
|
||||
|
||||
var manifests []*site.Manifest
|
||||
for _, plan := range plans {
|
||||
if plan.manifest != nil {
|
||||
manifests = append(manifests, plan.manifest)
|
||||
}
|
||||
}
|
||||
sort.SliceStable(manifests, func(i, j int) bool {
|
||||
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})
|
||||
})
|
||||
for _, m := range manifests {
|
||||
if m.Hidden {
|
||||
sum.Hidden++
|
||||
}
|
||||
}
|
||||
sum.Albums = len(manifests)
|
||||
|
||||
if err := b.writeBuild(id, manifests); 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)
|
||||
sum.BuildsRemoved = removedBuilds
|
||||
sum.TilesRemoved = removedTiles
|
||||
if err != nil {
|
||||
b.log.Printf("cleanup: %v", err)
|
||||
}
|
||||
sum.Duration = time.Since(b.start)
|
||||
return sum, nil
|
||||
}
|
||||
|
||||
func (b *builder) logAlbum(plan *albumPlan) {
|
||||
a := plan.album
|
||||
extra := ""
|
||||
if a.Unlisted > 0 {
|
||||
extra = fmt.Sprintf(", %d unlisted JPEG(s) ignored", a.Unlisted)
|
||||
}
|
||||
if a.Hidden {
|
||||
extra += ", hidden"
|
||||
}
|
||||
b.log.Printf("album %s: %d photos + cover, %d processed, %d cached%s, ready at %s", a.Slug, len(a.Photos), plan.fresh, plan.reused, extra, round(time.Since(b.start)))
|
||||
}
|
||||
|
||||
func coverCrop(c *album.Cover, width, height int) ([4]int, error) {
|
||||
if width <= 0 || height <= 0 {
|
||||
return [4]int{}, errors.New("cover photo has no size")
|
||||
}
|
||||
if c.Crop != nil {
|
||||
x, y, w, h := c.Crop[0], c.Crop[1], c.Crop[2], c.Crop[3]
|
||||
if x+w > width || y+h > height {
|
||||
return [4]int{}, fmt.Errorf("cover.crop [%d, %d, %d, %d] exceeds the %dx%d photo", x, y, w, h, width, height)
|
||||
}
|
||||
return [4]int{x, y, w, h}, nil
|
||||
}
|
||||
w := width
|
||||
h := int(math.Round(float64(width) * 9 / 32))
|
||||
x := 0
|
||||
if h > height {
|
||||
h = height
|
||||
w = min(width, int(math.Round(float64(height)*32/9)))
|
||||
x = (width - w) / 2
|
||||
}
|
||||
focus := 0.5
|
||||
if c.FocusY != nil {
|
||||
focus = *c.FocusY
|
||||
}
|
||||
y := int(math.Round(focus*float64(height) - float64(h)/2))
|
||||
y = max(0, min(y, height-h))
|
||||
return [4]int{x, y, max(1, w), max(1, h)}, nil
|
||||
}
|
||||
|
||||
func (b *builder) tiles() site.Tiles {
|
||||
return site.Tiles{
|
||||
Format: b.cfg.Images.Format,
|
||||
TileSize: b.cfg.Images.TileSize,
|
||||
Overlap: b.cfg.Images.Overlap,
|
||||
Path: "/t/",
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
Title: a.Title,
|
||||
Subtitle: a.Subtitle,
|
||||
Date: a.Date,
|
||||
Order: a.Order,
|
||||
Hidden: a.Hidden,
|
||||
CollapsedFocusY: *a.CollapsedFocusY,
|
||||
ShowEXIF: *a.ShowEXIF,
|
||||
Tiles: b.tiles(),
|
||||
Cover: &cover,
|
||||
Photos: make([]site.Photo, len(a.Photos)),
|
||||
}
|
||||
for i, photo := range a.Photos {
|
||||
rec := records[plan.hashes[i]]
|
||||
p := site.Photo{
|
||||
Pyramid: rec.Pyramid,
|
||||
Title: photo.Title,
|
||||
Caption: photo.Caption,
|
||||
Alt: photo.Alt,
|
||||
Slides: photo.Slides,
|
||||
}
|
||||
if m.ShowEXIF {
|
||||
p.EXIF = rec.EXIF
|
||||
}
|
||||
m.Photos[i] = p
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func (b *builder) previousBuild() string {
|
||||
target, err := os.Readlink(b.current)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
id := filepath.Base(target)
|
||||
if _, err := os.Stat(filepath.Join(b.builds, id)); err != nil {
|
||||
return ""
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
func (b *builder) carryOver(previous, slug, id string) *site.Manifest {
|
||||
if previous == "" {
|
||||
return 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
|
||||
}
|
||||
m.Build = id
|
||||
return &m
|
||||
}
|
||||
|
||||
func newBuildID() (string, error) {
|
||||
var suffix [3]byte
|
||||
if _, err := rand.Read(suffix[:]); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return time.Now().UTC().Format("20060102-150405") + "-" + hex.EncodeToString(suffix[:]), nil
|
||||
}
|
||||
|
||||
func (b *builder) writeBuild(id string, manifests []*site.Manifest) error {
|
||||
stage := fsutil.TempName(filepath.Join(b.builds, id))
|
||||
if err := os.MkdirAll(filepath.Join(stage, "a"), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
ok := false
|
||||
defer func() {
|
||||
if !ok {
|
||||
_ = os.RemoveAll(stage)
|
||||
}
|
||||
}()
|
||||
if err := os.Symlink(filepath.Join("..", "..", "t"), filepath.Join(stage, "t")); err != nil {
|
||||
return fmt.Errorf("link tiles: %w", err)
|
||||
}
|
||||
|
||||
index := &site.Index{Build: id, Tiles: b.tiles(), Albums: []site.IndexAlbum{}}
|
||||
for _, m := range manifests {
|
||||
if m.Hidden {
|
||||
continue
|
||||
}
|
||||
index.Albums = append(index.Albums, site.IndexAlbum{
|
||||
Slug: m.Slug,
|
||||
Title: m.Title,
|
||||
Subtitle: m.Subtitle,
|
||||
Date: m.Date,
|
||||
CollapsedFocusY: m.CollapsedFocusY,
|
||||
Photos: len(m.Photos),
|
||||
Manifest: site.ManifestURL(id, m.Slug),
|
||||
Cover: m.Cover,
|
||||
})
|
||||
}
|
||||
|
||||
errs := make([]error, len(manifests)+1)
|
||||
var wg sync.WaitGroup
|
||||
limit := make(chan struct{}, runtime.NumCPU())
|
||||
for i, m := range manifests {
|
||||
wg.Add(1)
|
||||
go func(i int, m *site.Manifest) {
|
||||
defer wg.Done()
|
||||
limit <- struct{}{}
|
||||
defer func() { <-limit }()
|
||||
dir := filepath.Join(stage, "a", m.Slug)
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
errs[i] = err
|
||||
return
|
||||
}
|
||||
if err := fsutil.WriteJSONAtomic(filepath.Join(dir, site.ManifestName(id)), m); err != nil {
|
||||
errs[i] = err
|
||||
return
|
||||
}
|
||||
errs[i] = fsutil.WriteAtomic(filepath.Join(dir, "index.html"), 0o644, func(w io.Writer) error {
|
||||
return site.RenderAlbum(w, m)
|
||||
})
|
||||
}(i, m)
|
||||
}
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
if err := fsutil.WriteJSONAtomic(filepath.Join(stage, site.IndexName(id)), index); err != nil {
|
||||
errs[len(manifests)] = err
|
||||
return
|
||||
}
|
||||
errs[len(manifests)] = fsutil.WriteAtomic(filepath.Join(stage, "index.html"), 0o644, func(w io.Writer) error {
|
||||
return site.RenderIndex(w, index)
|
||||
})
|
||||
}()
|
||||
wg.Wait()
|
||||
if err := errors.Join(errs...); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.Rename(stage, filepath.Join(b.builds, id)); err != nil {
|
||||
return err
|
||||
}
|
||||
ok = true
|
||||
return nil
|
||||
}
|
||||
|
||||
func (b *builder) cleanup(id string) (int, int, error) {
|
||||
entries, err := os.ReadDir(b.builds)
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
var names []string
|
||||
for _, entry := range entries {
|
||||
name := entry.Name()
|
||||
if strings.HasPrefix(name, ".") {
|
||||
if strings.Contains(name, fsutil.TempMarker) {
|
||||
_ = os.RemoveAll(filepath.Join(b.builds, name))
|
||||
}
|
||||
continue
|
||||
}
|
||||
if entry.IsDir() {
|
||||
names = append(names, name)
|
||||
}
|
||||
}
|
||||
sort.Sort(sort.Reverse(sort.StringSlice(names)))
|
||||
live := b.previousBuild()
|
||||
var kept []string
|
||||
removed := 0
|
||||
var errs []error
|
||||
for i, name := range names {
|
||||
if i < b.cfg.Build.KeepBuilds || name == id || name == live {
|
||||
kept = append(kept, name)
|
||||
continue
|
||||
}
|
||||
if err := os.RemoveAll(filepath.Join(b.builds, name)); err != nil {
|
||||
errs = append(errs, err)
|
||||
kept = append(kept, name)
|
||||
continue
|
||||
}
|
||||
removed++
|
||||
}
|
||||
refs := map[string]bool{}
|
||||
for _, name := range kept {
|
||||
if err := collectRefs(filepath.Join(b.builds, name), name, refs); err != nil {
|
||||
errs = append(errs, fmt.Errorf("build %s unreadable, keeping all tiles: %w", name, err))
|
||||
return removed, 0, errors.Join(errs...)
|
||||
}
|
||||
}
|
||||
tilesRemoved, err := b.proc.ForgetUnreferenced(refs)
|
||||
if err != nil {
|
||||
errs = append(errs, err)
|
||||
}
|
||||
return removed, tilesRemoved, errors.Join(errs...)
|
||||
}
|
||||
|
||||
type pyramidRef struct {
|
||||
Hash string `json:"hash"`
|
||||
}
|
||||
|
||||
func collectRefs(dir, id string, refs map[string]bool) error {
|
||||
var index struct {
|
||||
Albums []struct {
|
||||
Cover *pyramidRef `json:"cover"`
|
||||
} `json:"albums"`
|
||||
}
|
||||
if err := fsutil.ReadJSON(filepath.Join(dir, site.IndexName(id)), &index); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, a := range index.Albums {
|
||||
if a.Cover != nil {
|
||||
refs[a.Cover.Hash] = true
|
||||
}
|
||||
}
|
||||
albums, err := os.ReadDir(filepath.Join(dir, "a"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, entry := range albums {
|
||||
if !entry.IsDir() {
|
||||
continue
|
||||
}
|
||||
var m struct {
|
||||
Cover *pyramidRef `json:"cover"`
|
||||
Photos []pyramidRef `json:"photos"`
|
||||
}
|
||||
if err := fsutil.ReadJSON(filepath.Join(dir, "a", entry.Name(), site.ManifestName(id)), &m); err != nil {
|
||||
return err
|
||||
}
|
||||
if m.Cover != nil {
|
||||
refs[m.Cover.Hash] = true
|
||||
}
|
||||
for _, p := range m.Photos {
|
||||
refs[p.Hash] = true
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func round(d time.Duration) time.Duration {
|
||||
switch {
|
||||
case d >= 10*time.Second:
|
||||
return d.Round(100 * time.Millisecond)
|
||||
case d >= time.Second:
|
||||
return d.Round(10 * time.Millisecond)
|
||||
default:
|
||||
return d.Round(time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
func megabytes(n int64) string {
|
||||
return fmt.Sprintf("%.1f MB", float64(n)/(1<<20))
|
||||
}
|
||||
|
||||
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))
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/BurntSushi/toml"
|
||||
)
|
||||
|
||||
const DefaultPath = "/etc/luphoto/config.toml"
|
||||
|
||||
type Config struct {
|
||||
Server Server `toml:"server"`
|
||||
Paths Paths `toml:"paths"`
|
||||
Images Images `toml:"images"`
|
||||
Loading Loading `toml:"loading"`
|
||||
Build Build `toml:"build"`
|
||||
Protection Protection `toml:"protection"`
|
||||
|
||||
Source string `toml:"-"`
|
||||
State string `toml:"-"`
|
||||
}
|
||||
|
||||
type Server struct {
|
||||
Mode string `toml:"mode"`
|
||||
Listen string `toml:"listen"`
|
||||
BaseURL string `toml:"base_url"`
|
||||
}
|
||||
|
||||
type Paths struct {
|
||||
Albums string `toml:"albums"`
|
||||
Output string `toml:"output"`
|
||||
Cache string `toml:"cache"`
|
||||
}
|
||||
|
||||
type Quality struct {
|
||||
Top int `toml:"top"`
|
||||
Mid int `toml:"mid"`
|
||||
Low int `toml:"low"`
|
||||
}
|
||||
|
||||
type Images struct {
|
||||
TileSize int `toml:"tile_size"`
|
||||
Overlap int `toml:"overlap"`
|
||||
Format string `toml:"format"`
|
||||
Quality Quality `toml:"quality"`
|
||||
MinLevels int `toml:"min_levels"`
|
||||
SeedPx int `toml:"seed_px"`
|
||||
TileNames string `toml:"tile_names"`
|
||||
ScrambleCells bool `toml:"scramble_cells"`
|
||||
}
|
||||
|
||||
type Loading struct {
|
||||
BudgetMS int `toml:"budget_ms"`
|
||||
MaxDPR float64 `toml:"max_dpr"`
|
||||
Concurrency int `toml:"concurrency"`
|
||||
}
|
||||
|
||||
type Build struct {
|
||||
Watch bool `toml:"watch"`
|
||||
Debounce Duration `toml:"debounce"`
|
||||
Workers int `toml:"workers"`
|
||||
KeepBuilds int `toml:"keep_builds"`
|
||||
}
|
||||
|
||||
type Protection struct {
|
||||
BlockContextMenu bool `toml:"block_context_menu"`
|
||||
HotlinkAllow []string `toml:"hotlink_allow"`
|
||||
}
|
||||
|
||||
type Duration struct {
|
||||
time.Duration
|
||||
}
|
||||
|
||||
func (d *Duration) UnmarshalText(text []byte) error {
|
||||
parsed, err := time.ParseDuration(strings.TrimSpace(string(text)))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d.Duration = parsed
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d Duration) MarshalText() ([]byte, error) {
|
||||
return []byte(d.Duration.String()), nil
|
||||
}
|
||||
|
||||
func Defaults() Config {
|
||||
return Config{
|
||||
Server: Server{
|
||||
Mode: "export",
|
||||
Listen: "127.0.0.1:8080",
|
||||
BaseURL: "https://photos.luciochen.com",
|
||||
},
|
||||
Paths: Paths{
|
||||
Albums: "/srv/luphoto/albums",
|
||||
},
|
||||
Images: Images{
|
||||
TileSize: 512,
|
||||
Overlap: 1,
|
||||
Format: "webp",
|
||||
Quality: Quality{Top: 82, Mid: 85, Low: 88},
|
||||
MinLevels: 6,
|
||||
SeedPx: 48,
|
||||
TileNames: "hashed",
|
||||
},
|
||||
Loading: Loading{
|
||||
BudgetMS: 3000,
|
||||
MaxDPR: 2.0,
|
||||
Concurrency: 6,
|
||||
},
|
||||
Build: Build{
|
||||
Watch: true,
|
||||
Debounce: Duration{30 * time.Second},
|
||||
Workers: 2,
|
||||
KeepBuilds: 3,
|
||||
},
|
||||
Protection: Protection{
|
||||
BlockContextMenu: true,
|
||||
HotlinkAllow: []string{"photos.luciochen.com"},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func Load(path string) (*Config, error) {
|
||||
cfg := Defaults()
|
||||
data, err := os.ReadFile(path)
|
||||
switch {
|
||||
case err == nil:
|
||||
meta, decodeErr := toml.Decode(string(data), &cfg)
|
||||
if decodeErr != nil {
|
||||
return nil, fmt.Errorf("config %s: %w", path, decodeErr)
|
||||
}
|
||||
if unknown := meta.Undecoded(); len(unknown) > 0 {
|
||||
keys := make([]string, len(unknown))
|
||||
for i, key := range unknown {
|
||||
keys[i] = key.String()
|
||||
}
|
||||
sort.Strings(keys)
|
||||
return nil, fmt.Errorf("config %s: unknown keys: %s", path, strings.Join(keys, ", "))
|
||||
}
|
||||
cfg.Source = path
|
||||
case errors.Is(err, fs.ErrNotExist):
|
||||
cfg.Source = ""
|
||||
default:
|
||||
return nil, fmt.Errorf("config %s: %w", path, err)
|
||||
}
|
||||
if err := cfg.resolvePaths(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := cfg.Validate(); err != nil {
|
||||
return nil, fmt.Errorf("config %s: %w", path, err)
|
||||
}
|
||||
return &cfg, nil
|
||||
}
|
||||
|
||||
func (c *Config) resolvePaths() error {
|
||||
dataRoot, cacheRoot, err := defaultRoots()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if c.Paths.Output == "" {
|
||||
c.Paths.Output = filepath.Join(dataRoot, "site")
|
||||
}
|
||||
if c.Paths.Cache == "" {
|
||||
c.Paths.Cache = cacheRoot
|
||||
}
|
||||
for _, p := range []*string{&c.Paths.Albums, &c.Paths.Output, &c.Paths.Cache} {
|
||||
abs, err := filepath.Abs(*p)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*p = abs
|
||||
}
|
||||
c.State = filepath.Join(filepath.Dir(c.Paths.Output), "state")
|
||||
return nil
|
||||
}
|
||||
|
||||
func defaultRoots() (string, string, error) {
|
||||
if os.Geteuid() == 0 || os.Getenv("INVOCATION_ID") != "" {
|
||||
return "/var/lib/luphoto", "/var/cache/luphoto", nil
|
||||
}
|
||||
dataHome := os.Getenv("XDG_DATA_HOME")
|
||||
if dataHome == "" {
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return "", "", fmt.Errorf("no data directory: %w", err)
|
||||
}
|
||||
dataHome = filepath.Join(home, ".local", "share")
|
||||
}
|
||||
cacheHome, err := os.UserCacheDir()
|
||||
if err != nil {
|
||||
return "", "", fmt.Errorf("no cache directory: %w", err)
|
||||
}
|
||||
return filepath.Join(dataHome, "luphoto"), filepath.Join(cacheHome, "luphoto"), nil
|
||||
}
|
||||
|
||||
func (c *Config) Validate() error {
|
||||
var problems []string
|
||||
add := func(format string, args ...any) {
|
||||
problems = append(problems, fmt.Sprintf(format, args...))
|
||||
}
|
||||
switch c.Server.Mode {
|
||||
case "serve", "export":
|
||||
default:
|
||||
add("server.mode must be \"serve\" or \"export\", got %q", c.Server.Mode)
|
||||
}
|
||||
if c.Server.Listen == "" {
|
||||
add("server.listen is empty")
|
||||
}
|
||||
if c.Server.BaseURL != "" && !strings.HasPrefix(c.Server.BaseURL, "http://") && !strings.HasPrefix(c.Server.BaseURL, "https://") {
|
||||
add("server.base_url must start with http:// or https://")
|
||||
}
|
||||
if c.Paths.Albums == "" {
|
||||
add("paths.albums is empty")
|
||||
}
|
||||
if c.Paths.Output == c.Paths.Cache {
|
||||
add("paths.output and paths.cache must differ")
|
||||
}
|
||||
if within(c.Paths.Output, c.Paths.Albums) || within(c.Paths.Albums, c.Paths.Output) {
|
||||
add("paths.output and paths.albums must not contain each other")
|
||||
}
|
||||
img := c.Images
|
||||
if img.TileSize < 64 || img.TileSize > 8192 {
|
||||
add("images.tile_size must be between 64 and 8192")
|
||||
}
|
||||
if img.Overlap < 0 || img.Overlap*2 >= img.TileSize {
|
||||
add("images.overlap must be at least 0 and below half of tile_size")
|
||||
}
|
||||
switch img.Format {
|
||||
case "webp", "avif":
|
||||
default:
|
||||
add("images.format must be \"webp\" or \"avif\", got %q", img.Format)
|
||||
}
|
||||
for _, q := range []struct {
|
||||
name string
|
||||
value int
|
||||
}{{"top", img.Quality.Top}, {"mid", img.Quality.Mid}, {"low", img.Quality.Low}} {
|
||||
if q.value < 1 || q.value > 100 {
|
||||
add("images.quality.%s must be between 1 and 100", q.name)
|
||||
}
|
||||
}
|
||||
if img.MinLevels < 1 || img.MinLevels > 24 {
|
||||
add("images.min_levels must be between 1 and 24")
|
||||
}
|
||||
if img.SeedPx < 8 || img.SeedPx > 512 {
|
||||
add("images.seed_px must be between 8 and 512")
|
||||
}
|
||||
if img.TileNames != "hashed" {
|
||||
add("images.tile_names must be \"hashed\"")
|
||||
}
|
||||
if c.Loading.BudgetMS < 100 {
|
||||
add("loading.budget_ms must be at least 100")
|
||||
}
|
||||
if c.Loading.MaxDPR < 1 || c.Loading.MaxDPR > 4 {
|
||||
add("loading.max_dpr must be between 1 and 4")
|
||||
}
|
||||
if c.Loading.Concurrency < 1 || c.Loading.Concurrency > 64 {
|
||||
add("loading.concurrency must be between 1 and 64")
|
||||
}
|
||||
if c.Build.Debounce.Duration < 0 {
|
||||
add("build.debounce must not be negative")
|
||||
}
|
||||
if c.Build.Workers < 1 || c.Build.Workers > 256 {
|
||||
add("build.workers must be between 1 and 256")
|
||||
}
|
||||
if c.Build.KeepBuilds < 1 {
|
||||
add("build.keep_builds must be at least 1")
|
||||
}
|
||||
for _, host := range c.Protection.HotlinkAllow {
|
||||
if host == "" || strings.ContainsAny(host, "/ ") {
|
||||
add("protection.hotlink_allow entry %q is not a host name", host)
|
||||
}
|
||||
}
|
||||
if len(problems) > 0 {
|
||||
return errors.New(strings.Join(problems, "; "))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func within(parent, child string) bool {
|
||||
rel, err := filepath.Rel(parent, child)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return rel == "." || (rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)))
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package fsutil
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
const TempMarker = ".tmp-"
|
||||
|
||||
func TempName(path string) string {
|
||||
var suffix [6]byte
|
||||
_, _ = rand.Read(suffix[:])
|
||||
return filepath.Join(filepath.Dir(path), "."+filepath.Base(path)+TempMarker+hex.EncodeToString(suffix[:]))
|
||||
}
|
||||
|
||||
func WriteAtomic(path string, perm os.FileMode, write func(io.Writer) error) error {
|
||||
tmp := TempName(path)
|
||||
f, err := os.OpenFile(tmp, os.O_WRONLY|os.O_CREATE|os.O_EXCL, perm)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
buffered := bufio.NewWriterSize(f, 64<<10)
|
||||
err = write(buffered)
|
||||
if err == nil {
|
||||
err = buffered.Flush()
|
||||
}
|
||||
if err == nil {
|
||||
err = f.Sync()
|
||||
}
|
||||
if closeErr := f.Close(); err == nil {
|
||||
err = closeErr
|
||||
}
|
||||
if err == nil {
|
||||
err = os.Rename(tmp, path)
|
||||
}
|
||||
if err != nil {
|
||||
_ = os.Remove(tmp)
|
||||
return fmt.Errorf("write %s: %w", path, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func WriteFileAtomic(path string, data []byte, perm os.FileMode) error {
|
||||
return WriteAtomic(path, perm, func(w io.Writer) error {
|
||||
_, err := w.Write(data)
|
||||
return err
|
||||
})
|
||||
}
|
||||
|
||||
func WriteJSONAtomic(path string, value any) error {
|
||||
return WriteAtomic(path, 0o644, func(w io.Writer) error {
|
||||
enc := json.NewEncoder(w)
|
||||
enc.SetEscapeHTML(false)
|
||||
return enc.Encode(value)
|
||||
})
|
||||
}
|
||||
|
||||
func ReadJSON(path string, value any) error {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
return json.NewDecoder(bufio.NewReaderSize(f, 64<<10)).Decode(value)
|
||||
}
|
||||
|
||||
func SymlinkAtomic(target, link string) error {
|
||||
tmp := TempName(link)
|
||||
if err := os.Symlink(target, tmp); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.Rename(tmp, link); err != nil {
|
||||
_ = os.Remove(tmp)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
package process
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"image"
|
||||
_ "image/jpeg"
|
||||
"io"
|
||||
"math"
|
||||
"math/big"
|
||||
"os"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/rwcarlsen/goexif/exif"
|
||||
)
|
||||
|
||||
type EXIF struct {
|
||||
Make string `json:"make,omitempty"`
|
||||
Model string `json:"model,omitempty"`
|
||||
Lens string `json:"lens,omitempty"`
|
||||
FocalLength float64 `json:"focal_length,omitempty"`
|
||||
FNumber float64 `json:"f_number,omitempty"`
|
||||
Exposure string `json:"exposure,omitempty"`
|
||||
ISO int `json:"iso,omitempty"`
|
||||
Date string `json:"date,omitempty"`
|
||||
}
|
||||
|
||||
type Source struct {
|
||||
Path string
|
||||
Hash string
|
||||
Size int64
|
||||
Width int
|
||||
Height int
|
||||
EXIF *EXIF
|
||||
Record *Record
|
||||
digest []byte
|
||||
}
|
||||
|
||||
var copyBuffers = sync.Pool{New: func() any {
|
||||
buf := make([]byte, 1<<20)
|
||||
return &buf
|
||||
}}
|
||||
|
||||
func (p *Processor) Inspect(ctx context.Context, paths []string) (map[string]*Source, map[string]error) {
|
||||
sources := make(map[string]*Source, len(paths))
|
||||
failures := make(map[string]error)
|
||||
var mu sync.Mutex
|
||||
jobs := make(chan string)
|
||||
var wg sync.WaitGroup
|
||||
for w := 0; w < min(runtime.NumCPU(), len(paths)); w++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for path := range jobs {
|
||||
src, err := p.inspect(ctx, path)
|
||||
mu.Lock()
|
||||
if err != nil {
|
||||
failures[path] = err
|
||||
} else {
|
||||
sources[path] = src
|
||||
}
|
||||
mu.Unlock()
|
||||
}
|
||||
}()
|
||||
}
|
||||
for _, path := range paths {
|
||||
jobs <- path
|
||||
}
|
||||
close(jobs)
|
||||
wg.Wait()
|
||||
return sources, failures
|
||||
}
|
||||
|
||||
func (p *Processor) inspect(ctx context.Context, path string) (*Source, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer f.Close()
|
||||
h := sha256.New()
|
||||
buf := copyBuffers.Get().(*[]byte)
|
||||
size, err := io.CopyBuffer(h, f, *buf)
|
||||
copyBuffers.Put(buf)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read %s: %w", path, err)
|
||||
}
|
||||
digest, err := h.(encoding.BinaryMarshaler).MarshalBinary()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
src := &Source{Path: path, Size: size, digest: digest}
|
||||
src.Hash = p.hashWith(digest, "photo")
|
||||
if rec, ok := p.Lookup(src.Hash); ok {
|
||||
src.Record = rec
|
||||
src.Width, src.Height = rec.Width, rec.Height
|
||||
src.EXIF = rec.EXIF
|
||||
return src, nil
|
||||
}
|
||||
if _, err := f.Seek(0, io.SeekStart); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cfg, _, err := image.DecodeConfig(f)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s: not a readable JPEG: %w", path, err)
|
||||
}
|
||||
if _, err := f.Seek(0, io.SeekStart); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
meta, orientation := readEXIF(f)
|
||||
src.EXIF = meta
|
||||
src.Width, src.Height = cfg.Width, cfg.Height
|
||||
if orientation >= 5 && orientation <= 8 {
|
||||
src.Width, src.Height = cfg.Height, cfg.Width
|
||||
}
|
||||
return src, nil
|
||||
}
|
||||
|
||||
func (p *Processor) hashWith(digest []byte, extra string) string {
|
||||
h := sha256.New()
|
||||
if err := h.(encoding.BinaryUnmarshaler).UnmarshalBinary(digest); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
io.WriteString(h, "\x00"+p.fingerprint+"\x00"+extra)
|
||||
return hex.EncodeToString(h.Sum(nil))[:16]
|
||||
}
|
||||
|
||||
func (p *Processor) CoverHash(src *Source, crop [4]int) string {
|
||||
return p.hashWith(src.digest, fmt.Sprintf("cover:%d,%d,%d,%d", crop[0], crop[1], crop[2], crop[3]))
|
||||
}
|
||||
|
||||
func readEXIF(r io.Reader) (meta *EXIF, orientation int) {
|
||||
defer func() {
|
||||
if recover() != nil {
|
||||
meta, orientation = nil, 1
|
||||
}
|
||||
}()
|
||||
x, err := exif.Decode(r)
|
||||
if err != nil || x == nil {
|
||||
return nil, 1
|
||||
}
|
||||
orientation = 1
|
||||
if tag, err := x.Get(exif.Orientation); err == nil {
|
||||
if v, err := tag.Int(0); err == nil {
|
||||
orientation = v
|
||||
}
|
||||
}
|
||||
e := &EXIF{
|
||||
Make: exifString(x, exif.Make),
|
||||
Model: exifString(x, exif.Model),
|
||||
Lens: exifString(x, exif.LensModel),
|
||||
}
|
||||
if r, ok := exifRat(x, exif.FocalLength); ok {
|
||||
e.FocalLength = round(ratFloat(r), 1)
|
||||
}
|
||||
if r, ok := exifRat(x, exif.FNumber); ok {
|
||||
e.FNumber = round(ratFloat(r), 1)
|
||||
}
|
||||
if r, ok := exifRat(x, exif.ExposureTime); ok {
|
||||
e.Exposure = formatExposure(r)
|
||||
}
|
||||
if tag, err := x.Get(exif.ISOSpeedRatings); err == nil {
|
||||
if v, err := tag.Int(0); err == nil && v > 0 {
|
||||
e.ISO = v
|
||||
}
|
||||
}
|
||||
for _, field := range []exif.FieldName{exif.DateTimeOriginal, exif.DateTimeDigitized, exif.DateTime} {
|
||||
if raw := exifString(x, field); raw != "" {
|
||||
if t, err := time.Parse("2006:01:02 15:04:05", raw); err == nil {
|
||||
e.Date = t.Format("2006-01-02T15:04:05")
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if *e == (EXIF{}) {
|
||||
return nil, orientation
|
||||
}
|
||||
return e, orientation
|
||||
}
|
||||
|
||||
func exifString(x *exif.Exif, field exif.FieldName) string {
|
||||
tag, err := x.Get(field)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
s, err := tag.StringVal()
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(strings.TrimRight(s, "\x00"))
|
||||
}
|
||||
|
||||
func exifRat(x *exif.Exif, field exif.FieldName) (*big.Rat, bool) {
|
||||
tag, err := x.Get(field)
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
r, err := tag.Rat(0)
|
||||
if err != nil || r == nil || r.Sign() <= 0 {
|
||||
return nil, false
|
||||
}
|
||||
return r, true
|
||||
}
|
||||
|
||||
func ratFloat(r *big.Rat) float64 {
|
||||
f, _ := r.Float64()
|
||||
return f
|
||||
}
|
||||
|
||||
func round(v float64, digits int) float64 {
|
||||
scale := math.Pow(10, float64(digits))
|
||||
return math.Round(v*scale) / scale
|
||||
}
|
||||
|
||||
func formatExposure(r *big.Rat) string {
|
||||
seconds := ratFloat(r)
|
||||
if seconds >= 0.3 {
|
||||
return strconv.FormatFloat(round(seconds, 1), 'f', -1, 64)
|
||||
}
|
||||
return "1/" + strconv.Itoa(int(math.Round(1/seconds)))
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
package process
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/luciochen233/luphoto/internal/config"
|
||||
"github.com/luciochen233/luphoto/internal/fsutil"
|
||||
)
|
||||
|
||||
const processorVersion = "luphoto-pyramid-1"
|
||||
|
||||
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"`
|
||||
}
|
||||
|
||||
type Pyramid struct {
|
||||
Hash string `json:"hash"`
|
||||
Width int `json:"width"`
|
||||
Height int `json:"height"`
|
||||
Levels []Level `json:"levels"`
|
||||
Seed string `json:"seed"`
|
||||
}
|
||||
|
||||
type Record struct {
|
||||
Pyramid
|
||||
Kind string `json:"kind"`
|
||||
Format string `json:"format"`
|
||||
TileSize int `json:"tile_size"`
|
||||
Overlap int `json:"overlap"`
|
||||
Crop []int `json:"crop,omitempty"`
|
||||
EXIF *EXIF `json:"exif,omitempty"`
|
||||
Processed time.Time `json:"processed"`
|
||||
}
|
||||
|
||||
func (r *Record) TileBytes() int64 {
|
||||
var total int64
|
||||
for _, level := range r.Levels {
|
||||
for _, b := range level.Bytes {
|
||||
total += b
|
||||
}
|
||||
}
|
||||
return total
|
||||
}
|
||||
|
||||
func (r *Record) TileCount() int {
|
||||
n := 0
|
||||
for _, level := range r.Levels {
|
||||
n += len(level.Tiles)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
type Processor struct {
|
||||
images config.Images
|
||||
vips *Vips
|
||||
key []byte
|
||||
fingerprint string
|
||||
TilesDir string
|
||||
StateDir string
|
||||
recordsDir string
|
||||
workDir string
|
||||
Threads int
|
||||
}
|
||||
|
||||
func New(ctx context.Context, cfg *config.Config) (*Processor, error) {
|
||||
tiles := filepath.Join(cfg.Paths.Output, "t")
|
||||
records := filepath.Join(cfg.State, "pyramids")
|
||||
work := filepath.Join(cfg.Paths.Cache, "work")
|
||||
for _, dir := range []string{cfg.Paths.Output, tiles, cfg.State, records, cfg.Paths.Cache, work} {
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
key, err := loadOrCreateKey(filepath.Join(cfg.State, "site.key"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
threads := runtime.NumCPU() / cfg.Build.Workers
|
||||
if threads < 1 {
|
||||
threads = 1
|
||||
}
|
||||
env := os.Environ()
|
||||
if os.Getenv("VIPS_CONCURRENCY") == "" {
|
||||
env = append(env, "VIPS_CONCURRENCY="+strconv.Itoa(threads))
|
||||
}
|
||||
env = append(env, "TMPDIR="+work)
|
||||
v, err := DetectVips(ctx, env)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
img := cfg.Images
|
||||
keySum := sha256.Sum256(key)
|
||||
fingerprint := strings.Join([]string{
|
||||
processorVersion,
|
||||
"tile=" + strconv.Itoa(img.TileSize),
|
||||
"overlap=" + strconv.Itoa(img.Overlap),
|
||||
"format=" + img.Format,
|
||||
fmt.Sprintf("q=%d,%d,%d", img.Quality.Top, img.Quality.Mid, img.Quality.Low),
|
||||
"min_levels=" + strconv.Itoa(img.MinLevels),
|
||||
"seed=" + strconv.Itoa(img.SeedPx),
|
||||
"names=" + img.TileNames,
|
||||
"scramble=" + strconv.FormatBool(img.ScrambleCells),
|
||||
"key=" + hex.EncodeToString(keySum[:4]),
|
||||
}, "|")
|
||||
return &Processor{
|
||||
images: img,
|
||||
vips: v,
|
||||
key: key,
|
||||
fingerprint: fingerprint,
|
||||
TilesDir: tiles,
|
||||
StateDir: cfg.State,
|
||||
recordsDir: records,
|
||||
workDir: work,
|
||||
Threads: threads,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (p *Processor) VipsVersion() string {
|
||||
return p.vips.Version
|
||||
}
|
||||
|
||||
func loadOrCreateKey(path string) ([]byte, error) {
|
||||
key, err := os.ReadFile(path)
|
||||
if err == nil {
|
||||
if len(key) != 32 {
|
||||
return nil, fmt.Errorf("site key %s: expected 32 bytes, found %d", path, len(key))
|
||||
}
|
||||
return key, nil
|
||||
}
|
||||
if !errors.Is(err, fs.ErrNotExist) {
|
||||
return nil, err
|
||||
}
|
||||
key = make([]byte, 32)
|
||||
if _, err := rand.Read(key); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := fsutil.WriteFileAtomic(path, key, 0o600); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return key, nil
|
||||
}
|
||||
|
||||
func (p *Processor) recordPath(hash string) string {
|
||||
return filepath.Join(p.recordsDir, hash+".json")
|
||||
}
|
||||
|
||||
func (p *Processor) Lookup(hash string) (*Record, bool) {
|
||||
var rec Record
|
||||
if err := fsutil.ReadJSON(p.recordPath(hash), &rec); err != nil || rec.Hash != hash {
|
||||
return nil, false
|
||||
}
|
||||
info, err := os.Stat(filepath.Join(p.TilesDir, hash))
|
||||
if err != nil || !info.IsDir() {
|
||||
return nil, false
|
||||
}
|
||||
return &rec, true
|
||||
}
|
||||
|
||||
type Job struct {
|
||||
Hash string
|
||||
Kind string
|
||||
Label string
|
||||
Source *Source
|
||||
Crop *[4]int
|
||||
}
|
||||
|
||||
func (j *Job) pixels() int {
|
||||
if j.Crop != nil {
|
||||
return j.Crop[2] * j.Crop[3]
|
||||
}
|
||||
return j.Source.Width * j.Source.Height
|
||||
}
|
||||
|
||||
type Result struct {
|
||||
Job *Job
|
||||
Record *Record
|
||||
Err error
|
||||
Duration time.Duration
|
||||
}
|
||||
|
||||
func (p *Processor) Run(ctx context.Context, jobs []*Job, workers int, done func(Result)) {
|
||||
ordered := append([]*Job(nil), jobs...)
|
||||
sort.SliceStable(ordered, func(i, j int) bool { return ordered[i].pixels() > ordered[j].pixels() })
|
||||
queue := make(chan *Job)
|
||||
var wg sync.WaitGroup
|
||||
var mu sync.Mutex
|
||||
for w := 0; w < min(workers, len(ordered)); w++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for job := range queue {
|
||||
start := time.Now()
|
||||
rec, err := p.process(ctx, job)
|
||||
res := Result{Job: job, Record: rec, Err: err, Duration: time.Since(start)}
|
||||
mu.Lock()
|
||||
done(res)
|
||||
mu.Unlock()
|
||||
}
|
||||
}()
|
||||
}
|
||||
for _, job := range ordered {
|
||||
queue <- job
|
||||
}
|
||||
close(queue)
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
func (p *Processor) ForgetUnreferenced(keep map[string]bool) (int, error) {
|
||||
entries, err := os.ReadDir(p.TilesDir)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
removed := 0
|
||||
var firstErr error
|
||||
for _, entry := range entries {
|
||||
name := entry.Name()
|
||||
if strings.HasPrefix(name, ".") {
|
||||
if strings.Contains(name, fsutil.TempMarker) {
|
||||
_ = os.RemoveAll(filepath.Join(p.TilesDir, name))
|
||||
}
|
||||
continue
|
||||
}
|
||||
if keep[name] {
|
||||
continue
|
||||
}
|
||||
if err := os.Remove(p.recordPath(name)); err != nil && !errors.Is(err, fs.ErrNotExist) && firstErr == nil {
|
||||
firstErr = err
|
||||
}
|
||||
if err := os.RemoveAll(filepath.Join(p.TilesDir, name)); err != nil {
|
||||
if firstErr == nil {
|
||||
firstErr = err
|
||||
}
|
||||
continue
|
||||
}
|
||||
removed++
|
||||
}
|
||||
records, err := os.ReadDir(p.recordsDir)
|
||||
if err == nil {
|
||||
for _, entry := range records {
|
||||
hash := strings.TrimSuffix(entry.Name(), ".json")
|
||||
if !keep[hash] {
|
||||
_ = os.Remove(filepath.Join(p.recordsDir, entry.Name()))
|
||||
}
|
||||
}
|
||||
}
|
||||
return removed, firstErr
|
||||
}
|
||||
|
||||
func (p *Processor) CleanWork() {
|
||||
entries, err := os.ReadDir(p.workDir)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for _, entry := range entries {
|
||||
_ = os.RemoveAll(filepath.Join(p.workDir, entry.Name()))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,354 @@
|
||||
package process
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/luciochen233/luphoto/internal/fsutil"
|
||||
)
|
||||
|
||||
const minLongEdge = 100
|
||||
|
||||
func LevelSizes(width, height, minLevels 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})
|
||||
}
|
||||
for i, j := 0, len(sizes)-1; i < j; i, j = i+1, j-1 {
|
||||
sizes[i], sizes[j] = sizes[j], sizes[i]
|
||||
}
|
||||
return sizes
|
||||
}
|
||||
|
||||
func (p *Processor) levelQuality(level, count int, size [2]int) int {
|
||||
switch {
|
||||
case level >= count-2:
|
||||
return p.images.Quality.Top
|
||||
case max(size[0], size[1]) <= 1100:
|
||||
return p.images.Quality.Low
|
||||
default:
|
||||
return p.images.Quality.Mid
|
||||
}
|
||||
}
|
||||
|
||||
func (p *Processor) TileID(hash string, level, x, y int) string {
|
||||
mac := hmac.New(sha256.New, p.key)
|
||||
mac.Write([]byte(hash + "|" + strconv.Itoa(level) + "|" + strconv.Itoa(x) + "|" + strconv.Itoa(y)))
|
||||
return hex.EncodeToString(mac.Sum(nil))[:16]
|
||||
}
|
||||
|
||||
type refFile struct {
|
||||
path string
|
||||
refs atomic.Int32
|
||||
}
|
||||
|
||||
func (r *refFile) release() {
|
||||
if r.refs.Add(-1) == 0 {
|
||||
_ = os.Remove(r.path)
|
||||
}
|
||||
}
|
||||
|
||||
func (p *Processor) process(ctx context.Context, job *Job) (*Record, error) {
|
||||
work := filepath.Join(p.workDir, job.Hash)
|
||||
stage := filepath.Join(p.TilesDir, "."+job.Hash+fsutil.TempMarker+"stage")
|
||||
for _, dir := range []string{work, stage} {
|
||||
if err := os.RemoveAll(dir); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
defer os.RemoveAll(work)
|
||||
committed := false
|
||||
defer func() {
|
||||
if !committed {
|
||||
_ = os.RemoveAll(stage)
|
||||
}
|
||||
}()
|
||||
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
|
||||
top := filepath.Join(work, "top.v")
|
||||
if err := p.prepare(ctx, job, work, top); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
width, height, err := VSize(top)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sizes := LevelSizes(width, height, p.images.MinLevels)
|
||||
count := len(sizes)
|
||||
seedLevel := count - 1
|
||||
for i, size := range sizes {
|
||||
if max(size[0], size[1]) >= p.images.SeedPx {
|
||||
seedLevel = i
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
levels := make([]Level, count)
|
||||
var seed string
|
||||
var firstErr error
|
||||
var errOnce sync.Once
|
||||
fail := func(err error) {
|
||||
errOnce.Do(func() {
|
||||
firstErr = err
|
||||
cancel()
|
||||
})
|
||||
}
|
||||
var wg sync.WaitGroup
|
||||
current := &refFile{path: top}
|
||||
for i := count - 1; i >= 0; i-- {
|
||||
if ctx.Err() != nil {
|
||||
break
|
||||
}
|
||||
if i == seedLevel {
|
||||
s, err := p.seed(ctx, current.path, work)
|
||||
if err != nil {
|
||||
fail(err)
|
||||
break
|
||||
}
|
||||
seed = s
|
||||
}
|
||||
if i > 0 {
|
||||
current.refs.Store(2)
|
||||
} else {
|
||||
current.refs.Store(1)
|
||||
}
|
||||
wg.Add(1)
|
||||
go func(i int, src *refFile) {
|
||||
defer wg.Done()
|
||||
defer src.release()
|
||||
level, err := p.cutLevel(ctx, job.Hash, src.path, stage, i, count, sizes[i])
|
||||
if err != nil {
|
||||
fail(fmt.Errorf("level %d: %w", i, err))
|
||||
return
|
||||
}
|
||||
levels[i] = level
|
||||
}(i, current)
|
||||
if i == 0 {
|
||||
break
|
||||
}
|
||||
next := &refFile{path: filepath.Join(work, "l"+strconv.Itoa(i-1)+".v")}
|
||||
err := p.resize(ctx, current.path, next.path, sizes[i], sizes[i-1])
|
||||
current.release()
|
||||
if err != nil {
|
||||
fail(fmt.Errorf("resize to level %d: %w", i-1, err))
|
||||
break
|
||||
}
|
||||
current = next
|
||||
}
|
||||
wg.Wait()
|
||||
if firstErr != nil {
|
||||
return nil, firstErr
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
leftovers, err := os.ReadDir(stage)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, entry := range leftovers {
|
||||
if entry.IsDir() || strings.HasSuffix(entry.Name(), ".dzi") {
|
||||
if err := os.RemoveAll(filepath.Join(stage, entry.Name())); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
final := filepath.Join(p.TilesDir, job.Hash)
|
||||
if err := os.RemoveAll(final); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := os.Rename(stage, final); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
committed = true
|
||||
|
||||
rec := &Record{
|
||||
Pyramid: Pyramid{Hash: job.Hash, Width: width, Height: height, Levels: levels, Seed: seed},
|
||||
Kind: job.Kind,
|
||||
Format: p.images.Format,
|
||||
TileSize: p.images.TileSize,
|
||||
Overlap: p.images.Overlap,
|
||||
Processed: time.Now().UTC().Truncate(time.Second),
|
||||
}
|
||||
if job.Kind == "photo" {
|
||||
rec.EXIF = job.Source.EXIF
|
||||
}
|
||||
if job.Crop != nil {
|
||||
rec.Crop = job.Crop[:]
|
||||
}
|
||||
if err := fsutil.WriteJSONAtomic(p.recordPath(job.Hash), rec); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return rec, nil
|
||||
}
|
||||
|
||||
func (p *Processor) prepare(ctx context.Context, job *Job, work, top string) error {
|
||||
input := job.Source.Path + "[autorotate]"
|
||||
if job.Crop != nil {
|
||||
cropped := filepath.Join(work, "crop.v")
|
||||
c := job.Crop
|
||||
if err := p.vips.Run(ctx, "extract_area", input, cropped,
|
||||
strconv.Itoa(c[0]), strconv.Itoa(c[1]), strconv.Itoa(c[2]), strconv.Itoa(c[3])); err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.Remove(cropped)
|
||||
input = cropped
|
||||
}
|
||||
err := p.vips.Run(ctx, "icc_transform", input, top, "srgb", "--embedded", "--intent", "perceptual")
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
_ = os.Remove(top)
|
||||
if fallbackErr := p.vips.Run(ctx, "colourspace", input, top, "srgb"); fallbackErr != nil {
|
||||
return errors.Join(err, fallbackErr)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func formatScale(to, from int) string {
|
||||
return strconv.FormatFloat(float64(to)/float64(from), 'g', -1, 64)
|
||||
}
|
||||
|
||||
func (p *Processor) resize(ctx context.Context, src, dst string, from, to [2]int) error {
|
||||
if err := p.vips.Run(ctx, "resize", src, dst, formatScale(to[0], from[0]),
|
||||
"--vscale", formatScale(to[1], from[1]), "--kernel", "lanczos3"); err != nil {
|
||||
return err
|
||||
}
|
||||
w, h, err := VSize(dst)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if w != to[0] || h != to[1] {
|
||||
return fmt.Errorf("vips produced %dx%d, expected %dx%d", w, h, to[0], to[1])
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Processor) seed(ctx context.Context, src, work string) (string, error) {
|
||||
out := filepath.Join(work, "seed."+p.images.Format)
|
||||
if err := p.vips.Run(ctx, "thumbnail", src, out+p.vips.SaveOptions(p.images.Quality.Low),
|
||||
strconv.Itoa(p.images.SeedPx), "--height", strconv.Itoa(p.images.SeedPx)); err != nil {
|
||||
return "", fmt.Errorf("seed: %w", err)
|
||||
}
|
||||
data, err := os.ReadFile(out)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
_ = os.Remove(out)
|
||||
return base64.StdEncoding.EncodeToString(data), nil
|
||||
}
|
||||
|
||||
type tileFile struct {
|
||||
name string
|
||||
x, y int
|
||||
}
|
||||
|
||||
func (p *Processor) cutLevel(ctx context.Context, hash, src, stage string, level, count int, size [2]int) (Level, error) {
|
||||
quality := p.levelQuality(level, count, size)
|
||||
base := filepath.Join(stage, strconv.Itoa(level))
|
||||
ext := "." + p.images.Format
|
||||
if err := p.vips.Run(ctx, "dzsave", src, base,
|
||||
"--layout", "dz",
|
||||
"--depth", "one",
|
||||
"--tile-size", strconv.Itoa(p.images.TileSize),
|
||||
"--overlap", strconv.Itoa(p.images.Overlap),
|
||||
"--suffix", ext+p.vips.SaveOptions(quality)); err != nil {
|
||||
return Level{}, err
|
||||
}
|
||||
dir := filepath.Join(base+"_files", "0")
|
||||
entries, err := os.ReadDir(dir)
|
||||
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))
|
||||
for _, entry := range entries {
|
||||
name := entry.Name()
|
||||
if !strings.HasSuffix(name, ext) {
|
||||
continue
|
||||
}
|
||||
xs, ys, ok := strings.Cut(strings.TrimSuffix(name, ext), "_")
|
||||
x, errX := strconv.Atoi(xs)
|
||||
y, errY := strconv.Atoi(ys)
|
||||
if !ok || errX != nil || errY != nil || x < 0 || y < 0 || x >= cols || y >= rows {
|
||||
return Level{}, fmt.Errorf("unexpected tile %s", name)
|
||||
}
|
||||
files = append(files, tileFile{name: name, x: x, y: y})
|
||||
}
|
||||
if len(files) != cols*rows {
|
||||
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),
|
||||
}
|
||||
renamers := min(4, (len(files)+31)/32)
|
||||
var wg sync.WaitGroup
|
||||
errs := make([]error, renamers)
|
||||
for r := 0; r < renamers; r++ {
|
||||
wg.Add(1)
|
||||
go func(r int) {
|
||||
defer wg.Done()
|
||||
for i := r; i < len(files); i += renamers {
|
||||
if ctx.Err() != nil {
|
||||
errs[r] = ctx.Err()
|
||||
return
|
||||
}
|
||||
f := files[i]
|
||||
id := p.TileID(hash, level, f.x, f.y)
|
||||
target := filepath.Join(stage, id+ext)
|
||||
if err := os.Rename(filepath.Join(dir, f.name), target); err != nil {
|
||||
errs[r] = err
|
||||
return
|
||||
}
|
||||
info, err := os.Stat(target)
|
||||
if err != nil {
|
||||
errs[r] = err
|
||||
return
|
||||
}
|
||||
slot := f.y*cols + f.x
|
||||
out.Tiles[slot] = id
|
||||
out.Bytes[slot] = info.Size()
|
||||
}
|
||||
}(r)
|
||||
}
|
||||
wg.Wait()
|
||||
if err := errors.Join(errs...); err != nil {
|
||||
return Level{}, err
|
||||
}
|
||||
_ = os.RemoveAll(base + "_files")
|
||||
_ = os.Remove(base + ".dzi")
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
package process
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type Vips struct {
|
||||
Version string
|
||||
Major int
|
||||
Minor int
|
||||
Strip string
|
||||
env []string
|
||||
}
|
||||
|
||||
var versionPattern = regexp.MustCompile(`vips-(\d+)\.(\d+)(\.\d+)?`)
|
||||
|
||||
func DetectVips(ctx context.Context, env []string) (*Vips, error) {
|
||||
path, err := exec.LookPath("vips")
|
||||
if err != nil {
|
||||
return nil, errors.New("vips not found in PATH; install libvips-tools")
|
||||
}
|
||||
cmd := exec.CommandContext(ctx, path, "--version")
|
||||
cmd.Env = env
|
||||
out, err := cmd.Output()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("vips --version: %w", err)
|
||||
}
|
||||
m := versionPattern.FindStringSubmatch(string(out))
|
||||
if m == nil {
|
||||
return nil, fmt.Errorf("vips --version: unrecognised output %q", strings.TrimSpace(string(out)))
|
||||
}
|
||||
major, _ := strconv.Atoi(m[1])
|
||||
minor, _ := strconv.Atoi(m[2])
|
||||
v := &Vips{Version: strings.TrimPrefix(m[0], "vips-"), Major: major, Minor: minor, env: env}
|
||||
if major > 8 || (major == 8 && minor >= 15) {
|
||||
v.Strip = "keep=none"
|
||||
} else {
|
||||
v.Strip = "strip"
|
||||
}
|
||||
if major < 8 || (major == 8 && minor < 12) {
|
||||
return nil, fmt.Errorf("libvips %s is too old; 8.12 or newer is required", v.Version)
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
type limitedBuffer struct {
|
||||
buf bytes.Buffer
|
||||
limit int
|
||||
}
|
||||
|
||||
func (l *limitedBuffer) Write(p []byte) (int, error) {
|
||||
if room := l.limit - l.buf.Len(); room > 0 {
|
||||
if len(p) > room {
|
||||
l.buf.Write(p[:room])
|
||||
} else {
|
||||
l.buf.Write(p)
|
||||
}
|
||||
}
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
func (v *Vips) Run(ctx context.Context, args ...string) error {
|
||||
cmd := exec.CommandContext(ctx, "vips", args...)
|
||||
cmd.Env = v.env
|
||||
stderr := &limitedBuffer{limit: 4096}
|
||||
cmd.Stderr = stderr
|
||||
cmd.Stdout = io.Discard
|
||||
if err := cmd.Run(); err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
msg := strings.TrimSpace(stderr.buf.String())
|
||||
if msg == "" {
|
||||
msg = err.Error()
|
||||
}
|
||||
return fmt.Errorf("vips %s: %s", args[0], msg)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (v *Vips) SaveOptions(quality int) string {
|
||||
return "[Q=" + strconv.Itoa(quality) + "," + v.Strip + "]"
|
||||
}
|
||||
|
||||
var (
|
||||
vipsMagicIntel = []byte{0xb6, 0xa6, 0xf2, 0x08}
|
||||
vipsMagicSparc = []byte{0x08, 0xf2, 0xa6, 0xb6}
|
||||
)
|
||||
|
||||
func VSize(path string) (int, int, error) {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
defer f.Close()
|
||||
var header [12]byte
|
||||
if _, err := io.ReadFull(f, header[:]); err != nil {
|
||||
return 0, 0, fmt.Errorf("%s: %w", path, err)
|
||||
}
|
||||
var order binary.ByteOrder
|
||||
switch {
|
||||
case bytes.Equal(header[:4], vipsMagicIntel):
|
||||
order = binary.LittleEndian
|
||||
case bytes.Equal(header[:4], vipsMagicSparc):
|
||||
order = binary.BigEndian
|
||||
default:
|
||||
return 0, 0, fmt.Errorf("%s: not a vips image", path)
|
||||
}
|
||||
return int(int32(order.Uint32(header[4:8]))), int(int32(order.Uint32(header[8:12]))), nil
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package site
|
||||
|
||||
import (
|
||||
"embed"
|
||||
"html/template"
|
||||
"io"
|
||||
|
||||
"github.com/luciochen233/luphoto/internal/process"
|
||||
)
|
||||
|
||||
//go:embed templates/*.html
|
||||
var templateFiles embed.FS
|
||||
|
||||
var templates = template.Must(template.ParseFS(templateFiles, "templates/*.html"))
|
||||
|
||||
type Tiles struct {
|
||||
Format string `json:"format"`
|
||||
TileSize int `json:"tile_size"`
|
||||
Overlap int `json:"overlap"`
|
||||
Path string `json:"path"`
|
||||
}
|
||||
|
||||
type Photo struct {
|
||||
process.Pyramid
|
||||
Title string `json:"title,omitempty"`
|
||||
Caption string `json:"caption,omitempty"`
|
||||
Alt string `json:"alt,omitempty"`
|
||||
Slides int `json:"slides"`
|
||||
EXIF *process.EXIF `json:"exif,omitempty"`
|
||||
}
|
||||
|
||||
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"`
|
||||
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"`
|
||||
}
|
||||
|
||||
type Index struct {
|
||||
Build string `json:"build"`
|
||||
Tiles Tiles `json:"tiles"`
|
||||
Albums []IndexAlbum `json:"albums"`
|
||||
}
|
||||
|
||||
func IndexURL(build string) string {
|
||||
return "/index." + build + ".json"
|
||||
}
|
||||
|
||||
func ManifestURL(build, slug string) string {
|
||||
return "/a/" + slug + "/manifest." + build + ".json"
|
||||
}
|
||||
|
||||
func ManifestName(build string) string {
|
||||
return "manifest." + build + ".json"
|
||||
}
|
||||
|
||||
func IndexName(build string) string {
|
||||
return "index." + build + ".json"
|
||||
}
|
||||
|
||||
type indexPage struct {
|
||||
Build string
|
||||
IndexURL string
|
||||
Albums []IndexAlbum
|
||||
}
|
||||
|
||||
type albumPage struct {
|
||||
Build string
|
||||
Slug string
|
||||
Title string
|
||||
Subtitle string
|
||||
Date string
|
||||
Photos int
|
||||
ManifestURL string
|
||||
IndexURL string
|
||||
}
|
||||
|
||||
func RenderIndex(w io.Writer, index *Index) error {
|
||||
return templates.ExecuteTemplate(w, "index.html", indexPage{
|
||||
Build: index.Build,
|
||||
IndexURL: IndexURL(index.Build),
|
||||
Albums: index.Albums,
|
||||
})
|
||||
}
|
||||
|
||||
func RenderAlbum(w io.Writer, m *Manifest) error {
|
||||
return templates.ExecuteTemplate(w, "album.html", albumPage{
|
||||
Build: m.Build,
|
||||
Slug: m.Slug,
|
||||
Title: m.Title,
|
||||
Subtitle: m.Subtitle,
|
||||
Date: m.Date,
|
||||
Photos: len(m.Photos),
|
||||
ManifestURL: ManifestURL(m.Build, m.Slug),
|
||||
IndexURL: IndexURL(m.Build),
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="robots" content="noimageindex">
|
||||
<title>{{.Title}} · Lucio</title>
|
||||
<link rel="preload" href="{{.ManifestURL}}" as="fetch" crossorigin>
|
||||
</head>
|
||||
<body data-build="{{.Build}}" data-album="{{.Slug}}" data-manifest="{{.ManifestURL}}" data-index="{{.IndexURL}}">
|
||||
<main>
|
||||
<h1>{{.Title}}</h1>
|
||||
{{- if .Subtitle}}
|
||||
<p>{{.Subtitle}}</p>
|
||||
{{- end}}
|
||||
<p>{{.Photos}} photos{{if .Date}} · <time>{{.Date}}</time>{{end}}</p>
|
||||
<p><a href="/">All albums</a></p>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,20 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="robots" content="noimageindex">
|
||||
<title>Photos · Lucio</title>
|
||||
<link rel="preload" href="{{.IndexURL}}" as="fetch" crossorigin>
|
||||
</head>
|
||||
<body data-build="{{.Build}}" data-index="{{.IndexURL}}">
|
||||
<main>
|
||||
<h1>Photos · Lucio</h1>
|
||||
<ul>
|
||||
{{- range .Albums}}
|
||||
<li><a href="/a/{{.Slug}}/">{{.Title}}</a>{{if .Subtitle}} <span>{{.Subtitle}}</span>{{end}}{{if .Date}} <time>{{.Date}}</time>{{end}}</li>
|
||||
{{- end}}
|
||||
</ul>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,5 @@
|
||||
FROM ubuntu:24.04
|
||||
RUN apt-get update \
|
||||
&& DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends golang-go libvips-tools ca-certificates git \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
WORKDIR /src
|
||||
@@ -0,0 +1,45 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
scripts_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
repo_dir="$(dirname "$scripts_dir")"
|
||||
image="${LUPHOTO_DEV_IMAGE:-luphoto-dev}"
|
||||
|
||||
case "$(uname -s)" in
|
||||
MINGW*|MSYS*|CYGWIN*)
|
||||
export MSYS_NO_PATHCONV=1
|
||||
scripts_host="$(cygpath -w "$scripts_dir")"
|
||||
repo_host="$(cygpath -w "$repo_dir")"
|
||||
;;
|
||||
*)
|
||||
scripts_host="$scripts_dir"
|
||||
repo_host="$repo_dir"
|
||||
;;
|
||||
esac
|
||||
|
||||
if [ "${LUPHOTO_DEV_REBUILD:-0}" = "1" ] || ! docker image inspect "$image" >/dev/null 2>&1; then
|
||||
docker build -t "$image" -f "$scripts_host/dev.Dockerfile" "$scripts_host"
|
||||
fi
|
||||
|
||||
tty_args=()
|
||||
if [ -t 0 ] && [ -t 1 ]; then
|
||||
tty_args=(-it)
|
||||
fi
|
||||
|
||||
extra_args=()
|
||||
if [ -n "${LUPHOTO_DEV_ARGS:-}" ]; then
|
||||
read -r -a extra_args <<<"$LUPHOTO_DEV_ARGS"
|
||||
fi
|
||||
|
||||
if [ "$#" -eq 0 ]; then
|
||||
set -- bash
|
||||
fi
|
||||
|
||||
exec docker run --rm "${tty_args[@]}" \
|
||||
-v "$repo_host:/src" \
|
||||
-v luphoto-gomod:/root/go/pkg/mod \
|
||||
-v luphoto-gocache:/root/.cache/go-build \
|
||||
-e GOFLAGS="${GOFLAGS:-}" \
|
||||
-w /src \
|
||||
"${extra_args[@]}" \
|
||||
"$image" "$@"
|
||||
Reference in new issue
Block a user