Skip to content

GOWA - WhatsApp REST API with support for UI, Multi Account, Webhooks, and MCP, and Chatwoot. Built with Golang for efficient memory use.

Add video sending from URL (#315)

Aldino Kemalc1ff9c71a345
diff --git a/docs/openapi.yaml b/docs/openapi.yaml
index 3935f277..46a87d16 100644
--- a/docs/openapi.yaml
+++ b/docs/openapi.yaml
@@ -1,7 +1,7 @@
openapi: "3.0.0"
info:
title: WhatsApp API MultiDevice
- version: 6.2.0
+ version: 6.3.0
description: This API is used for sending whatsapp via API
servers:
- url: http://localhost:3000
@@ -609,6 +609,10 @@ paths:
type: string
format: binary
description: Video to send
+ video_url:
+ type: string
+ example: https://example.com/sample.mp4
+ description: Video URL to send
compress:
type: boolean
example: false
diff --git a/src/domains/send/video.go b/src/domains/send/video.go
index 818a9e47..4ce4bb83 100644
--- a/src/domains/send/video.go
+++ b/src/domains/send/video.go
@@ -9,4 +9,5 @@ type VideoRequest struct {
ViewOnce bool `json:"view_once" form:"view_once"`
Compress bool `json:"compress"`
IsForwarded bool `json:"is_forwarded" form:"is_forwarded"`
+ VideoURL *string `json:"video_url" form:"video_url"`
}
diff --git a/src/pkg/utils/general.go b/src/pkg/utils/general.go
index 60475a78..ba93e57a 100644
--- a/src/pkg/utils/general.go
+++ b/src/pkg/utils/general.go
@@ -368,3 +368,73 @@ func DownloadAudioFromURL(audioURL string) ([]byte, string, error) {
return audioData, fileName, nil
}
+
+// DownloadVideoFromURL downloads a video file from the provided URL and returns the bytes and sanitized filename.
+// It validates that the content-type returned by the server is one of the supported WhatsApp video formats and
+// that the size does not exceed WhatsappSettingMaxDownloadSize to avoid memory exhaustion.
+func DownloadVideoFromURL(videoURL string) ([]byte, string, error) {
+ client := &http.Client{
+ Timeout: 30 * time.Second,
+ CheckRedirect: func(req *http.Request, via []*http.Request) error {
+ if len(via) >= 10 {
+ return fmt.Errorf("too many redirects")
+ }
+ return nil
+ },
+ }
+
+ resp, err := client.Get(videoURL)
+ if err != nil {
+ return nil, "", err
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != http.StatusOK {
+ return nil, "", fmt.Errorf("HTTP request failed with status: %s", resp.Status)
+ }
+
+ // Extract MIME type without parameters
+ contentType := strings.TrimSpace(strings.Split(resp.Header.Get("Content-Type"), ";")[0])
+
+ allowedMimes := map[string]bool{
+ "video/mp4": true,
+ "video/x-matroska": true, // mkv
+ "video/avi": true,
+ "video/x-msvideo": true,
+ }
+
+ if !allowedMimes[contentType] {
+ return nil, "", fmt.Errorf("invalid content type: %s", contentType)
+ }
+
+ // Validate content length if provided
+ maxSize := config.WhatsappSettingMaxDownloadSize
+ if resp.ContentLength > 0 && resp.ContentLength > maxSize {
+ return nil, "", fmt.Errorf("video size %d exceeds maximum allowed size %d", resp.ContentLength, maxSize)
+ }
+
+ // Guard against unknown Content-Length by limiting reader
+ limit := maxSize
+ if limit < math.MaxInt64 {
+ limit++
+ }
+
+ limitedReader := &io.LimitedReader{R: resp.Body, N: limit}
+ videoData, err := io.ReadAll(limitedReader)
+ if err != nil {
+ return nil, "", err
+ }
+ if int64(len(videoData)) > maxSize {
+ return nil, "", fmt.Errorf("downloaded video size of %d bytes exceeds the maximum allowed size of %d bytes", len(videoData), maxSize)
+ }
+
+ // Derive filename from URL path
+ segments := strings.Split(videoURL, "/")
+ fileName := segments[len(segments)-1]
+ fileName = strings.Split(fileName, "?")[0]
+ if fileName == "" {
+ fileName = fmt.Sprintf("video_%d.mp4", time.Now().Unix())
+ }
+
+ return videoData, fileName, nil
+}
diff --git a/src/ui/rest/send.go b/src/ui/rest/send.go
index 247b2f3f..64836191 100644
--- a/src/ui/rest/send.go
+++ b/src/ui/rest/send.go
@@ -96,10 +96,11 @@ func (controller *Send) SendVideo(c *fiber.Ctx) error {
err := c.BodyParser(&request)
utils.PanicIfNeeded(err)
- video, err := c.FormFile("video")
- utils.PanicIfNeeded(err)
+ // Try to get file but ignore error if not provided
+ if videoFile, errFile := c.FormFile("video"); errFile == nil {
+ request.Video = videoFile
+ }
- request.Video = video
whatsapp.SanitizePhone(&request.Phone)
response, err := controller.Service.SendVideo(c.UserContext(), request)
diff --git a/src/usecase/send.go b/src/usecase/send.go
index 3cef08ce..e9a945ca 100644
--- a/src/usecase/send.go
+++ b/src/usecase/send.go
@@ -309,12 +309,40 @@ func (service serviceSend) SendVideo(ctx context.Context, request domainSend.Vid
deletedItems []string
)
+ // Ensure temporary files are always removed, even on early returns
+ defer func() {
+ if len(deletedItems) > 0 {
+ // Run cleanup in background with slight delay to avoid race with open handles
+ go utils.RemoveFile(1, deletedItems...)
+ }
+ }()
+
generateUUID := fiberUtils.UUIDv4()
- // Save video to server
- oriVideoPath := fmt.Sprintf("%s/%s", config.PathSendItems, generateUUID+request.Video.Filename)
- err = fasthttp.SaveMultipartFile(request.Video, oriVideoPath)
- if err != nil {
- return response, pkgError.InternalServerError(fmt.Sprintf("failed to store video in server %v", err))
+
+ var oriVideoPath string
+
+ // Determine source of video (URL or uploaded file)
+ if request.VideoURL != nil && *request.VideoURL != "" {
+ // Download video bytes
+ videoBytes, fileName, errDownload := utils.DownloadVideoFromURL(*request.VideoURL)
+ if errDownload != nil {
+ return response, pkgError.InternalServerError(fmt.Sprintf("failed to download video from URL %v", errDownload))
+ }
+ // Build file path to save the downloaded video temporarily
+ oriVideoPath = fmt.Sprintf("%s/%s", config.PathSendItems, generateUUID+fileName)
+ if errWrite := os.WriteFile(oriVideoPath, videoBytes, 0644); errWrite != nil {
+ return response, pkgError.InternalServerError(fmt.Sprintf("failed to store downloaded video in server %v", errWrite))
+ }
+ } else if request.Video != nil {
+ // Save uploaded video to server
+ oriVideoPath = fmt.Sprintf("%s/%s", config.PathSendItems, generateUUID+request.Video.Filename)
+ err = fasthttp.SaveMultipartFile(request.Video, oriVideoPath)
+ if err != nil {
+ return response, pkgError.InternalServerError(fmt.Sprintf("failed to store video in server %v", err))
+ }
+ } else {
+ // This should not happen due to validation, but guard anyway
+ return response, pkgError.ValidationError("either Video or VideoURL must be provided")
}
// Check if ffmpeg is installed
@@ -323,7 +351,7 @@ func (service serviceSend) SendVideo(ctx context.Context, request domainSend.Vid
return response, pkgError.InternalServerError("ffmpeg not installed")
}
- // Get thumbnail video with ffmpeg
+ // Generate thumbnail using ffmpeg
thumbnailVideoPath := fmt.Sprintf("%s/%s", config.PathSendItems, generateUUID+".png")
cmdThumbnail := exec.Command("ffmpeg", "-i", oriVideoPath, "-ss", "00:00:01.000", "-vframes", "1", thumbnailVideoPath)
err = cmdThumbnail.Run()
@@ -346,21 +374,41 @@ func (service serviceSend) SendVideo(ctx context.Context, request domainSend.Vid
deletedItems = append(deletedItems, thumbnailResizeVideoPath)
videoThumbnail = thumbnailResizeVideoPath
+ // Compress if requested
if request.Compress {
compresVideoPath := fmt.Sprintf("%s/%s", config.PathSendItems, generateUUID+".mp4")
- cmdCompress := exec.Command("ffmpeg", "-i", oriVideoPath, "-strict", "-2", compresVideoPath)
- err = cmdCompress.Run()
+ // 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()
if err != nil {
- return response, pkgError.InternalServerError("failed to compress video")
+ 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)
} else {
videoPath = oriVideoPath
- deletedItems = append(deletedItems, oriVideoPath)
}
+ deletedItems = append(deletedItems, oriVideoPath)
//Send to WA server
dataWaVideo, err := os.ReadFile(videoPath)
@@ -404,12 +452,6 @@ func (service serviceSend) SendVideo(ctx context.Context, request domainSend.Vid
caption = "🎥 " + request.Caption
}
ts, err := service.wrapSendMessage(ctx, dataWaRecipient, msg, caption)
- go func() {
- errDelete := utils.RemoveFile(1, deletedItems...)
- if errDelete != nil {
- logrus.Infof("error when deleting picture: %v", errDelete)
- }
- }()
if err != nil {
return response, err
}
diff --git a/src/validations/send_validation.go b/src/validations/send_validation.go
index 83600245..d2d8680a 100644
--- a/src/validations/send_validation.go
+++ b/src/validations/send_validation.go
@@ -83,28 +83,48 @@ func ValidateSendFile(ctx context.Context, request domainSend.FileRequest) error
}
func ValidateSendVideo(ctx context.Context, request domainSend.VideoRequest) error {
+ // Validate common required fields
err := validation.ValidateStructWithContext(ctx, &request,
validation.Field(&request.Phone, validation.Required),
- validation.Field(&request.Video, validation.Required),
)
if err != nil {
return pkgError.ValidationError(err.Error())
}
- availableMimes := map[string]bool{
- "video/mp4": true,
- "video/x-matroska": true,
- "video/avi": true,
+ // Ensure at least one of Video or VideoURL is provided
+ if request.Video == nil && (request.VideoURL == nil || *request.VideoURL == "") {
+ return pkgError.ValidationError("either Video or VideoURL must be provided")
}
- if !availableMimes[request.Video.Header.Get("Content-Type")] {
- return pkgError.ValidationError("your video type is not allowed. please use mp4/mkv/avi")
+ // If Video file provided perform MIME / size validation
+ if request.Video != nil {
+ availableMimes := map[string]bool{
+ "video/mp4": true,
+ "video/x-matroska": true,
+ "video/avi": true,
+ "video/x-msvideo": true,
+ }
+
+ if !availableMimes[request.Video.Header.Get("Content-Type")] {
+ return pkgError.ValidationError("your video type is not allowed. please use mp4/mkv/avi/x-msvideo")
+ }
+
+ if request.Video.Size > config.WhatsappSettingMaxVideoSize { // 30MB
+ maxSizeString := humanize.Bytes(uint64(config.WhatsappSettingMaxVideoSize))
+ return pkgError.ValidationError(fmt.Sprintf("max video upload is %s, please upload in cloud and send via text if your file is higher than %s", maxSizeString, maxSizeString))
+ }
}
- if request.Video.Size > config.WhatsappSettingMaxVideoSize { // 30MB
- maxSizeString := humanize.Bytes(uint64(config.WhatsappSettingMaxVideoSize))
- return pkgError.ValidationError(fmt.Sprintf("max video upload is %s, please upload in cloud and send via text if your file is higher than %s", maxSizeString, maxSizeString))
+ // If VideoURL provided, validate url
+ if request.VideoURL != nil {
+ if *request.VideoURL == "" {
+ return pkgError.ValidationError("VideoURL cannot be empty")
+ }
+
+ if err := validation.Validate(*request.VideoURL, is.URL); err != nil {
+ return pkgError.ValidationError("VideoURL must be a valid URL")
+ }
}
return nil
diff --git a/src/validations/send_validation_test.go b/src/validations/send_validation_test.go
index cccf4635..ef3bf82a 100644
--- a/src/validations/send_validation_test.go
+++ b/src/validations/send_validation_test.go
@@ -211,7 +211,7 @@ func TestValidateSendVideo(t *testing.T) {
ViewOnce: false,
Compress: false,
}},
- err: pkgError.ValidationError("video: cannot be blank."),
+ err: pkgError.ValidationError("either Video or VideoURL must be provided"),
},
{
name: "should error with invalid format video",
@@ -228,7 +228,31 @@ func TestValidateSendVideo(t *testing.T) {
ViewOnce: false,
Compress: false,
}},
- err: pkgError.ValidationError("your video type is not allowed. please use mp4/mkv/avi"),
+ err: pkgError.ValidationError("your video type is not allowed. please use mp4/mkv/avi/x-msvideo"),
+ },
+ {
+ name: "should error with empty video and video_url",
+ args: args{request: domainSend.VideoRequest{
+ Phone: "[email protected]",
+ Caption: "simple caption",
+ Video: nil,
+ VideoURL: func() *string { s := ""; return &s }(),
+ ViewOnce: false,
+ Compress: false,
+ }},
+ err: pkgError.ValidationError("either Video or VideoURL must be provided"),
+ },
+ {
+ name: "should success with video_url provided",
+ args: args{request: domainSend.VideoRequest{
+ Phone: "[email protected]",
+ Caption: "simple caption",
+ Video: nil,
+ VideoURL: func() *string { s := "https://example.com/sample.mp4"; return &s }(),
+ ViewOnce: false,
+ Compress: false,
+ }},
+ err: nil,
},
}
@@ -567,7 +591,7 @@ func TestValidateSendAudio(t *testing.T) {
Audio: nil,
}},
- err: pkgError.ValidationError("audio: cannot be blank."),
+ err: pkgError.ValidationError("either Audio or AudioURL must be provided"),
},
{
name: "should error with invalid audio type",
diff --git a/src/views/components/SendVideo.js b/src/views/components/SendVideo.js
index d4b0ea15..0211ff9b 100644
--- a/src/views/components/SendVideo.js
+++ b/src/views/components/SendVideo.js
@@ -19,6 +19,7 @@ export default {
type: window.TYPEUSER,
phone: '',
loading: false,
+ video_url: null,
selectedFileName: null,
is_forwarded: false
}
@@ -55,15 +56,16 @@ export default {
}
const fileInput = $("#file_video")[0];
- if (!fileInput || !fileInput.files || !fileInput.files[0]) {
- console.log('fileInput', fileInput);
+ const hasFile = fileInput && fileInput.files && fileInput.files[0];
+
+ if (!hasFile && !this.video_url) {
isValid = false;
- } else {
+ }
+
+ if (hasFile) {
const videoFile = fileInput.files[0];
- // Validate file type
if (!videoFile.type.startsWith('video/')) {
isValid = false;
- console.log('videoFile', videoFile);
}
}
@@ -91,7 +93,15 @@ export default {
payload.append("view_once", this.view_once)
payload.append("compress", this.compress)
payload.append("is_forwarded", this.is_forwarded)
- payload.append('video', $("#file_video")[0].files[0])
+
+ const fileInput = $("#file_video")[0];
+ if (fileInput && fileInput.files && fileInput.files[0]) {
+ payload.append('video', fileInput.files[0])
+ }
+ if (this.video_url) {
+ payload.append('video_url', this.video_url)
+ }
+
let response = await window.http.post(`/send/video`, payload)
this.handleReset();
return response.data.message;
@@ -110,6 +120,7 @@ export default {
this.compress = false;
this.phone = '';
this.selectedFileName = null;
+ this.video_url = null;
this.is_forwarded = false;
$("#file_video").val('');
},
@@ -170,7 +181,13 @@ export default {
<label>Mark video as forwarded</label>
</div>
</div>
- <div class="field" style="padding-bottom: 30px">
+ <div class="field">
+ <label>Video URL</label>
+ <input type="text" v-model="video_url" placeholder="https://example.com/sample.mp4"
+ aria-label="video_url" />
+ </div>
+ <div style="text-align: left; font-weight: bold; margin: 10px 0;" v-if="!video_url">or you can upload video from your device</div>
+ <div class="field" style="padding-bottom: 30px" v-if="!video_url">
<label>Video</label>
<input type="file" style="display: none" accept="video/*" id="file_video" @change="handleFileChange">
<label for="file_video" class="ui positive medium green left floated button" style="color: white">