Files
upandown/internal/storage/thumbs.go
T

304 lines
7.4 KiB
Go

package storage
import (
"bytes"
"encoding/binary"
"fmt"
"image"
"image/draw"
"image/gif"
"image/jpeg"
"image/png"
"io"
"os"
"path"
"path/filepath"
"strings"
"time"
)
// Miniatures des images (JPEG, PNG, GIF), générées par le serveur à la
// demande avec la bibliothèque standard et rangées dans .thumbs/ en miroir de
// l'arborescence (a/b.jpg -> .thumbs/a/b.jpg.thumb). Une miniature plus ancienne
// que son fichier est considérée comme périmée et régénérée. L'orientation
// EXIF des JPEG est appliquée. Les autres formats (WebP, SVG...) sont affichés
// tels quels par le navigateur, sans miniature.
const (
// ThumbSize est le plus grand côté d'une miniature (pixels).
ThumbSize = 480
maxThumbPixels = 25_000_000 // protège contre les « bombes » de décompression
maxThumbSource = 80 << 20 // taille maximale du fichier source
)
// isDecodableImage indique si la bibliothèque standard sait décoder le fichier.
func isDecodableImage(name string) bool {
switch strings.ToLower(path.Ext(name)) {
case ".jpg", ".jpeg", ".png", ".gif":
return true
}
return false
}
func (s *Store) thumbAbs(c string, isDir bool) string {
p := filepath.Join(s.root, thumbsDir, filepath.FromSlash(c))
if isDir {
return p
}
return p + ".thumb"
}
// Thumb renvoie la miniature d'une image (créée si absente ou périmée), son
// type MIME et sa date. ErrNotFound si le fichier n'est pas une image
// décodable.
func (s *Store) Thumb(rel string) ([]byte, string, time.Time, error) {
c, abs, err := s.resolve(rel)
if err != nil {
return nil, "", time.Time{}, err
}
if c == "" || !isDecodableImage(c) {
return nil, "", time.Time{}, ErrNotFound
}
src, err := os.Lstat(abs)
if err != nil || !src.Mode().IsRegular() {
return nil, "", time.Time{}, ErrNotFound
}
ta := s.thumbAbs(c, false)
if ti, err := os.Stat(ta); err == nil && !ti.ModTime().Before(src.ModTime()) {
if b, err := os.ReadFile(ta); err == nil {
return b, sniffThumb(b), ti.ModTime(), nil
}
}
if src.Size() > maxThumbSource {
return nil, "", time.Time{}, ErrNotFound
}
s.thumbSem <- struct{}{}
defer func() { <-s.thumbSem }()
b, err := makeThumb(abs)
if err != nil {
return nil, "", time.Time{}, ErrNotFound
}
if err := os.MkdirAll(filepath.Dir(ta), 0o755); err == nil {
_ = atomicWrite(ta, b)
}
return b, sniffThumb(b), time.Now(), nil
}
func sniffThumb(b []byte) string {
if bytes.HasPrefix(b, []byte("\x89PNG")) {
return "image/png"
}
return "image/jpeg"
}
func makeThumb(abs string) ([]byte, error) {
f, err := os.Open(abs)
if err != nil {
return nil, err
}
defer f.Close()
cfg, format, err := image.DecodeConfig(f)
if err != nil {
return nil, err
}
if cfg.Width < 1 || cfg.Height < 1 || cfg.Width*cfg.Height > maxThumbPixels {
return nil, fmt.Errorf("image hors limites (%dx%d)", cfg.Width, cfg.Height)
}
if _, err := f.Seek(0, io.SeekStart); err != nil {
return nil, err
}
orientation := 1
if format == "jpeg" {
orientation = jpegOrientation(f)
if _, err := f.Seek(0, io.SeekStart); err != nil {
return nil, err
}
}
var img image.Image
switch format {
case "jpeg":
img, err = jpeg.Decode(f)
case "png":
img, err = png.Decode(f)
case "gif":
img, err = gif.Decode(f)
default:
err = fmt.Errorf("format %s non géré", format)
}
if err != nil {
return nil, err
}
b := img.Bounds()
w, h := b.Dx(), b.Dy()
scale := float64(ThumbSize) / float64(max(w, h))
tw, th := w, h
if scale < 1 {
tw, th = max(1, int(float64(w)*scale+0.5)), max(1, int(float64(h)*scale+0.5))
}
out := orient(resize(img, tw, th), orientation)
var buf bytes.Buffer
if format == "jpeg" {
// Fond blanc : un JPEG n'a pas de transparence, mais le décodage CMJN ou autre pourrait en avoir.
err = jpeg.Encode(&buf, out, &jpeg.Options{Quality: 82})
} else {
err = png.Encode(&buf, out)
}
return buf.Bytes(), err
}
// resize rééchantillonne img en w x h par moyenne de surface (filtre « boîte »),
// en alpha prémultiplié ; sans agrandissement au-delà de la taille d'origine.
func resize(img image.Image, w, h int) *image.RGBA {
b := img.Bounds()
src := image.NewRGBA(image.Rect(0, 0, b.Dx(), b.Dy()))
draw.Draw(src, src.Bounds(), img, b.Min, draw.Src)
if w == b.Dx() && h == b.Dy() {
return src
}
wx, wy := boxWeights(b.Dx(), w), boxWeights(b.Dy(), h)
dst := image.NewRGBA(image.Rect(0, 0, w, h))
for dy := 0; dy < h; dy++ {
for dx := 0; dx < w; dx++ {
var acc [4]float64
var total float64
for _, y := range wy[dy] {
row := y.i * src.Stride
for _, x := range wx[dx] {
k := y.w * x.w
p := src.Pix[row+x.i*4:]
acc[0] += k * float64(p[0])
acc[1] += k * float64(p[1])
acc[2] += k * float64(p[2])
acc[3] += k * float64(p[3])
total += k
}
}
o := dst.PixOffset(dx, dy)
for c := range acc {
dst.Pix[o+c] = uint8(acc[c]/total + 0.5)
}
}
}
return dst
}
// jpegOrientation lit l'orientation EXIF (1 à 8) d'un JPEG ; 1 si absente.
func jpegOrientation(r io.Reader) int {
buf := make([]byte, 128<<10)
n, _ := io.ReadFull(r, buf)
d := buf[:n]
if len(d) < 4 || d[0] != 0xFF || d[1] != 0xD8 {
return 1
}
i := 2
for i+4 <= len(d) {
if d[i] != 0xFF {
return 1
}
marker := d[i+1]
if marker == 0xDA || marker == 0xD9 { // début des données ou fin
return 1
}
size := int(binary.BigEndian.Uint16(d[i+2:]))
if size < 2 || i+2+size > len(d) {
return 1
}
if marker == 0xE1 && size >= 16 && string(d[i+4:i+10]) == "Exif\x00\x00" {
return exifOrientation(d[i+10 : i+2+size])
}
i += 2 + size
}
return 1
}
func exifOrientation(t []byte) int {
if len(t) < 8 {
return 1
}
var bo binary.ByteOrder
switch string(t[:2]) {
case "II":
bo = binary.LittleEndian
case "MM":
bo = binary.BigEndian
default:
return 1
}
off := int(bo.Uint32(t[4:]))
if off < 8 || off+2 > len(t) {
return 1
}
count := int(bo.Uint16(t[off:]))
for k := 0; k < count; k++ {
e := off + 2 + k*12
if e+12 > len(t) {
return 1
}
if bo.Uint16(t[e:]) == 0x0112 {
if v := int(bo.Uint16(t[e+8:])); v >= 1 && v <= 8 {
return v
}
return 1
}
}
return 1
}
// orient applique l'orientation EXIF o (2 : miroir horizontal, 3 : 180°,
// 4 : miroir vertical, 5 : transposée, 6 : 90° horaire, 7 : transverse,
// 8 : 90° anti-horaire).
func orient(src *image.RGBA, o int) *image.RGBA {
if o <= 1 || o > 8 {
return src
}
w, h := src.Bounds().Dx(), src.Bounds().Dy()
dw, dh := w, h
if o >= 5 {
dw, dh = h, w
}
dst := image.NewRGBA(image.Rect(0, 0, dw, dh))
for y := 0; y < h; y++ {
for x := 0; x < w; x++ {
var nx, ny int
switch o {
case 2:
nx, ny = w-1-x, y
case 3:
nx, ny = w-1-x, h-1-y
case 4:
nx, ny = x, h-1-y
case 5:
nx, ny = y, x
case 6:
nx, ny = h-1-y, x
case 7:
nx, ny = h-1-y, w-1-x
case 8:
nx, ny = y, w-1-x
}
copy(dst.Pix[dst.PixOffset(nx, ny):dst.PixOffset(nx, ny)+4], src.Pix[src.PixOffset(x, y):src.PixOffset(x, y)+4])
}
}
return dst
}
// Les opérations suivantes accompagnent Move/Delete. Elles sont « au mieux » :
// une miniature manquante sera simplement régénérée.
func (s *Store) moveThumb(from, to string, isDir bool) {
src, dst := s.thumbAbs(from, isDir), s.thumbAbs(to, isDir)
if _, err := os.Stat(src); err != nil {
return
}
_ = os.RemoveAll(dst)
if err := os.MkdirAll(filepath.Dir(dst), 0o755); err == nil {
_ = os.Rename(src, dst)
}
}
func (s *Store) removeThumb(c string) {
_ = os.Remove(s.thumbAbs(c, false))
_ = os.RemoveAll(s.thumbAbs(c, true))
}