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.

fix(webhook): propagate device context to async forward goroutines (#793)

Claudio Oliveira29ebb7733d36
diff --git a/src/infrastructure/chatwoot/client.go b/src/infrastructure/chatwoot/client.go
index 8e1bc154..5dd46267 100644
--- a/src/infrastructure/chatwoot/client.go
+++ b/src/infrastructure/chatwoot/client.go
@@ -866,9 +866,14 @@ func (c *Client) createMessageWithAttachments(endpoint, content, messageType str
mimeType := mime.TypeByExtension(ext)
if mimeType == "" {
- if ext == ".oga" {
+ switch ext {
+ case ".oga", ".ogg":
+ // The runtime image ships no /etc/mime.types, so
+ // mime.TypeByExtension never resolves these on its own.
+ // WhatsApp voice notes are saved as .ogg (Opus-in-Ogg);
+ // .oga is the alternate extension for the same container.
mimeType = "audio/ogg"
- } else {
+ default:
mimeType = "application/octet-stream"
}
}
diff --git a/src/infrastructure/whatsapp/event_call.go b/src/infrastructure/whatsapp/event_call.go
index c7d210ee..9b8cd2aa 100644
--- a/src/infrastructure/whatsapp/event_call.go
+++ b/src/infrastructure/whatsapp/event_call.go
@@ -44,7 +44,7 @@ func handleCallOffer(ctx context.Context, evt *events.CallOffer, chatStorageRepo
// Forward call event to webhook
go func(e *events.CallOffer, c *whatsmeow.Client, rejected bool) {
- webhookCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ webhookCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
defer cancel()
if err := forwardCallOfferToWebhook(webhookCtx, e, deviceID, c, rejected); err != nil {
logrus.Errorf("Failed to forward call event to webhook: %v", err)
diff --git a/src/infrastructure/whatsapp/event_chat_presence.go b/src/infrastructure/whatsapp/event_chat_presence.go
index 92a6fec5..6d906406 100644
--- a/src/infrastructure/whatsapp/event_chat_presence.go
+++ b/src/infrastructure/whatsapp/event_chat_presence.go
@@ -26,7 +26,7 @@ func handleChatPresence(ctx context.Context, evt *events.ChatPresence, deviceID
// Forward chat presence event to webhook
go func(e *events.ChatPresence, c *whatsmeow.Client) {
- webhookCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ webhookCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
defer cancel()
if err := forwardChatPresenceToWebhook(webhookCtx, e, deviceID, c); err != nil {
logrus.Errorf("Failed to forward chat_presence event to webhook: %v", err)
diff --git a/src/infrastructure/whatsapp/event_group.go b/src/infrastructure/whatsapp/event_group.go
index a32287ca..a03fa1d6 100644
--- a/src/infrastructure/whatsapp/event_group.go
+++ b/src/infrastructure/whatsapp/event_group.go
@@ -85,7 +85,7 @@ func handleJoinedGroup(ctx context.Context, evt *events.JoinedGroup, deviceID st
// Forward joined group event to webhook
go func(e *events.JoinedGroup, c *whatsmeow.Client) {
- webhookCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ webhookCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
defer cancel()
if err := forwardJoinedGroupToWebhook(webhookCtx, e, deviceID, c); err != nil {
logrus.Errorf("Failed to forward joined group event to webhook: %v", err)
diff --git a/src/infrastructure/whatsapp/event_handler.go b/src/infrastructure/whatsapp/event_handler.go
index 06c7480d..76e93994 100644
--- a/src/infrastructure/whatsapp/event_handler.go
+++ b/src/infrastructure/whatsapp/event_handler.go
@@ -124,7 +124,7 @@ func handleDeleteForMe(ctx context.Context, evt *events.DeleteForMe, chatStorage
// Send webhook notification for delete event
go func(c *whatsmeow.Client) {
- webhookCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ webhookCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
defer cancel()
if err := forwardDeleteToWebhook(webhookCtx, evt, message, deviceID, c); err != nil {
log.Errorf("Failed to forward delete event to webhook: %v", err)
@@ -322,7 +322,7 @@ func handleReceipt(ctx context.Context, evt *events.Receipt, deviceID string, cl
// Note: Receipt events are not rate limited as they are critical for message delivery status
if sendReceipt {
go func(e *events.Receipt, c *whatsmeow.Client) {
- webhookCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ webhookCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
defer cancel()
if err := forwardReceiptToWebhook(webhookCtx, e, deviceID, c); err != nil {
logrus.Errorf("Failed to forward ack event to webhook: %v", err)
@@ -343,12 +343,12 @@ func handlePresence(_ context.Context, evt *events.Presence) {
}
}
-func handleAppState(_ context.Context, evt *events.AppState, deviceID string, client *whatsmeow.Client) {
+func handleAppState(ctx context.Context, evt *events.AppState, deviceID string, client *whatsmeow.Client) {
log.Debugf("App state event: %+v / %+v", evt.Index, evt.SyncActionValue)
if isLabelAppState(evt) {
go func(e *events.AppState, c *whatsmeow.Client) {
- webhookCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ webhookCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
defer cancel()
if err := forwardLabelAppStateToWebhook(webhookCtx, e, deviceID, c); err != nil {
logrus.Errorf("Failed to forward label appstate event to webhook: %v", err)
@@ -382,7 +382,7 @@ func handleGroupInfo(ctx context.Context, evt *events.GroupInfo, deviceID string
// Forward group info event to webhook
go func(e *events.GroupInfo, c *whatsmeow.Client) {
- webhookCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ webhookCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
defer cancel()
if err := forwardGroupInfoToWebhook(webhookCtx, e, deviceID, c); err != nil {
logrus.Errorf("Failed to forward group info event to webhook: %v", err)
diff --git a/src/infrastructure/whatsapp/event_message.go b/src/infrastructure/whatsapp/event_message.go
index ca24fd80..e40f88ad 100644
--- a/src/infrastructure/whatsapp/event_message.go
+++ b/src/infrastructure/whatsapp/event_message.go
@@ -15,6 +15,7 @@ import (
"github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
"github.com/sirupsen/logrus"
"go.mau.fi/whatsmeow/types/events"
+ "google.golang.org/protobuf/reflect/protoreflect"
)
var reMention = regexp.MustCompile(`\B@\w+`)
@@ -171,9 +172,86 @@ func buildEventPayload(ctx context.Context, client *whatsmeow.Client, evt *event
return "", nil, err
}
+ if payloadHasNoRenderableContent(payload) && !hasRecognizedMessageType(msg) {
+ // Neither a recognized message type nor any renderable payload field:
+ // this is genuinely an unhandled kind (e.g. templates, interactive/
+ // native-flow messages, polls, group invites, payment requests).
+ // Downstream (Chatwoot) will render it as "(Unsupported message
+ // type)" with no way to tell which WhatsApp message kind caused it.
+ // Log which proto field is populated — never its value, since that
+ // can carry customer message content, media URLs, and decryption
+ // keys — so a future occurrence is diagnosable from logs alone.
+ logrus.Warnf("Unrecognized message type from %s (id=%s): populated proto fields=%v", evt.Info.Sender.String(), evt.Info.ID, populatedMessageFields(msg))
+ }
+
return EventTypeMessage, payload, nil
}
+// payloadHasNoRenderableContent reports whether none of the fields
+// buildMessageBody/buildOptionalFields/buildMediaFields/buildOtherMessageTypes
+// populate for a recognized message type are present. Kept in sync with the
+// field names those functions write to payload.
+//
+// This alone is not sufficient to conclude the message type is unrecognized:
+// a known media type (image/audio/video/document/sticker/video_note) with a
+// failed/expired download leaves its field unset here too, even though
+// buildMediaFields correctly identified it. Callers must also check
+// hasRecognizedMessageType before treating this as "unhandled type".
+func payloadHasNoRenderableContent(payload map[string]any) bool {
+ renderableKeys := []string{
+ "body",
+ "image", "audio", "video", "video_note", "document", "sticker",
+ "contact", "contacts_array", "list", "live_location", "location", "order",
+ }
+ for _, key := range renderableKeys {
+ if _, ok := payload[key]; ok {
+ return false
+ }
+ }
+ return true
+}
+
+// hasRecognizedMessageType reports whether msg is one of the kinds
+// buildMediaFields/buildOtherMessageTypes know how to handle, independent of
+// whether extraction actually produced payload content (e.g. a media
+// download can fail while the type itself is still recognized). Keep this in
+// sync with the Get*Message() checks in those two functions.
+func hasRecognizedMessageType(msg *waE2E.Message) bool {
+ switch {
+ case msg.GetAudioMessage() != nil,
+ msg.GetDocumentMessage() != nil,
+ msg.GetImageMessage() != nil,
+ msg.GetStickerMessage() != nil,
+ msg.GetVideoMessage() != nil,
+ msg.GetPtvMessage() != nil,
+ msg.GetContactMessage() != nil,
+ msg.GetContactsArrayMessage() != nil,
+ msg.GetListMessage() != nil,
+ msg.GetLiveLocationMessage() != nil,
+ msg.GetLocationMessage() != nil,
+ msg.GetOrderMessage() != nil:
+ return true
+ default:
+ return false
+ }
+}
+
+// populatedMessageFields lists the proto field names set on msg (e.g.
+// "interactiveMessage", "templateMessage"), using reflection purely for
+// field descriptors — never field values — so this is safe to log at warn
+// level even though the message itself may carry customer content.
+func populatedMessageFields(msg *waE2E.Message) []string {
+ if msg == nil {
+ return nil
+ }
+ var names []string
+ msg.ProtoReflect().Range(func(fd protoreflect.FieldDescriptor, _ protoreflect.Value) bool {
+ names = append(names, string(fd.Name()))
+ return true
+ })
+ return names
+}
+
func buildFromFields(ctx context.Context, client *whatsmeow.Client, evt *events.Message, payload map[string]any) {
chatJID := evt.Info.Chat.ToNonAD()
if chatJID.Server == "lid" {
diff --git a/src/infrastructure/whatsapp/event_message_handler.go b/src/infrastructure/whatsapp/event_message_handler.go
index b19d0f99..063ea0da 100644
--- a/src/infrastructure/whatsapp/event_message_handler.go
+++ b/src/infrastructure/whatsapp/event_message_handler.go
@@ -174,7 +174,7 @@ func handleWebhookForward(ctx context.Context, evt *events.Message, client *what
// Forward to webhook if any webhook is configured (global or per-device)
// The forwardPayloadToConfiguredWebhooks function itself handles the no-op case
go func(e *events.Message, c *whatsmeow.Client) {
- webhookCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ webhookCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
defer cancel()
if err := forwardMessageToWebhook(webhookCtx, c, e); err != nil {
logrus.Error("Failed forward to webhook: ", err)
diff --git a/src/infrastructure/whatsapp/event_newsletter.go b/src/infrastructure/whatsapp/event_newsletter.go
index 39c12d8a..b20f3361 100644
--- a/src/infrastructure/whatsapp/event_newsletter.go
+++ b/src/infrastructure/whatsapp/event_newsletter.go
@@ -14,7 +14,7 @@ func handleNewsletterJoin(ctx context.Context, evt *events.NewsletterJoin, devic
log.Infof("Joined newsletter %s", evt.ID)
go func(e *events.NewsletterJoin) {
- webhookCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ webhookCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
defer cancel()
if err := forwardNewsletterJoinToWebhook(webhookCtx, e, deviceID); err != nil {
logrus.Errorf("Failed to forward newsletter join to webhook: %v", err)
@@ -27,7 +27,7 @@ func handleNewsletterLeave(ctx context.Context, evt *events.NewsletterLeave, dev
log.Infof("Left newsletter %s (role: %s)", evt.ID, evt.Role)
go func(e *events.NewsletterLeave) {
- webhookCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ webhookCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
defer cancel()
if err := forwardNewsletterLeaveToWebhook(webhookCtx, e, deviceID); err != nil {
logrus.Errorf("Failed to forward newsletter leave to webhook: %v", err)
@@ -40,7 +40,7 @@ func handleNewsletterLiveUpdate(ctx context.Context, evt *events.NewsletterLiveU
log.Infof("Newsletter %s: %d new message(s)", evt.JID, len(evt.Messages))
go func(e *events.NewsletterLiveUpdate) {
- webhookCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ webhookCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
defer cancel()
if err := forwardNewsletterLiveUpdateToWebhook(webhookCtx, e, deviceID); err != nil {
logrus.Errorf("Failed to forward newsletter live update to webhook: %v", err)
@@ -53,7 +53,7 @@ func handleNewsletterMuteChange(ctx context.Context, evt *events.NewsletterMuteC
log.Infof("Newsletter %s mute changed to: %s", evt.ID, evt.Mute)
go func(e *events.NewsletterMuteChange) {
- webhookCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ webhookCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
defer cancel()
if err := forwardNewsletterMuteChangeToWebhook(webhookCtx, e, deviceID); err != nil {
logrus.Errorf("Failed to forward newsletter mute change to webhook: %v", err)