package uploads import ( "bytes" "errors" "fmt" "image" _ "image/jpeg" _ "image/png" "os" "path/filepath" "strings" "github.com/HugoSmits86/nativewebp" "github.com/google/uuid" "golang.org/x/image/draw" _ "golang.org/x/image/webp" ) const ( MaxFileSizeBytes = 10 * 1024 * 1024 // 10 MB MaxImageWidth = 1920 ) type SavedFile struct { ArchivoRuta string // POSIX relative path: comprobantes//. ArchivoNombre string Mime string Tamano int } func RutaAbsoluta(uploadDir, relPath string) (string, error) { baseAbs, err := filepath.Abs(uploadDir) if err != nil { return "", err } cleanRel := filepath.FromSlash(strings.TrimPrefix(relPath, "/")) full := filepath.Clean(filepath.Join(baseAbs, cleanRel)) if full != baseAbs && !strings.HasPrefix(full, baseAbs+string(os.PathSeparator)) { return "", errors.New("ruta fuera de UPLOAD_DIR") } return full, nil } func GuardarComprobante(uploadDir, pagoID, originalName, contentType string, raw []byte) (*SavedFile, error) { if len(raw) == 0 { return nil, errors.New("archivo vacio") } if len(raw) > MaxFileSizeBytes { return nil, errors.New("el archivo excede el limite de 10 MB") } ct := strings.ToLower(strings.TrimSpace(strings.Split(contentType, ";")[0])) extOrig := strings.ToLower(filepath.Ext(originalName)) isPDF := ct == "application/pdf" || (ct == "" && extOrig == ".pdf") || (len(raw) >= 5 && string(raw[:5]) == "%PDF-") var finalBytes []byte var finalMime, finalExt string if isPDF { finalBytes = raw finalMime = "application/pdf" finalExt = ".pdf" } else if strings.HasPrefix(ct, "image/") || extOrig == ".jpg" || extOrig == ".jpeg" || extOrig == ".png" || extOrig == ".webp" { img, _, err := image.Decode(bytes.NewReader(raw)) if err != nil { return nil, fmt.Errorf("formato de imagen no soportado (usa JPG, PNG, WebP o PDF): %w", err) } img = resizeIfWider(img, MaxImageWidth) var buf bytes.Buffer if err := nativewebp.Encode(&buf, img, nil); err != nil { return nil, fmt.Errorf("error convirtiendo imagen a WebP: %w", err) } finalBytes = buf.Bytes() finalMime = "image/webp" finalExt = ".webp" } else { return nil, errors.New("tipo de archivo no permitido; sube una imagen (JPG, PNG, WebP) o PDF") } safePagoID := sanitizeSegment(pagoID) relPath := fmt.Sprintf("comprobantes/%s/%s%s", safePagoID, uuid.NewString(), finalExt) absPath, err := RutaAbsoluta(uploadDir, relPath) if err != nil { return nil, err } if err := os.MkdirAll(filepath.Dir(absPath), 0o755); err != nil { return nil, fmt.Errorf("error creando directorio de comprobantes: %w", err) } if err := os.WriteFile(absPath, finalBytes, 0o644); err != nil { return nil, fmt.Errorf("error guardando comprobante: %w", err) } nombre := strings.TrimSpace(originalName) if nombre == "" { nombre = "comprobante" + finalExt } return &SavedFile{ ArchivoRuta: relPath, ArchivoNombre: nombre, Mime: finalMime, Tamano: len(finalBytes), }, nil } func EliminarComprobante(uploadDir, relPath string) error { if strings.TrimSpace(relPath) == "" { return nil } absPath, err := RutaAbsoluta(uploadDir, relPath) if err != nil { return err } if err := os.Remove(absPath); err != nil && !os.IsNotExist(err) { return err } return nil } func resizeIfWider(src image.Image, maxW int) image.Image { b := src.Bounds() w := b.Dx() h := b.Dy() if w <= maxW || w <= 0 || h <= 0 { return src } newH := int(float64(h) * (float64(maxW) / float64(w))) if newH < 1 { newH = 1 } dst := image.NewRGBA(image.Rect(0, 0, maxW, newH)) draw.CatmullRom.Scale(dst, dst.Bounds(), src, b, draw.Over, nil) return dst } func sanitizeSegment(s string) string { var out strings.Builder for _, r := range s { if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r == '-' || r == '_' { out.WriteRune(r) } } if out.Len() == 0 { return "unknown" } return out.String() }