package imageproc import ( "context" "crypto/sha256" "encoding/hex" "errors" "fmt" "image" _ "image/jpeg" _ "image/png" "io" "os" "os/exec" "path/filepath" "strconv" "strings" "highload/internal/model" ) const ( MaxBytes = 10 * 1024 * 1024 MaxPixels = 40_000_000 ) var ( ErrInvalidImage = errors.New("invalid image") ErrResourceLimit = errors.New("image processing resource limit") ) type File struct { Path string Variant model.AttachmentVariant } type variantSpec struct { name, extension, mime string width, height int args []string } func Generate(ctx context.Context, dir, input, mime string, version int32) ([]File, error) { var jpegQuality, webpQuality string switch version { case 1: jpegQuality, webpQuality = "85", "80" case 2: jpegQuality, webpQuality = "90", "72" default: return nil, fmt.Errorf("unsupported image pipeline version %d", version) } f, err := os.Open(input) if err != nil { return nil, err } cfg, format, decodeErr := image.DecodeConfig(io.LimitReader(f, MaxBytes)) _ = f.Close() if decodeErr != nil || (format != "png" && format != "jpeg") || mime != "image/"+format || cfg.Width <= 0 || cfg.Height <= 0 || cfg.Width > MaxPixels/cfg.Height { return nil, ErrInvalidImage } // Paths are generated on the server; input format is independently verified. source := format + ":" + input orient, err := magick(ctx, "identify", "-ping", "-format", "%[orientation]", source) if err != nil { return nil, err } w, h := cfg.Width, cfg.Height switch strings.TrimSpace(orient) { case "LeftTop", "RightTop", "RightBottom", "LeftBottom": w, h = h, w } tw, th := fit(w, h, 256) ow, oh := fit(w, h, 1280) side := min(w, h) specs := []variantSpec{ {name: "thumbnail", extension: "jpg", mime: "image/jpeg", width: tw, height: th, args: []string{"-resize", geometry(tw, th), "-quality", jpegQuality}}, {name: "crop", extension: "jpg", mime: "image/jpeg", width: 128, height: 128, args: []string{"-gravity", "center", "-crop", fmt.Sprintf("%dx%d+0+0", side, side), "+repage", "-resize", "128x128!", "-quality", jpegQuality}}, {name: "optimized", extension: "webp", mime: "image/webp", width: ow, height: oh, args: []string{"-resize", geometry(ow, oh), "-quality", webpQuality, "-define", "webp:method=4"}}, } files := make([]File, 0, len(specs)) for _, spec := range specs { out := filepath.Join(dir, spec.name+"."+spec.extension) args := []string{"-regard-warnings", source, "-auto-orient"} if spec.mime == "image/jpeg" { args = append(args, "-background", "white", "-alpha", "remove", "-alpha", "off") } args = append(args, spec.args...) args = append(args, "-strip", out) if _, err := magick(ctx, args...); err != nil { return nil, err } meta, err := inspectFile(ctx, out, spec) if err != nil { return nil, err } files = append(files, File{Path: out, Variant: meta}) } return files, nil } func fit(w, h, bound int) (int, int) { if max(w, h) <= bound { return w, h } if w >= h { return bound, max(1, h*bound/w) } return max(1, w*bound/h), bound } func geometry(w, h int) string { return fmt.Sprintf("%dx%d!", w, h) } func inspectFile(ctx context.Context, path string, spec variantSpec) (model.AttachmentVariant, error) { var meta model.AttachmentVariant desc, err := magick(ctx, "identify", "-ping", "-format", "%m %w %h", path) if err != nil { return meta, err } format := strings.ToUpper(strings.TrimPrefix(spec.mime, "image/")) if strings.TrimSpace(desc) != format+" "+strconv.Itoa(spec.width)+" "+strconv.Itoa(spec.height) { return meta, fmt.Errorf("generated variant has unexpected format or size") } f, err := os.Open(path) if err != nil { return meta, err } defer f.Close() sum := sha256.New() size, err := io.Copy(sum, f) if err != nil { return meta, err } return model.AttachmentVariant{Name: spec.name, ContentType: spec.mime, Width: spec.width, Height: spec.height, SizeBytes: size, SHA256: hex.EncodeToString(sum.Sum(nil))}, nil } func magick(ctx context.Context, args ...string) (string, error) { cmd := exec.CommandContext(ctx, "magick", args...) out, err := cmd.CombinedOutput() if ctx.Err() != nil { return "", ctx.Err() } if err == nil { return string(out), nil } message := strings.ToLower(string(out)) if strings.Contains(message, "cache resources exhausted") || strings.Contains(message, "time limit") || strings.Contains(message, "memory allocation") || strings.Contains(message, "list length exceeds") { return "", ErrResourceLimit } if strings.Contains(message, "corrupt") || strings.Contains(message, "unexpected end") || strings.Contains(message, "insufficient image data") || strings.Contains(message, "decode") { return "", ErrInvalidImage } return "", fmt.Errorf("ImageMagick command failed: %w", err) }