Files
lucioandClaude Opus 5.5 f5152fb709 Anti-scraping: 3x3 grids, decoy pools, robot check
Every pyramid level is cut into at least min_grid x min_grid tiles.
Each photo's tile pool mixes real tiles with hard-linked decoys from
other photos; the grid-to-pool map, byte sizes, seed and scramble seed
are sealed per build and unlocked by a press-and-hold check backed by
a static proof of work. Cell scrambling is on by default, and
robots.txt disallows tiles and pool files.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 21:39:30 -08:00

469 lines
12 KiB
Go

package process
import (
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"math"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/luciochen233/luphoto/internal/fsutil"
)
const minLongEdge = 100
func (p *Processor) Overlap() int {
if p.images.ScrambleCells {
return 0
}
return p.images.Overlap
}
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
}
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]
}
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)
}
}
const (
OGWidth = 1200
OGHeight = 630
OGQuality = 80
)
func OGRegion(width, height int, crop [4]int) [4]int {
h := min(height, crop[3])
w := int(math.Round(float64(h) * OGWidth / OGHeight))
if w > width {
w = width
h = min(height, int(math.Round(float64(w)*OGHeight/OGWidth)))
}
cx := float64(crop[0]) + float64(crop[2])/2
cy := float64(crop[1]) + float64(crop[3])/2
x := max(0, min(width-w, int(math.Round(cx-float64(w)/2))))
y := max(0, min(height-h, int(math.Round(cy-float64(h)/2))))
return [4]int{x, y, max(1, w), max(1, h)}
}
func (p *Processor) renderOG(ctx context.Context, job *Job) (*Record, error) {
work := filepath.Join(p.workDir, job.Hash)
if err := os.RemoveAll(work); err != nil {
return nil, err
}
if err := os.MkdirAll(work, 0o755); err != nil {
return nil, err
}
defer os.RemoveAll(work)
prepared := filepath.Join(work, "og.v")
if err := p.prepare(ctx, job, work, prepared); err != nil {
return nil, err
}
final := filepath.Join(p.OGDir, job.Hash+".jpg")
tmp := fsutil.TempName(final) + ".jpg"
if err := p.vips.Run(ctx, "thumbnail", prepared, tmp+p.vips.SaveOptions("jpeg", OGQuality),
strconv.Itoa(OGWidth), "--height", strconv.Itoa(OGHeight), "--crop", "centre"); err != nil {
_ = os.Remove(tmp)
return nil, err
}
if err := os.Rename(tmp, final); err != nil {
_ = os.Remove(tmp)
return nil, err
}
return &Record{Pyramid: Pyramid{Hash: job.Hash, Width: OGWidth, Height: OGHeight}, Kind: "og", Format: "jpeg"}, nil
}
func (p *Processor) process(ctx context.Context, job *Job) (*Record, error) {
if job.Kind == "og" {
return p.renderOG(ctx, job)
}
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, p.images.MinGrid)
count := len(sizes)
seedLevel := count - 1
for i, size := range sizes {
if max(size[0], size[1]) >= p.images.SeedPx {
seedLevel = i
break
}
}
scrambleSeed := ""
if p.images.ScrambleCells {
scrambleSeed = p.ScrambleSeed(job.Hash)
}
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()
input := src.path
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, ts, ScrambleCell); err != nil {
fail(fmt.Errorf("scramble level %d: %w", i, err))
return
}
defer os.Remove(scrambled)
input = scrambled
}
level, err := p.cutLevel(ctx, job.Hash, input, 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, Scramble: scrambleSeed},
Kind: job.Kind,
Format: p.images.Format,
TileSize: p.images.TileSize,
Overlap: p.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.Format, 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
}
func levelDir(files string) (string, error) {
entries, err := os.ReadDir(files)
if err != nil {
return "", err
}
found := ""
for _, entry := range entries {
if !entry.IsDir() {
continue
}
if _, err := strconv.Atoi(entry.Name()); err != nil {
continue
}
if found != "" {
return "", fmt.Errorf("dzsave wrote more than one level in %s", files)
}
found = filepath.Join(files, entry.Name())
}
if found == "" {
return "", fmt.Errorf("dzsave wrote no level in %s", files)
}
return found, 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
ts, overlap := p.levelTile(size)
if err := p.vips.Run(ctx, "dzsave", src, base,
"--layout", "dz",
"--depth", "one",
"--tile-size", strconv.Itoa(ts),
"--overlap", strconv.Itoa(overlap),
"--suffix", ext+p.vips.SaveOptions(p.images.Format, quality)); err != nil {
return Level{}, err
}
dir, err := levelDir(base + "_files")
if err != nil {
return Level{}, err
}
entries, err := os.ReadDir(dir)
if err != nil {
return Level{}, err
}
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],
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
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
}