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: add on-demand media download API and auto-download UI (#398)
Aldino Kemalf3de5456f51a
diff --git a/src/domains/message/interfaces.go b/src/domains/message/interfaces.goindex b39b8595..ed18ed96 100644--- a/src/domains/message/interfaces.go+++ b/src/domains/message/interfaces.go@@ -16,6 +16,7 @@ type IMessageActions interface {type IMessageManagement interface {DeleteMessage(ctx context.Context, request DeleteRequest) (err error)StarMessage(ctx context.Context, request StarRequest) (err error)+ DownloadMedia(ctx context.Context, request DownloadMediaRequest) (response DownloadMediaResponse, err error)}// IMessageUsecase combines all message interfacesdiff --git a/src/domains/message/message.go b/src/domains/message/message.goindex ef38312d..dbc20a81 100644--- a/src/domains/message/message.go+++ b/src/domains/message/message.go@@ -37,3 +37,17 @@ type StarRequest struct {Phone string `json:"phone" form:"phone"`IsStarred bool `json:"is_starred"`}++type DownloadMediaRequest struct {+ MessageID string `json:"message_id" uri:"message_id"`+ Phone string `json:"phone" form:"phone"`+}++type DownloadMediaResponse struct {+ MessageID string `json:"message_id"`+ Status string `json:"status"`+ MediaType string `json:"media_type"`+ Filename string `json:"filename"`+ FilePath string `json:"file_path"`+ FileSize int64 `json:"file_size"`+}diff --git a/src/pkg/utils/environment.go b/src/pkg/utils/environment.goindex e7c06164..601ba89a 100644--- a/src/pkg/utils/environment.go+++ b/src/pkg/utils/environment.go@@ -17,19 +17,19 @@ func IsLocal() bool {}func Env[T any](key string, defValue ...T) T {- if env := viper.Get(key); env != nil {- // Ensure type safety for retrieved environment variables- if value, ok := env.(T); ok {- return value- }- }+ if env := viper.Get(key); env != nil {+ // Ensure type safety for retrieved environment variables+ if value, ok := env.(T); ok {+ return value+ }+ }- if len(defValue) > 0 {- return defValue[0]- }+ if len(defValue) > 0 {+ return defValue[0]+ }- var zero T- return zero+ var zero T+ return zero}// MustHaveEnv ensure the ENV is exists, otherwise will crashing the appdiff --git a/src/ui/rest/message.go b/src/ui/rest/message.goindex d9fbe2e1..00ddd288 100644--- a/src/ui/rest/message.go+++ b/src/ui/rest/message.go@@ -21,6 +21,7 @@ func InitRestMessage(app fiber.Router, service domainMessage.IMessageUsecase) Meapp.Post("/message/:message_id/read", rest.MarkAsRead)app.Post("/message/:message_id/star", rest.StarMessage)app.Post("/message/:message_id/unstar", rest.UnstarMessage)+ app.Get("/message/:message_id/download", rest.DownloadMedia)return rest}@@ -157,3 +158,21 @@ func (controller *Message) UnstarMessage(c *fiber.Ctx) error {Results: nil,})}++func (controller *Message) DownloadMedia(c *fiber.Ctx) error {+ var request domainMessage.DownloadMediaRequest++ request.MessageID = c.Params("message_id")+ request.Phone = c.Query("phone")+ utils.SanitizePhone(&request.Phone)++ response, err := controller.Service.DownloadMedia(c.UserContext(), request)+ utils.PanicIfNeeded(err)++ return c.JSON(utils.ResponseData{+ Status: 200,+ Code: "SUCCESS",+ Message: response.Status,+ Results: response,+ })+}diff --git a/src/usecase/message.go b/src/usecase/message.goindex 83ff901b..b2cb67d8 100644--- a/src/usecase/message.go+++ b/src/usecase/message.go@@ -3,14 +3,18 @@ package usecaseimport ("context""fmt"+ "os"+ "path/filepath""time"+ "github.com/aldinokemal/go-whatsapp-web-multidevice/config"domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"domainMessage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/message""github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/whatsapp""github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils""github.com/aldinokemal/go-whatsapp-web-multidevice/validations""github.com/sirupsen/logrus"+ "go.mau.fi/whatsmeow""go.mau.fi/whatsmeow/appstate""go.mau.fi/whatsmeow/proto/waCommon""go.mau.fi/whatsmeow/proto/waE2E"@@ -182,3 +186,126 @@ func (service serviceMessage) StarMessage(ctx context.Context, request domainMes}return nil}++// DownloadMedia implements message.IMessageService.+func (service serviceMessage) DownloadMedia(ctx context.Context, request domainMessage.DownloadMediaRequest) (response domainMessage.DownloadMediaResponse, err error) {+ if err = validations.ValidateDownloadMedia(ctx, request); err != nil {+ return response, err+ }++ dataWaRecipient, err := utils.ValidateJidWithLogin(whatsapp.GetClient(), request.Phone)+ if err != nil {+ return response, err+ }++ // Query the message from chat storage+ message, err := service.chatStorageRepo.GetMessageByID(request.MessageID)+ if err != nil {+ return response, fmt.Errorf("message not found: %v", err)+ }++ if message == nil {+ return response, fmt.Errorf("message with ID %s not found", request.MessageID)+ }++ // Check if message has media+ if message.MediaType == "" || message.URL == "" {+ return response, fmt.Errorf("message %s does not contain downloadable media", request.MessageID)+ }++ // Verify the message is from the specified chat+ if message.ChatJID != dataWaRecipient.String() {+ return response, fmt.Errorf("message %s does not belong to chat %s", request.MessageID, dataWaRecipient.String())+ }++ // Create directory structure for organized storage+ chatDir := filepath.Join(config.PathMedia, utils.ExtractPhoneNumber(message.ChatJID))+ dateDir := filepath.Join(chatDir, message.Timestamp.Format("2006-01-02"))++ err = os.MkdirAll(dateDir, 0755)+ if err != nil {+ return response, fmt.Errorf("failed to create directory: %v", err)+ }++ // Create a downloadable message interface based on media type+ var downloadableMsg interface{}++ switch message.MediaType {+ case "image":+ downloadableMsg = &waE2E.ImageMessage{+ URL: proto.String(message.URL),+ MediaKey: message.MediaKey,+ FileSHA256: message.FileSHA256,+ FileEncSHA256: message.FileEncSHA256,+ FileLength: proto.Uint64(message.FileLength),+ }+ case "video":+ downloadableMsg = &waE2E.VideoMessage{+ URL: proto.String(message.URL),+ MediaKey: message.MediaKey,+ FileSHA256: message.FileSHA256,+ FileEncSHA256: message.FileEncSHA256,+ FileLength: proto.Uint64(message.FileLength),+ }+ case "audio":+ downloadableMsg = &waE2E.AudioMessage{+ URL: proto.String(message.URL),+ MediaKey: message.MediaKey,+ FileSHA256: message.FileSHA256,+ FileEncSHA256: message.FileEncSHA256,+ FileLength: proto.Uint64(message.FileLength),+ }+ case "document":+ downloadableMsg = &waE2E.DocumentMessage{+ URL: proto.String(message.URL),+ MediaKey: message.MediaKey,+ FileSHA256: message.FileSHA256,+ FileEncSHA256: message.FileEncSHA256,+ FileLength: proto.Uint64(message.FileLength),+ FileName: proto.String(message.Filename),+ }+ case "sticker":+ downloadableMsg = &waE2E.StickerMessage{+ URL: proto.String(message.URL),+ MediaKey: message.MediaKey,+ FileSHA256: message.FileSHA256,+ FileEncSHA256: message.FileEncSHA256,+ FileLength: proto.Uint64(message.FileLength),+ }+ default:+ return response, fmt.Errorf("unsupported media type: %s", message.MediaType)+ }++ // Download the media using existing utils.ExtractMedia function+ extractedMedia, err := utils.ExtractMedia(ctx, whatsapp.GetClient(), dateDir, downloadableMsg.(whatsmeow.DownloadableMessage))+ if err != nil {+ return response, fmt.Errorf("failed to download media: %v", err)+ }++ // Get file size+ fileInfo, err := os.Stat(extractedMedia.MediaPath)+ if err != nil {+ logrus.Warnf("Could not get file size for %s: %v", extractedMedia.MediaPath, err)+ }++ // Build response+ response.MessageID = request.MessageID+ response.Status = fmt.Sprintf("Media downloaded successfully to %s", extractedMedia.MediaPath)+ response.MediaType = message.MediaType+ response.Filename = filepath.Base(extractedMedia.MediaPath)+ response.FilePath = extractedMedia.MediaPath+ if fileInfo != nil {+ response.FileSize = fileInfo.Size()+ }++ logrus.Info(map[string]any{+ "message_id": request.MessageID,+ "phone": request.Phone,+ "chat": dataWaRecipient.String(),+ "media_type": response.MediaType,+ "file_path": response.FilePath,+ "file_size": response.FileSize,+ })++ return response, nil+}diff --git a/src/validations/message_validation.go b/src/validations/message_validation.goindex 47b9dc94..939e26a4 100644--- a/src/validations/message_validation.go+++ b/src/validations/message_validation.go@@ -89,3 +89,16 @@ func ValidateStarMessage(ctx context.Context, request domainMessage.StarRequest)return nil}++func ValidateDownloadMedia(ctx context.Context, request domainMessage.DownloadMediaRequest) error {+ err := validation.ValidateStructWithContext(ctx, &request,+ validation.Field(&request.Phone, validation.Required),+ validation.Field(&request.MessageID, validation.Required),+ )++ if err != nil {+ return pkgError.ValidationError(err.Error())+ }++ return nil+}diff --git a/src/views/components/ChatMessages.js b/src/views/components/ChatMessages.jsindex 606dda76..d4b6b2c3 100644--- a/src/views/components/ChatMessages.js+++ b/src/views/components/ChatMessages.js@@ -13,6 +13,12 @@ export default {currentPage: 1,pageSize: 20,totalMessages: 0,+ // Media download tracking+ downloadedMedia: {}, // messageId -> { file_path, media_type, file_size, status }+ downloadingMedia: new Set(), // Set of messageIds currently downloading+ mediaDownloadErrors: {}, // messageId -> error message+ maxConcurrentDownloads: 3,+ currentDownloads: 0,};},computed: {@@ -91,6 +97,9 @@ export default {if (this.messages.length === 0) {showErrorInfo("No messages found for the specified criteria");+ } else {+ // Auto-download media for loaded messages+ this.downloadAllMediaInMessages();}} catch (error) {showErrorInfo(@@ -126,6 +135,11 @@ export default {this.onlyMedia = false;this.currentPage = 1;this.totalMessages = 0;+ // Clear media download state+ this.downloadedMedia = {};+ this.downloadingMedia.clear();+ this.mediaDownloadErrors = {};+ this.currentDownloads = 0;},formatTimestamp(timestamp) {if (!timestamp) return "N/A";@@ -147,6 +161,139 @@ export default {if (message.media_type) return `[${message.media_type.toUpperCase()}]`;return "[No content]";},+ getMediaDisplay(message) {+ if (!message.media_type || !message.url || !message.id) {+ return null;+ }++ const messageId = message.id;+ const downloadedInfo = this.downloadedMedia[messageId];+ const isDownloaded = this.isMediaDownloaded(messageId);+ const isDownloading = this.isMediaDownloading(messageId);+ const hasError = this.hasMediaDownloadError(messageId);++ // Show loading state+ if (isDownloading) {+ return {+ type: 'loading',+ content: `<div class="ui active mini inline loader"></div> Downloading ${message.media_type}...`+ };+ }++ // Show error state with retry option+ if (hasError) {+ return {+ type: 'error',+ content: `<div class="ui red message">+ <i class="exclamation triangle icon"></i>+ Failed to download ${message.media_type}+ <span class="ui mini button" style="cursor: pointer; margin-left: 10px;"+ onclick="document.dispatchEvent(new CustomEvent('retryMediaDownload', {detail: '${messageId}'}))">+ <i class="redo icon"></i> Retry+ </span>+ </div>`+ };+ }++ // Show downloaded media+ if (isDownloaded && downloadedInfo) {+ const filePath = downloadedInfo.file_path;+ const mediaType = downloadedInfo.media_type;+ const filename = downloadedInfo.filename;+ const fileSize = downloadedInfo.file_size;++ switch (mediaType.toLowerCase()) {+ case 'image':+ return {+ type: 'image',+ content: `<div class="ui fluid image">+ <img src="${filePath}" alt="${filename}" style="max-width: 300px; max-height: 300px; border-radius: 4px;"+ onerror="this.style.display='none'; this.nextElementSibling.style.display='block';">+ <div style="display: none;" class="ui placeholder segment">+ <div class="ui icon header">+ <i class="image outline icon"></i>+ Image not available+ </div>+ </div>+ </div>`+ };++ case 'video':+ return {+ type: 'video',+ content: `<div class="ui fluid">+ <video controls style="max-width: 300px; max-height: 300px; border-radius: 4px;" preload="metadata">+ <source src="${filePath}" type="video/mp4">+ <source src="${filePath}" type="video/webm">+ <source src="${filePath}" type="video/ogg">+ Your browser does not support the video tag.+ </video>+ </div>`+ };++ case 'audio':+ return {+ type: 'audio',+ content: `<div class="ui fluid">+ <audio controls style="width: 100%; max-width: 300px;">+ <source src="${filePath}" type="audio/mpeg">+ <source src="${filePath}" type="audio/ogg">+ <source src="${filePath}" type="audio/wav">+ Your browser does not support the audio tag.+ </audio>+ </div>`+ };++ case 'document':+ const sizeText = fileSize ? `(${Math.round(fileSize / 1024)} KB)` : '';+ return {+ type: 'document',+ content: `<div class="ui labeled button">+ <a href="${filePath}" download="${filename}" class="ui button">+ <i class="download icon"></i>+ ${filename} ${sizeText}+ </a>+ <div class="ui basic left pointing label">+ Document+ </div>+ </div>`+ };++ case 'sticker':+ return {+ type: 'sticker',+ content: `<div class="ui">+ <img src="${filePath}" alt="Sticker" style="max-width: 150px; max-height: 150px; border-radius: 4px;"+ onerror="this.style.display='none'; this.nextElementSibling.style.display='block';">+ <div style="display: none;" class="ui placeholder segment">+ <div class="ui icon header">+ <i class="smile outline icon"></i>+ Sticker not available+ </div>+ </div>+ </div>`+ };++ default:+ return {+ type: 'unknown',+ content: `<div class="ui message">+ <i class="file icon"></i>+ Unknown media type: ${mediaType}+ </div>`+ };+ }+ }++ // Default: show media available label+ return {+ type: 'available',+ content: `<div class="ui tiny blue label">+ <i class="linkify icon"></i>+ ${message.media_type.toUpperCase()} Available+ </div>`+ };+ },getMessageStyle(message) {const baseStyle = {padding: "1em",@@ -166,6 +313,103 @@ export default {};}},+ // Media download methods+ isMediaDownloaded(messageId) {+ return this.downloadedMedia[messageId] && this.downloadedMedia[messageId].status === 'completed';+ },+ isMediaDownloading(messageId) {+ return this.downloadingMedia.has(messageId);+ },+ hasMediaDownloadError(messageId) {+ return !!this.mediaDownloadErrors[messageId];+ },+ async downloadMediaForMessage(message) {+ if (!message.media_type || !message.url || !message.id) {+ return;+ }++ const messageId = message.id;++ // Skip if already downloaded or downloading+ if (this.isMediaDownloaded(messageId) || this.isMediaDownloading(messageId)) {+ return;+ }++ // Check concurrent download limit+ if (this.currentDownloads >= this.maxConcurrentDownloads) {+ return;+ }++ try {+ this.downloadingMedia.add(messageId);+ this.currentDownloads++;++ // Clear any previous error+ if (this.mediaDownloadErrors[messageId]) {+ delete this.mediaDownloadErrors[messageId];+ }++ const response = await window.http.get(+ `/message/${messageId}/download?phone=${this.formattedJid}`+ );++ if (response.data && response.data.results) {+ this.downloadedMedia[messageId] = {+ file_path: response.data.results.file_path,+ media_type: response.data.results.media_type,+ file_size: response.data.results.file_size,+ filename: response.data.results.filename,+ status: 'completed'+ };+ }+ } catch (error) {+ console.error(`Failed to download media for message ${messageId}:`, error);+ this.mediaDownloadErrors[messageId] = error.response?.data?.message || 'Download failed';+ } finally {+ this.downloadingMedia.delete(messageId);+ this.currentDownloads--;+ }+ },+ async retryMediaDownload(messageId) {+ const message = this.messages.find(m => m.id === messageId);+ if (message) {+ // Clear the error first+ delete this.mediaDownloadErrors[messageId];+ await this.downloadMediaForMessage(message);+ }+ },+ async downloadAllMediaInMessages() {+ const mediaMessages = this.messages.filter(message =>+ message.media_type && message.url && message.id &&+ !this.isMediaDownloaded(message.id) && !this.isMediaDownloading(message.id)+ );++ if (mediaMessages.length === 0) {+ return;+ }++ // Download in batches to respect concurrency limit+ const downloadQueue = [...mediaMessages];++ const processQueue = async () => {+ while (downloadQueue.length > 0 && this.currentDownloads < this.maxConcurrentDownloads) {+ const message = downloadQueue.shift();+ if (message) {+ await this.downloadMediaForMessage(message);+ // Small delay to prevent overwhelming the server+ await new Promise(resolve => setTimeout(resolve, 100));+ }+ }++ // If there are still items in queue and we can download more, continue+ if (downloadQueue.length > 0 && this.currentDownloads < this.maxConcurrentDownloads) {+ setTimeout(processQueue, 500); // Wait a bit before checking again+ }+ };++ // Start processing+ processQueue();+ },},mounted() {// Store the event handler so we can remove it later@@ -173,14 +417,26 @@ export default {this.openModal();};+ // Handle retry media download events+ this.handleRetryMediaDownload = (event) => {+ const messageId = event.detail;+ this.retryMediaDownload(messageId);+ };+// Listen for custom event from ChatList to open modal properlywindow.addEventListener('openChatMessages', this.handleOpenChatMessages);++ // Listen for retry media download events+ document.addEventListener('retryMediaDownload', this.handleRetryMediaDownload);},beforeUnmount() {- // Clean up event listener+ // Clean up event listenersif (this.handleOpenChatMessages) {window.removeEventListener('openChatMessages', this.handleOpenChatMessages);}+ if (this.handleRetryMediaDownload) {+ document.removeEventListener('retryMediaDownload', this.handleRetryMediaDownload);+ }},template: `<div class="purple card" @click="openModal()" style="cursor: pointer">@@ -310,9 +566,8 @@ export default {</div><div class="description"><p>{{ getMessageContent(message) }}</p>- <div v-if="message.url" class="ui tiny blue label">- <i class="linkify icon"></i>- Media Available+ <div v-if="message.media_type && message.url" class="media-container" style="margin-top: 0.5em;">+ <div v-if="getMediaDisplay(message)" v-html="getMediaDisplay(message).content"></div></div></div></div>