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: Support Send Audio from URL (#313)
Aldino Kemalfa509a6c1531
diff --git a/src/domains/send/audio.go b/src/domains/send/audio.goindex 5d370800..f3467aa5 100644--- a/src/domains/send/audio.go+++ b/src/domains/send/audio.go@@ -5,5 +5,6 @@ import "mime/multipart"type AudioRequest struct {Phone string `json:"phone" form:"phone"`Audio *multipart.FileHeader `json:"audio" form:"audio"`+ AudioURL *string `json:"audio_url" form:"audio_url"`IsForwarded bool `json:"is_forwarded" form:"is_forwarded"`}diff --git a/src/pkg/utils/general.go b/src/pkg/utils/general.goindex 30747a4e..60475a78 100644--- a/src/pkg/utils/general.go+++ b/src/pkg/utils/general.go@@ -8,6 +8,7 @@ import (_ "image/jpeg" // For JPEG encoding_ "image/png" // For PNG encoding"io"+ "math""net/http""net/url""os"@@ -246,6 +247,11 @@ func DownloadImageFromURL(url string) ([]byte, string, error) {return nil, "", err}defer response.Body.Close()++ if response.StatusCode != http.StatusOK {+ return nil, "", fmt.Errorf("HTTP request failed with status: %s", response.Status)+ }+contentType := response.Header.Get("Content-Type")if !strings.HasPrefix(contentType, "image/") {return nil, "", fmt.Errorf("invalid content type: %s", contentType)@@ -277,3 +283,88 @@ func DownloadImageFromURL(url string) ([]byte, string, error) {}return imageData, fileName, nil}++// DownloadAudioFromURL downloads an audio file from the provided URL and returns the bytes and sanitized filename.+// It validates that the content-type returned by the server starts with "audio/" and that the size is below+// WhatsappSettingMaxDownloadSize limit to avoid memory exhaustion. Only the MIME types defined in audio validation+// are allowed to ensure WhatsApp compatibility.+func DownloadAudioFromURL(audioURL 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(audioURL)+ 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 only the MIME type portion (ignore parameters like charset)+ contentType := strings.TrimSpace(strings.Split(resp.Header.Get("Content-Type"), ";")[0])++ // Align audio MIME validation with the one used for uploaded files to ensure consistency with WhatsApp requirements.+ allowedMimes := map[string]bool{+ "audio/aac": true,+ "audio/amr": true,+ "audio/flac": true,+ "audio/m4a": true,+ "audio/m4r": true,+ "audio/mp3": true,+ "audio/mpeg": true,+ "audio/ogg": true,+ "audio/wma": true,+ "audio/x-ms-wma": true,+ "audio/wav": true,+ "audio/vnd.wav": true,+ "audio/vnd.wave": true,+ "audio/wave": true,+ "audio/x-pn-wav": true,+ "audio/x-wav": true,+ }++ if !allowedMimes[contentType] {+ return nil, "", fmt.Errorf("invalid content type: %s", contentType)+ }++ // Validate content length when it is provided by the server.+ maxSize := config.WhatsappSettingMaxDownloadSize+ if resp.ContentLength > 0 && resp.ContentLength > maxSize {+ return nil, "", fmt.Errorf("audio size %d exceeds maximum allowed size %d", resp.ContentLength, maxSize)+ }++ // Guard against servers that do not set Content-Length by reading at most (maxSize+1) bytes+ // and erroring if the limit is exceeded.+ limit := maxSize+ if limit < math.MaxInt64 {+ limit+++ }++ limitedReader := &io.LimitedReader{R: resp.Body, N: limit}+ audioData, err := io.ReadAll(limitedReader)+ if err != nil {+ return nil, "", err+ }+ if int64(len(audioData)) > maxSize {+ return nil, "", fmt.Errorf("downloaded audio size of %d bytes exceeds the maximum allowed size of %d bytes", len(audioData), maxSize)+ }++ // Derive filename from URL path (strip query parameters if present)+ segments := strings.Split(audioURL, "/")+ fileName := segments[len(segments)-1]+ fileName = strings.Split(fileName, "?")[0]+ if fileName == "" {+ fileName = fmt.Sprintf("audio_%d", time.Now().Unix())+ }++ return audioData, fileName, nil+}diff --git a/src/ui/rest/send.go b/src/ui/rest/send.goindex 0e84e179..247b2f3f 100644--- a/src/ui/rest/send.go+++ b/src/ui/rest/send.go@@ -172,10 +172,11 @@ func (controller *Send) SendAudio(c *fiber.Ctx) error {err := c.BodyParser(&request)utils.PanicIfNeeded(err)- audio, err := c.FormFile("audio")- utils.PanicIfNeeded(err)+ // Try to get file but ignore error if not provided+ if audioFile, errFile := c.FormFile("audio"); errFile == nil {+ request.Audio = audioFile+ }- request.Audio = audiowhatsapp.SanitizePhone(&request.Phone)response, err := controller.Service.SendAudio(c.UserContext(), request)diff --git a/src/usecase/send.go b/src/usecase/send.goindex 35eaa23e..3cef08ce 100644--- a/src/usecase/send.go+++ b/src/usecase/send.go@@ -562,19 +562,36 @@ func (service serviceSend) SendLocation(ctx context.Context, request domainSend.}func (service serviceSend) SendAudio(ctx context.Context, request domainSend.AudioRequest) (response domainSend.GenericResponse, err error) {+ // Validate requesterr = validations.ValidateSendAudio(ctx, request)if err != nil {return response, err}+dataWaRecipient, err := whatsapp.ValidateJidWithLogin(service.WaCli, request.Phone)if err != nil {return response, err}- autioBytes := helpers.MultipartFormFileHeaderToBytes(request.Audio)- audioMimeType := http.DetectContentType(autioBytes)+ var (+ audioBytes []byte+ audioMimeType string+ )++ // Handle audio from URL or file+ if request.AudioURL != nil && *request.AudioURL != "" {+ audioBytes, _, err = utils.DownloadAudioFromURL(*request.AudioURL)+ if err != nil {+ return response, pkgError.InternalServerError(fmt.Sprintf("failed to download audio from URL %v", err))+ }+ audioMimeType = http.DetectContentType(audioBytes)+ } else if request.Audio != nil {+ audioBytes = helpers.MultipartFormFileHeaderToBytes(request.Audio)+ audioMimeType = http.DetectContentType(audioBytes)+ }- audioUploaded, err := service.uploadMedia(ctx, whatsmeow.MediaAudio, autioBytes, dataWaRecipient)+ // upload to WhatsApp servers+ audioUploaded, err := service.uploadMedia(ctx, whatsmeow.MediaAudio, audioBytes, dataWaRecipient)if err != nil {err = pkgError.WaUploadMediaError(fmt.Sprintf("Failed to upload audio: %v", err))return response, errdiff --git a/src/validations/send_validation.go b/src/validations/send_validation.goindex 9304faf0..83600245 100644--- a/src/validations/send_validation.go+++ b/src/validations/send_validation.go@@ -155,46 +155,64 @@ func ValidateSendLocation(ctx context.Context, request domainSend.LocationRequesfunc ValidateSendAudio(ctx context.Context, request domainSend.AudioRequest) error {err := validation.ValidateStructWithContext(ctx, &request,validation.Field(&request.Phone, validation.Required),- validation.Field(&request.Audio, validation.Required),)if err != nil {return pkgError.ValidationError(err.Error())}- availableMimes := map[string]bool{- "audio/aac": true,- "audio/amr": true,- "audio/flac": true,- "audio/m4a": true,- "audio/m4r": true,- "audio/mp3": true,- "audio/mpeg": true,- "audio/ogg": true,- "audio/wma": true,- "audio/x-ms-wma": true,- "audio/wav": true,- "audio/vnd.wav": true,- "audio/vnd.wave": true,- "audio/wave": true,- "audio/x-pn-wav": true,- "audio/x-wav": true,- }- availableMimesStr := ""-- // Sort MIME types for consistent error message order- mimeKeys := make([]string, 0, len(availableMimes))- for k := range availableMimes {- mimeKeys = append(mimeKeys, k)- }- sort.Strings(mimeKeys)-- for _, k := range mimeKeys {- availableMimesStr += k + ","- }-- if !availableMimes[request.Audio.Header.Get("Content-Type")] {- return pkgError.ValidationError(fmt.Sprintf("your audio type is not allowed. please use (%s)", availableMimesStr))+ // Ensure at least one of Audio or AudioURL is provided+ if request.Audio == nil && (request.AudioURL == nil || *request.AudioURL == "") {+ return pkgError.ValidationError("either Audio or AudioURL must be provided")+ }++ // If Audio file is provided, validate file MIME+ if request.Audio != nil {+ availableMimes := map[string]bool{+ "audio/aac": true,+ "audio/amr": true,+ "audio/flac": true,+ "audio/m4a": true,+ "audio/m4r": true,+ "audio/mp3": true,+ "audio/mpeg": true,+ "audio/ogg": true,+ "audio/wma": true,+ "audio/x-ms-wma": true,+ "audio/wav": true,+ "audio/vnd.wav": true,+ "audio/vnd.wave": true,+ "audio/wave": true,+ "audio/x-pn-wav": true,+ "audio/x-wav": true,+ }+ availableMimesStr := ""++ // Sort MIME types for consistent error message order+ mimeKeys := make([]string, 0, len(availableMimes))+ for k := range availableMimes {+ mimeKeys = append(mimeKeys, k)+ }+ sort.Strings(mimeKeys)++ for _, k := range mimeKeys {+ availableMimesStr += k + ","+ }++ if !availableMimes[request.Audio.Header.Get("Content-Type")] {+ return pkgError.ValidationError(fmt.Sprintf("your audio type is not allowed. please use (%s)", availableMimesStr))+ }+ }++ // If AudioURL provided, basic URL validation+ if request.AudioURL != nil {+ if *request.AudioURL == "" {+ return pkgError.ValidationError("AudioURL cannot be empty")+ }++ if err := validation.Validate(*request.AudioURL, is.URL); err != nil {+ return pkgError.ValidationError("AudioURL must be a valid URL")+ }}return nildiff --git a/src/views/components/SendAudio.js b/src/views/components/SendAudio.jsindex ca4452de..fb64dae6 100644--- a/src/views/components/SendAudio.js+++ b/src/views/components/SendAudio.js@@ -11,7 +11,8 @@ export default {type: window.TYPEUSER,loading: false,selectedFileName: null,- is_forwarded: false+ is_forwarded: false,+ audio_url: null,}},computed: {@@ -32,7 +33,7 @@ export default {return false;}- if (!this.selectedFileName) {+ if (!this.selectedFileName && !this.audio_url) {return false;}@@ -57,7 +58,16 @@ export default {let payload = new FormData();payload.append("phone", this.phone_id)payload.append("is_forwarded", this.is_forwarded)- payload.append("audio", $("#file_audio")[0].files[0])++ const fileInput = $("#file_audio");+ if (fileInput.length > 0 && fileInput[0].files.length > 0) {+ const file = fileInput[0].files[0];+ payload.append('audio', file);+ }+ if (this.audio_url) {+ payload.append('audio_url', this.audio_url)+ }+const response = await window.http.post(`/send/audio`, payload)this.handleReset();return response.data.message;@@ -76,6 +86,7 @@ export default {this.is_forwarded = false;$("#file_audio").val('');this.selectedFileName = null;+ this.audio_url = null;},handleFileChange(event) {const file = event.target.files[0];@@ -111,12 +122,21 @@ export default {<label>Mark audio as forwarded</label></div></div>+ <div class="field">+ <label>Audio URL</label>+ <input type="text" v-model="audio_url" placeholder="https://example.com/audio.mp3"+ aria-label="audio_url"/>+ </div>+ <div style="text-align: left; font-weight: bold; margin: 10px 0;">or you can upload audio from your+ device+ </div><div class="field" style="padding-bottom: 30px"><label>Audio</label>- <input type="file" style="display: none" accept="audio/*" id="file_audio" @change="handleFileChange"/>+ <input type="file" style="display: none" accept="audio/*" id="file_audio"+ @change="handleFileChange"/><label for="file_audio" class="ui positive medium green left floated button" style="color: white"><i class="ui upload icon"></i>- Upload+ Upload</label><div v-if="selectedFileName" style="margin-top: 60px"><div class="ui message">