Files
2026-11-18 21:37:25 +03:00

268 lines
6.9 KiB
Go

package attachment
import (
"bytes"
"context"
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"encoding/json"
"errors"
"image"
"image/color"
"image/jpeg"
"image/png"
"math"
"os"
"os/exec"
"path/filepath"
"syscall"
)
var ErrInvalidImage = errors.New("invalid image")
type oriented struct {
image.Image
orientation int
}
func (o oriented) Bounds() image.Rectangle {
b := o.Image.Bounds()
w, h := b.Dx(), b.Dy()
if o.orientation >= 5 && o.orientation <= 8 {
w, h = h, w
}
return image.Rect(0, 0, w, h)
}
func (o oriented) At(x, y int) color.Color {
b := o.Image.Bounds()
w, h := b.Dx(), b.Dy()
sx, sy := x, y
switch o.orientation {
case 2:
sx = w - 1 - x
case 3:
sx, sy = w-1-x, h-1-y
case 4:
sy = h - 1 - y
case 5:
sx, sy = y, x
case 6:
sx, sy = y, h-1-x
case 7:
sx, sy = w-1-y, h-1-x
case 8:
sx, sy = w-1-y, x
}
r, g, blue, a := o.Image.At(b.Min.X+sx, b.Min.Y+sy).RGBA()
white := uint32(65535) - a
return color.RGBA{uint8((r + white) / 257), uint8((g + white) / 257), uint8((blue + white) / 257), 255}
}
// EXIF IFD0 orientation; bounded segment parsing does not follow client offsets outside APP1.
func tiffOrientation(t []byte) int {
if len(t) < 8 {
return 1
}
var order binary.ByteOrder
if string(t[:2]) == "II" {
order = binary.LittleEndian
} else if string(t[:2]) == "MM" {
order = binary.BigEndian
} else {
return 1
}
if order.Uint16(t[2:4]) != 42 {
return 1
}
offset := uint64(order.Uint32(t[4:8]))
if offset+2 > uint64(len(t)) {
return 1
}
count := uint64(order.Uint16(t[offset : offset+2]))
for k := uint64(0); k < count; k++ {
p := offset + 2 + k*12
if p+12 > uint64(len(t)) {
break
}
entry := t[p : p+12]
if order.Uint16(entry[:2]) == 0x112 && order.Uint16(entry[2:4]) == 3 && order.Uint32(entry[4:8]) == 1 {
v := int(order.Uint16(entry[8:10]))
if v >= 1 && v <= 8 {
return v
}
}
}
return 1
}
func Orientation(data []byte) int {
if len(data) >= 8 && bytes.Equal(data[:8], []byte{137, 80, 78, 71, 13, 10, 26, 10}) {
for i := 8; i+12 <= len(data); {
n := uint64(binary.BigEndian.Uint32(data[i : i+4]))
if n > uint64(len(data)-i-12) {
return 1
}
end := i + 8 + int(n)
if string(data[i+4:i+8]) == "eXIf" {
return tiffOrientation(data[i+8 : end])
}
i = end + 4
}
return 1
}
if len(data) < 4 || data[0] != 255 || data[1] != 216 {
return 1
}
for i := 2; i+4 <= len(data); {
if data[i] != 255 {
return 1
}
for i+1 < len(data) && data[i+1] == 255 {
i++
}
if i+3 >= len(data) {
return 1
}
marker := data[i+1]
i += 2
if marker == 0xda || marker == 0xd9 {
return 1
}
if marker == 0x01 || marker >= 0xd0 && marker <= 0xd7 {
continue
}
n := int(binary.BigEndian.Uint16(data[i : i+2]))
if n < 2 || i+n > len(data) {
return 1
}
body := data[i+2 : i+n]
i += n
if marker == 0xe1 && len(body) >= 14 && bytes.Equal(body[:6], []byte("Exif\x00\x00")) {
return tiffOrientation(body[6:])
}
}
return 1
}
func fit(w, h, maxSide int) (int, int) {
if w <= maxSide && h <= maxSide {
return w, h
}
if w >= h {
return maxSide, max(1, int(int64(h)*int64(maxSide)/int64(w)))
}
return max(1, int(int64(w)*int64(maxSide)/int64(h))), maxSide
}
func resize(src image.Image, region image.Rectangle, w, h int) *image.RGBA {
out := image.NewRGBA(image.Rect(0, 0, w, h))
for y := 0; y < h; y++ {
fy := (float64(y)+.5)*float64(region.Dy())/float64(h) - .5
fy = math.Max(0, fy)
y0 := min(int(fy), region.Dy()-1)
y1 := min(y0+1, region.Dy()-1)
dy := fy - float64(y0)
for x := 0; x < w; x++ {
fx := (float64(x)+.5)*float64(region.Dx())/float64(w) - .5
fx = math.Max(0, fx)
x0 := min(int(fx), region.Dx()-1)
x1 := min(x0+1, region.Dx()-1)
dx := fx - float64(x0)
colors := [4]color.RGBA{color.RGBAModel.Convert(src.At(region.Min.X+x0, region.Min.Y+y0)).(color.RGBA), color.RGBAModel.Convert(src.At(region.Min.X+x1, region.Min.Y+y0)).(color.RGBA), color.RGBAModel.Convert(src.At(region.Min.X+x0, region.Min.Y+y1)).(color.RGBA), color.RGBAModel.Convert(src.At(region.Min.X+x1, region.Min.Y+y1)).(color.RGBA)}
blend := func(a, b, c, d uint8) uint8 {
return uint8(math.Round(float64(a)*(1-dx)*(1-dy) + float64(b)*dx*(1-dy) + float64(c)*(1-dx)*dy + float64(d)*dx*dy))
}
out.SetRGBA(x, y, color.RGBA{blend(colors[0].R, colors[1].R, colors[2].R, colors[3].R), blend(colors[0].G, colors[1].G, colors[2].G, colors[3].G), blend(colors[0].B, colors[1].B, colors[2].B, colors[3].B), 255})
}
}
return out
}
// Render runs only inside a deadline-killed child, never in the HTTP process.
func Render(ctx context.Context, source, dir, expectedSHA string) error {
raw, err := os.ReadFile(source)
if err != nil {
return err
}
sum := sha256.Sum256(raw)
if int64(len(raw)) > MaxBytes || hex.EncodeToString(sum[:]) != expectedSHA {
return ErrInvalidImage
}
cfg, _, err := image.DecodeConfig(bytes.NewReader(raw))
if err != nil || cfg.Width < 1 || cfg.Height < 1 || int64(cfg.Width) > MaxPixels/int64(cfg.Height) {
return ErrInvalidImage
}
if os.Getenv("PIPELINE_FAILPOINT") == "renderer_timeout" {
fifo := filepath.Join(dir, "blocked-input.png")
if err = syscall.Mkfifo(fifo, 0600); err != nil {
return err
}
return exec.CommandContext(ctx, "cwebp", "-quiet", fifo, "-o", filepath.Join(dir, "blocked.webp")).Run()
}
decoded, _, err := image.Decode(bytes.NewReader(raw))
if err != nil {
return ErrInvalidImage
}
src := oriented{decoded, Orientation(raw)}
bounds := src.Bounds()
tw, th := fit(bounds.Dx(), bounds.Dy(), 256)
ow, oh := fit(bounds.Dx(), bounds.Dy(), 1280)
variants := []Variant{}
for _, name := range []string{"thumbnail", "crop", "optimized"} {
w, h := tw, th
region := bounds
if name == "crop" {
w, h = 128, 128
side := min(bounds.Dx(), bounds.Dy())
left, top := (bounds.Dx()-side)/2, (bounds.Dy()-side)/2
region = image.Rect(left, top, left+side, top+side)
}
if name == "optimized" {
w, h = ow, oh
}
img := resize(src, region, w, h)
path := filepath.Join(dir, name)
if name == "optimized" {
input := filepath.Join(dir, "webp-input.png")
f, e := os.Create(input)
if e != nil {
return e
}
e = png.Encode(f, img)
f.Close()
if e != nil {
return e
}
command := exec.CommandContext(ctx, "cwebp", "-quiet", "-q", "80", "-m", "4", "-metadata", "none", input, "-o", path)
if err = command.Run(); err != nil {
return err
}
} else {
f, e := os.Create(path)
if e != nil {
return e
}
e = jpeg.Encode(f, img, &jpeg.Options{Quality: 85})
f.Close()
if e != nil {
return e
}
}
data, e := os.ReadFile(path)
if e != nil {
return e
}
hash := sha256.Sum256(data)
mime := "image/jpeg"
if name == "optimized" {
mime = "image/webp"
}
variants = append(variants, Variant{Name: name, ContentType: mime, Width: w, Height: h, Size: int64(len(data)), SHA256: hex.EncodeToString(hash[:])})
}
data, err := json.Marshal(variants)
if err != nil {
return err
}
return os.WriteFile(filepath.Join(dir, "manifest.json"), data, 0600)
}