Files
mtusi2026lab5/internal/worker/image.go
T

153 lines
3.3 KiB
Go

package worker
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"image"
"image/color"
"image/draw"
"image/jpeg"
_ "image/png"
"io"
"os"
"strconv"
"github.com/disintegration/imaging"
"mtusi2026-messenger/internal/db"
)
var errInvalidSource = errors.New("invalid source image")
func thumbnail(r io.ReadSeeker, maxPixels int) ([]byte, int, int, error) {
cfg, format, err := image.DecodeConfig(r)
if err != nil ||
(format != "png" && format != "jpeg") ||
cfg.Width <= 0 ||
cfg.Height <= 0 ||
cfg.Width > maxPixels/cfg.Height {
return nil, 0, 0, errInvalidSource
}
if _, err := r.Seek(0, io.SeekStart); err != nil {
return nil, 0, 0, err
}
src, err := imaging.Decode(r, imaging.AutoOrientation(true))
if err != nil {
return nil, 0, 0, errInvalidSource
}
width, height := src.Bounds().Dx(), src.Bounds().Dy()
if width > 256 || height > 256 {
if width >= height {
height = max(1, height*256/width)
width = 256
} else {
width = max(1, width*256/height)
height = 256
}
src = imaging.Resize(src, width, height, imaging.Lanczos)
}
dst := image.NewRGBA(image.Rect(0, 0, width, height))
draw.Draw(dst, dst.Bounds(), image.NewUniform(color.White), image.Point{}, draw.Src)
draw.Draw(dst, dst.Bounds(), src, src.Bounds().Min, draw.Over)
var out bytes.Buffer
if err := jpeg.Encode(&out, dst, &jpeg.Options{Quality: 85}); err != nil {
return nil, 0, 0, err
}
return out.Bytes(), width, height, nil
}
func (w *Worker) process(ctx context.Context, row db.Attachment) ([]db.CreateAttachmentVariantParams, error) {
if row.StagingKey == nil {
return nil, errInvalidSource
}
source, err := w.s3.Get(ctx, *row.StagingKey)
if err != nil {
return nil, err
}
defer source.Body.Close()
tmp, err := os.CreateTemp("", "attachment-job-*")
if err != nil {
return nil, err
}
defer func() {
_ = tmp.Close()
_ = os.Remove(tmp.Name())
}()
hash := sha256.New()
size, err := io.Copy(io.MultiWriter(tmp, hash), io.LimitReader(source.Body, int64(w.maxBytes)+1))
if err != nil {
return nil, err
}
if size != int64(row.SizeBytes) ||
hex.EncodeToString(hash.Sum(nil)) != row.Sha256 {
return nil, errInvalidSource
}
if _, err := tmp.Seek(0, io.SeekStart); err != nil {
return nil, err
}
select {
case w.decodeSlot <- struct{}{}:
case <-ctx.Done():
return nil, ctx.Err()
}
if err := ctx.Err(); err != nil {
<-w.decodeSlot
return nil, err
}
data, width, height, err := thumbnail(tmp, w.maxPixels)
<-w.decodeSlot
if err != nil {
return nil, err
}
if err := ctx.Err(); err != nil {
return nil, err
}
if _, err := tmp.Seek(0, io.SeekStart); err != nil {
return nil, err
}
if err := w.s3.Put(ctx, row.S3Key, tmp, size, string(row.ContentType)); err != nil {
return nil, err
}
key := "variants/" + row.ID.String() + "/v" + strconv.Itoa(row.PipelineVersion) + "/thumbnail"
if err := w.s3.Put(ctx, key, bytes.NewReader(data), int64(len(data)), "image/jpeg"); err != nil {
return nil, err
}
sum := sha256.Sum256(data)
return []db.CreateAttachmentVariantParams{{
AttachmentID: row.ID,
PipelineVersion: row.PipelineVersion,
Variant: db.AttachmentVariantNameThumbnail,
S3Key: key,
ContentType: "image/jpeg",
SizeBytes: len(data),
Width: width,
Height: height,
Sha256: hex.EncodeToString(sum[:]),
}}, nil
}