GOWA - WhatsApp REST API with support for UI, Multi Account, Webhooks, and MCP, and Chatwoot. Built with Golang for efficient memory use.
Go botgogolanggolang-whatsappgolang-whatsapp-apirestrest-apiwhatsappwhatsapp-apiwhatsapp-api-gowhatsapp-multi-devicewhatsapp-web-multi-device
feat(send): add HD photo and video quality (#809)
Aldino Kemal5d481a7cc4e7
diff --git a/docs/openapi.yaml b/docs/openapi.yamlindex 36b6dbe8..c484dfea 100644--- a/docs/openapi.yaml+++ b/docs/openapi.yaml@@ -1310,6 +1310,10 @@ paths:type: booleanexample: falsedescription: Compress image+ hd:+ type: boolean+ example: true+ description: Send a high-definition image rendition (maximum edge 2560px). Overrides compress when true.duration:type: integerexample: 86400@@ -1555,6 +1559,10 @@ paths:type: booleanexample: falsedescription: Compress video+ hd:+ type: boolean+ example: true+ description: Send an H.264 8-bit YUV 4:2:0 high-definition video rendition at CRF 23, capped at 1280x1280 while preserving aspect ratio and avoiding upscaling. Overrides compress when true.gif_playback:type: booleanexample: falsediff --git a/src/domains/send/image.go b/src/domains/send/image.goindex 0df23046..a0e2ac88 100644--- a/src/domains/send/image.go+++ b/src/domains/send/image.go@@ -10,4 +10,5 @@ type ImageRequest struct {ImageURL *string `json:"image_url" form:"image_url"`ViewOnce bool `json:"view_once" form:"view_once"`Compress bool `json:"compress"`+ HD bool `json:"hd" form:"hd"`}diff --git a/src/domains/send/video.go b/src/domains/send/video.goindex 7ff77218..2e690cd8 100644--- a/src/domains/send/video.go+++ b/src/domains/send/video.go@@ -9,6 +9,7 @@ type VideoRequest struct {Video *multipart.FileHeader `json:"video" form:"video"`ViewOnce bool `json:"view_once" form:"view_once"`Compress bool `json:"compress"`+ HD bool `json:"hd" form:"hd"`GifPlayback bool `json:"gif_playback" form:"gif_playback"`VideoURL *string `json:"video_url" form:"video_url"`}diff --git a/src/ui/mcp/schemas.go b/src/ui/mcp/schemas.goindex 1dc00572..ca0af4e8 100644--- a/src/ui/mcp/schemas.go+++ b/src/ui/mcp/schemas.go@@ -19,6 +19,7 @@ const sendSchema = `{"caption": {"type": "string", "description": "image/video/document/link: caption text"},"view_once": {"type": "boolean", "description": "image/video: view-once message (default false)"},"compress": {"type": "boolean", "description": "image (default true) / video (default false): re-encode before sending"},+ "hd": {"type": "boolean", "description": "image/video: send HD without upscaling (image: 2560px max edge; video: H.264 8-bit YUV 4:2:0 at CRF 23, capped at 1280x1280); overrides compress when true (default false)"},"video_url": {"type": "string", "description": "type=video: URL of the video (mp4/mkv/avi, fetched server-side)"},"gif_playback": {"type": "boolean", "description": "type=video: play as looping GIF (default false)"},"audio_url": {"type": "string", "description": "type=audio: URL of the audio file (fetched server-side)"},diff --git a/src/ui/mcp/send.go b/src/ui/mcp/send.goindex 57869553..0221822a 100644--- a/src/ui/mcp/send.go+++ b/src/ui/mcp/send.go@@ -72,6 +72,7 @@ func (s *SendHandler) handleSend(ctx context.Context, request mcpg.CallToolRequeCaption: request.GetString("caption", ""),ViewOnce: request.GetBool("view_once", false),Compress: request.GetBool("compress", true),+ HD: request.GetBool("hd", false),})case "video":videoURL := request.GetString("video_url", "")@@ -82,6 +83,7 @@ func (s *SendHandler) handleSend(ctx context.Context, request mcpg.CallToolRequeViewOnce: request.GetBool("view_once", false),GifPlayback: request.GetBool("gif_playback", false),Compress: request.GetBool("compress", false),+ HD: request.GetBool("hd", false),})case "audio":audioURL := request.GetString("audio_url", "")diff --git a/src/ui/mcp/send_test.go b/src/ui/mcp/send_test.goindex 693a7d7a..cda013aa 100644--- a/src/ui/mcp/send_test.go+++ b/src/ui/mcp/send_test.go@@ -111,25 +111,27 @@ func TestHandleSendDispatch(t *testing.T) {h := InitMcpSend(svc, &stubResolver{})_, err := h.handleSend(deviceCtx(), callReq(map[string]any{"type": "image", "phone": "628", "image_url": "http://x/a.png",- "caption": "c", "view_once": true,+ "caption": "c", "view_once": true, "hd": true,}))require.NoError(t, err)require.NotNil(t, svc.lastImage)assert.Equal(t, "http://x/a.png", *svc.lastImage.ImageURL)assert.True(t, svc.lastImage.ViewOnce)assert.True(t, svc.lastImage.Compress) // image compress defaults true+ assert.True(t, svc.lastImage.HD)})t.Run("video", func(t *testing.T) {svc := &stubSendService{}h := InitMcpSend(svc, &stubResolver{})_, err := h.handleSend(deviceCtx(), callReq(map[string]any{- "type": "video", "phone": "628", "video_url": "http://x/a.mp4", "gif_playback": true,+ "type": "video", "phone": "628", "video_url": "http://x/a.mp4", "gif_playback": true, "hd": true,}))require.NoError(t, err)require.NotNil(t, svc.lastVideo)assert.True(t, svc.lastVideo.GifPlayback)assert.False(t, svc.lastVideo.Compress) // video compress defaults false+ assert.True(t, svc.lastVideo.HD)})t.Run("audio", func(t *testing.T) {diff --git a/src/usecase/send.go b/src/usecase/send.goindex 55fa5f21..729811c4 100644--- a/src/usecase/send.go+++ b/src/usecase/send.go@@ -3,8 +3,10 @@ package usecaseimport ("bytes""context"+ "encoding/json""errors""fmt"+ "image""math""mime""net/http"@@ -38,6 +40,133 @@ import (// webpCanvasSizeRegex is compiled once at package level for efficiencyvar webpCanvasSizeRegex = regexp.MustCompile(`Canvas size:\s*(\d+)\s*x\s*(\d+)`)+const hdImageMaxEdge = 2560++type videoMetadata struct {+ Width uint32+ Height uint32+ Seconds uint32+}++func resizeImageForHD(src image.Image) image.Image {+ return imaging.Fit(src, hdImageMaxEdge, hdImageMaxEdge, imaging.Lanczos)+}++func prepareImageForSend(src image.Image, compress, hd bool) (image.Image, bool) {+ if hd {+ return resizeImageForHD(src), true+ }+ if compress {+ return imaging.Resize(src, 600, 0, imaging.Lanczos), true+ }+ return src, false+}++func openImageForSend(imagePath string, hd bool) (image.Image, error) {+ return imaging.Open(imagePath, imaging.AutoOrientation(hd))+}++func saveProcessedImage(src image.Image, directory, imageName string, hd bool) (string, error) {+ prefix := "new-"+ var saveOptions []imaging.EncodeOption+ if hd {+ prefix = "hd-"+ imageName = strings.TrimSuffix(imageName, filepath.Ext(imageName)) + ".jpg"+ saveOptions = append(saveOptions, imaging.JPEGQuality(92))+ }+ processedImagePath := filepath.Join(directory, prefix+imageName)+ return processedImagePath, imaging.Save(src, processedImagePath, saveOptions...)+}++func buildHDVideoFFmpegArgs(inputPath, outputPath string) []string {+ return []string{+ "-i", inputPath,+ "-c:v", "libx264",+ "-crf", "23",+ "-preset", "fast",+ "-vf", "scale='min(1280,iw)':'min(1280,ih)':force_original_aspect_ratio=decrease:force_divisible_by=2",+ "-pix_fmt", "yuv420p",+ "-c:a", "aac",+ "-b:a", "128k",+ "-movflags", "+faststart",+ "-y",+ outputPath,+ }+}++func buildVideoTranscodeArgs(inputPath, outputPath string, compress, hd bool) ([]string, bool) {+ if hd {+ return buildHDVideoFFmpegArgs(inputPath, outputPath), true+ }+ if !compress {+ return nil, false+ }+ return []string{+ "-i", inputPath,+ "-c:v", "libx264",+ "-crf", "28",+ "-preset", "fast",+ "-vf", "scale=720:-2",+ "-c:a", "aac",+ "-b:a", "128k",+ "-movflags", "+faststart",+ "-y",+ outputPath,+ }, true+}++func parseVideoMetadata(data []byte) (videoMetadata, error) {+ var probe struct {+ Streams []struct {+ Width uint32 `json:"width"`+ Height uint32 `json:"height"`+ Duration string `json:"duration"`+ } `json:"streams"`+ Format struct {+ Duration string `json:"duration"`+ } `json:"format"`+ }+ if err := json.Unmarshal(data, &probe); err != nil {+ return videoMetadata{}, err+ }++ var metadata videoMetadata+ if len(probe.Streams) > 0 {+ metadata.Width = probe.Streams[0].Width+ metadata.Height = probe.Streams[0].Height+ }+ durationText := probe.Format.Duration+ if durationText == "" || durationText == "N/A" {+ if len(probe.Streams) > 0 {+ durationText = probe.Streams[0].Duration+ }+ }+ if duration, err := strconv.ParseFloat(durationText, 64); err == nil && duration > 0 {+ metadata.Seconds = uint32(duration)+ }+ return metadata, nil+}++func getVideoMetadata(videoPath string) videoMetadata {+ output, err := runFFProbe(+ "-v", "error",+ "-select_streams", "v:0",+ "-show_entries", "stream=width,height,duration:format=duration",+ "-of", "json",+ videoPath,+ )+ if err != nil {+ logrus.Warnf("Failed to get video metadata: %v", err)+ return videoMetadata{}+ }+ metadata, err := parseVideoMetadata(output)+ if err != nil {+ logrus.Warnf("Failed to parse video metadata: %v", err)+ return videoMetadata{}+ }+ return metadata+}+type serviceSend struct {appService app.IAppUsecasechatStorageRepo domainChatStorage.IChatStorageRepository@@ -268,7 +397,7 @@ func (service serviceSend) SendImage(ctx context.Context, request domainSend.ImadeletedItems = append(deletedItems, oriImagePath)/* Generate thumbnail with smalled image size */- srcImage, err := imaging.Open(oriImagePath)+ srcImage, err := openImageForSend(oriImagePath, request.HD)if err != nil {return response, pkgError.InternalServerError(fmt.Sprintf("Failed to open image file '%s' for thumbnail generation: %v. Possible causes: file not found, unsupported format, or permission denied.", oriImagePath, err))}@@ -281,19 +410,14 @@ func (service serviceSend) SendImage(ctx context.Context, request domainSend.Ima}deletedItems = append(deletedItems, imageThumbnail)- if request.Compress {- // Resize image- openImageBuffer, err := imaging.Open(oriImagePath)- if err != nil {- return response, pkgError.InternalServerError(fmt.Sprintf("Failed to open image file '%s' for compression: %v. Possible causes: file not found, unsupported format, or permission denied.", oriImagePath, err))+ preparedImage, processed := prepareImageForSend(srcImage, request.Compress, request.HD)+ if processed {+ processedImagePath, saveErr := saveProcessedImage(preparedImage, config.PathSendItems, imageName, request.HD)+ if saveErr != nil {+ return response, pkgError.InternalServerError(fmt.Sprintf("failed to save processed image %v", saveErr))}- newImage := imaging.Resize(openImageBuffer, 600, 0, imaging.Lanczos)- newImagePath := fmt.Sprintf("%s/new-%s", config.PathSendItems, imageName)- if err = imaging.Save(newImage, newImagePath); err != nil {- return response, pkgError.InternalServerError(fmt.Sprintf("failed to save image %v", err))- }- deletedItems = append(deletedItems, newImagePath)- imagePath = newImagePath+ deletedItems = append(deletedItems, processedImagePath)+ imagePath = processedImagePath} else {imagePath = oriImagePath}@@ -304,6 +428,10 @@ func (service serviceSend) SendImage(ctx context.Context, request domainSend.Imaif err != nil {return response, err}+ imageConfig, _, err := image.DecodeConfig(bytes.NewReader(dataWaImage))+ if err != nil {+ return response, pkgError.InternalServerError(fmt.Sprintf("failed to read sent image dimensions %v", err))+ }uploadedImage, err := service.uploadMedia(ctx, client, whatsmeow.MediaImage, dataWaImage, dataWaRecipient)if err != nil {fmt.Printf("failed to upload file: %v", err)@@ -324,6 +452,8 @@ func (service serviceSend) SendImage(ctx context.Context, request domainSend.ImaFileEncSHA256: uploadedImage.FileEncSHA256,FileSHA256: uploadedImage.FileSHA256,FileLength: proto.Uint64(uint64(len(dataWaImage))),+ Width: proto.Uint32(uint32(imageConfig.Width)),+ Height: proto.Uint32(uint32(imageConfig.Height)),ViewOnce: proto.Bool(request.ViewOnce),}}@@ -813,37 +943,21 @@ func (service serviceSend) SendVideo(ctx context.Context, request domainSend.ViddeletedItems = append(deletedItems, thumbnailResizeVideoPath)videoThumbnail = thumbnailResizeVideoPath- // Compress if requested- if request.Compress {- compresVideoPath := fmt.Sprintf("%s/%s", config.PathSendItems, generateUUID+".mp4")-- // Use proper compression settings to reduce file size- // -crf 28: Constant Rate Factor (18-28 is good range, higher = smaller file)- // -preset medium: Balance between encoding speed and compression efficiency- // -c:v libx264: Use H.264 codec for video- // -c:a aac: Use AAC codec for audio- // -movflags +faststart: Optimize for web streaming- // -vf scale=720:-2: Scale video to max width 720px, maintain aspect ratio- cmdCompress := exec.Command("ffmpeg", "-i", oriVideoPath,- "-c:v", "libx264",- "-crf", "28",- "-preset", "fast",- "-vf", "scale=720:-2",- "-c:a", "aac",- "-b:a", "128k",- "-movflags", "+faststart",- "-y", // Overwrite output file if it exists- compresVideoPath)-- // Capture both stdout and stderr for better error reporting- output, err := cmdCompress.CombinedOutput()+ transcodedVideoPath := fmt.Sprintf("%s/%s.mp4", config.PathSendItems, generateUUID)+ transcodeArgs, shouldTranscode := buildVideoTranscodeArgs(oriVideoPath, transcodedVideoPath, request.Compress, request.HD)+ if shouldTranscode {+ cmdTranscode := exec.Command("ffmpeg", transcodeArgs...)+ output, err := cmdTranscode.CombinedOutput()if err != nil {+ if request.HD {+ logrus.Errorf("ffmpeg HD conversion failed: %v, output: %s", err, string(output))+ return response, pkgError.InternalServerError(fmt.Sprintf("failed to convert video to HD: %v", err))+ }logrus.Errorf("ffmpeg compression failed: %v, output: %s", err, string(output))return response, pkgError.InternalServerError(fmt.Sprintf("failed to compress video: %v", err))}-- videoPath = compresVideoPath- deletedItems = append(deletedItems, compresVideoPath)+ videoPath = transcodedVideoPath+ deletedItems = append(deletedItems, transcodedVideoPath)} else {videoPath = oriVideoPath}@@ -854,6 +968,7 @@ func (service serviceSend) SendVideo(ctx context.Context, request domainSend.Vidif err != nil {return response, err}+ metadata := getVideoMetadata(videoPath)uploaded, err := service.uploadMedia(ctx, client, whatsmeow.MediaVideo, dataWaVideo, dataWaRecipient)if err != nil {return response, pkgError.InternalServerError(fmt.Sprintf("Failed to upload file: %v", err))@@ -879,6 +994,15 @@ func (service serviceSend) SendVideo(ctx context.Context, request domainSend.VidThumbnailSHA256: dataWaThumbnail,ThumbnailDirectPath: proto.String(uploaded.DirectPath),}}+ if metadata.Width > 0 {+ msg.VideoMessage.Width = proto.Uint32(metadata.Width)+ }+ if metadata.Height > 0 {+ msg.VideoMessage.Height = proto.Uint32(metadata.Height)+ }+ if metadata.Seconds > 0 {+ msg.VideoMessage.Seconds = proto.Uint32(metadata.Seconds)+ }if request.BaseRequest.IsForwarded {msg.VideoMessage.ContextInfo = &waE2E.ContextInfo{diff --git a/src/usecase/send_test.go b/src/usecase/send_test.goindex 21a0e67c..47642989 100644--- a/src/usecase/send_test.go+++ b/src/usecase/send_test.go@@ -1,9 +1,14 @@package usecaseimport (+ "bytes""context""errors"+ "image"+ "image/jpeg""net/http"+ "os"+ "path/filepath""testing"domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"@@ -11,11 +16,178 @@ import ("github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/whatsapp"pkgError "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/error""github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require""go.mau.fi/whatsmeow""go.mau.fi/whatsmeow/proto/waE2E""google.golang.org/protobuf/proto")+func writeOrientedJPEG(t *testing.T, path string, orientation byte) {+ t.Helper()+ var encoded bytes.Buffer+ require.NoError(t, jpeg.Encode(&encoded, image.NewRGBA(image.Rect(0, 0, 2, 3)), &jpeg.Options{Quality: 100}))++ // Minimal little-endian EXIF APP1 segment containing only Orientation.+ exif := []byte{+ 0xff, 0xe1, 0x00, 0x22,+ 'E', 'x', 'i', 'f', 0x00, 0x00,+ 'I', 'I', 0x2a, 0x00, 0x08, 0x00, 0x00, 0x00,+ 0x01, 0x00,+ 0x12, 0x01, 0x03, 0x00, 0x01, 0x00, 0x00, 0x00,+ orientation, 0x00, 0x00, 0x00,+ 0x00, 0x00, 0x00, 0x00,+ }+ jpegData := encoded.Bytes()+ fixture := make([]byte, 0, len(jpegData)+len(exif))+ fixture = append(fixture, jpegData[:2]...)+ fixture = append(fixture, exif...)+ fixture = append(fixture, jpegData[2:]...)+ require.NoError(t, os.WriteFile(path, fixture, 0600))+}++func TestOpenImageForSendAppliesEXIFOrientationForHD(t *testing.T) {+ path := filepath.Join(t.TempDir(), "orientation-6.jpg")+ writeOrientedJPEG(t, path, 6)++ got, err := openImageForSend(path, true)+ require.NoError(t, err)+ assert.Equal(t, 3, got.Bounds().Dx())+ assert.Equal(t, 2, got.Bounds().Dy())+}++func TestSaveProcessedImageUsesJPEGForHDPNG(t *testing.T) {+ directory := t.TempDir()+ gotPath, err := saveProcessedImage(image.NewRGBA(image.Rect(0, 0, 32, 16)), directory, "report.png", true)+ assert.NoError(t, err)+ assert.Equal(t, filepath.Join(directory, "hd-report.jpg"), gotPath)++ data, err := os.ReadFile(gotPath)+ assert.NoError(t, err)+ assert.Equal(t, "image/jpeg", http.DetectContentType(data))+}++func TestResizeImageForHDCapsLongestEdgeWithoutUpscaling(t *testing.T) {+ tests := []struct {+ name string+ width int+ height int+ wantWidth int+ wantHeight int+ }{+ {name: "landscape", width: 4000, height: 2000, wantWidth: 2560, wantHeight: 1280},+ {name: "portrait", width: 2000, height: 4000, wantWidth: 1280, wantHeight: 2560},+ {name: "small image is not upscaled", width: 1200, height: 800, wantWidth: 1200, wantHeight: 800},+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ got := resizeImageForHD(image.NewRGBA(image.Rect(0, 0, tt.width, tt.height)))+ assert.Equal(t, tt.wantWidth, got.Bounds().Dx())+ assert.Equal(t, tt.wantHeight, got.Bounds().Dy())+ })+ }+}++func TestPrepareImageForSendSelectsRequestedQuality(t *testing.T) {+ source := image.NewRGBA(image.Rect(0, 0, 3000, 1500))+ tests := []struct {+ name string+ compress bool+ hd bool+ wantWidth int+ wantHeight int+ wantProcessed bool+ }{+ {name: "HD overrides compression", compress: true, hd: true, wantWidth: 2560, wantHeight: 1280, wantProcessed: true},+ {name: "HD overrides original mode", compress: false, hd: true, wantWidth: 2560, wantHeight: 1280, wantProcessed: true},+ {name: "legacy compression stays unchanged", compress: true, wantWidth: 600, wantHeight: 300, wantProcessed: true},+ {name: "original mode stays unchanged", wantWidth: 3000, wantHeight: 1500, wantProcessed: false},+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ got, processed := prepareImageForSend(source, tt.compress, tt.hd)+ assert.Equal(t, tt.wantWidth, got.Bounds().Dx())+ assert.Equal(t, tt.wantHeight, got.Bounds().Dy())+ assert.Equal(t, tt.wantProcessed, processed)+ })+ }+}++func TestBuildHDVideoFFmpegArgsUses1280BoundingBoxWithoutUpscaling(t *testing.T) {+ want := []string{+ "-i", "input.mp4",+ "-c:v", "libx264",+ "-crf", "23",+ "-preset", "fast",+ "-vf", "scale='min(1280,iw)':'min(1280,ih)':force_original_aspect_ratio=decrease:force_divisible_by=2",+ "-pix_fmt", "yuv420p",+ "-c:a", "aac",+ "-b:a", "128k",+ "-movflags", "+faststart",+ "-y",+ "output.mp4",+ }++ assert.Equal(t, want, buildHDVideoFFmpegArgs("input.mp4", "output.mp4"))+}++func TestBuildVideoTranscodeArgsSelectsRequestedQuality(t *testing.T) {+ hdArgs := buildHDVideoFFmpegArgs("input.mp4", "output.mp4")+ legacyArgs := []string{+ "-i", "input.mp4",+ "-c:v", "libx264",+ "-crf", "28",+ "-preset", "fast",+ "-vf", "scale=720:-2",+ "-c:a", "aac",+ "-b:a", "128k",+ "-movflags", "+faststart",+ "-y",+ "output.mp4",+ }++ tests := []struct {+ name string+ compress bool+ hd bool+ wantArgs []string+ wantOutput bool+ }{+ {name: "HD overrides compression", compress: true, hd: true, wantArgs: hdArgs, wantOutput: true},+ {name: "HD overrides original mode", hd: true, wantArgs: hdArgs, wantOutput: true},+ {name: "legacy compression stays unchanged", compress: true, wantArgs: legacyArgs, wantOutput: true},+ {name: "original mode stays unchanged"},+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ gotArgs, gotOutput := buildVideoTranscodeArgs("input.mp4", "output.mp4", tt.compress, tt.hd)+ assert.Equal(t, tt.wantArgs, gotArgs)+ assert.Equal(t, tt.wantOutput, gotOutput)+ })+ }+}++func TestParseVideoMetadataUsesContainerDuration(t *testing.T) {+ metadata, err := parseVideoMetadata([]byte(`{+ "streams": [{"width": 1280, "height": 720}],+ "format": {"duration": "13.040000"}+ }`))+ assert.NoError(t, err)+ assert.Equal(t, videoMetadata{Width: 1280, Height: 720, Seconds: 13}, metadata)+}++func TestParseVideoMetadataFallsBackToStreamDuration(t *testing.T) {+ metadata, err := parseVideoMetadata([]byte(`{+ "streams": [{"width": 720, "height": 1280, "duration": "9.750000"}],+ "format": {"duration": "N/A"}+ }`))+ assert.NoError(t, err)+ assert.Equal(t, uint32(9), metadata.Seconds)+}+type replyMessageRepo struct {domainChatStorage.IChatStorageRepositorymessage *domainChatStorage.Message