forked from mtusi2026/mtusi2026lab4
73 lines
1.8 KiB
Go
73 lines
1.8 KiB
Go
package imagefile
|
|
|
|
import (
|
|
"backend/internal/domain/model"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"errors"
|
|
"image"
|
|
_ "image/jpeg"
|
|
_ "image/png"
|
|
"io"
|
|
"os"
|
|
)
|
|
|
|
var ErrTooLarge = errors.New("image too large")
|
|
var ErrUnsupported = errors.New("invalid image or MIME")
|
|
|
|
type File struct {
|
|
*os.File
|
|
Size int64
|
|
SHA256, ContentType string
|
|
}
|
|
|
|
func (f *File) Dispose() { _ = f.Close(); _ = os.Remove(f.Name()) }
|
|
func Inspect(body io.Reader, filename, mime string) (out *File, err error) {
|
|
if err = model.ValidateFilename(filename); err != nil {
|
|
return nil, err
|
|
}
|
|
if mime != "image/png" && mime != "image/jpeg" {
|
|
return nil, ErrUnsupported
|
|
}
|
|
f, e := os.CreateTemp("", "messenger-upload-*")
|
|
if e != nil {
|
|
return nil, e
|
|
}
|
|
defer func() {
|
|
if err != nil {
|
|
_ = f.Close()
|
|
_ = os.Remove(f.Name())
|
|
}
|
|
}()
|
|
hash := sha256.New()
|
|
n, e := io.Copy(io.MultiWriter(f, hash), io.LimitReader(body, model.MaxImageBytes+1))
|
|
if e != nil {
|
|
return nil, &model.ValidationError{Message: "incomplete image upload"}
|
|
}
|
|
if n > model.MaxImageBytes {
|
|
return nil, ErrTooLarge
|
|
}
|
|
if _, e = f.Seek(0, io.SeekStart); e != nil {
|
|
return nil, e
|
|
}
|
|
cfg, format, e := image.DecodeConfig(f)
|
|
if e != nil || "image/"+format != mime {
|
|
return nil, ErrUnsupported
|
|
}
|
|
pixels := int64(cfg.Width) * int64(cfg.Height)
|
|
if cfg.Width < 1 || cfg.Height < 1 || pixels > model.MaxImagePixels {
|
|
return nil, ErrTooLarge
|
|
}
|
|
if _, e = f.Seek(0, io.SeekStart); e != nil {
|
|
return nil, e
|
|
}
|
|
decoded, actual, e := image.Decode(f)
|
|
if e != nil || actual != format || decoded.Bounds().Dx() != cfg.Width || decoded.Bounds().Dy() != cfg.Height {
|
|
return nil, ErrUnsupported
|
|
}
|
|
if _, e = f.Seek(0, io.SeekStart); e != nil {
|
|
return nil, e
|
|
}
|
|
return &File{f, n, hex.EncodeToString(hash.Sum(nil)), mime}, nil
|
|
}
|