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(webhook): forward conversion attribution and media metadata (#952)
Aldino Kemal7d61bcfd31aa
diff --git a/docs/webhook-payload.md b/docs/webhook-payload.mdindex bb7c19f7..245a59b4 100644--- a/docs/webhook-payload.md+++ b/docs/webhook-payload.md@@ -1822,6 +1822,88 @@ When a conversation starts from a Meta Click-to-WhatsApp ad, the first inbound m| `source_type` | string | Source type (e.g., `"ad"`) || `ad_type` | string | Ad type: `"CTWA"` (Click-to-WhatsApp) or `"CAWC"` (Click-to-Call) |+### Conversion Attribution and Media Metadata++Regular `message` events may also carry conversion attribution, media metadata and a few `contextInfo` values. They are+read from the message's own `contextInfo` (never from a quoted message) after unwrapping ephemeral and view-once+containers. Every field is optional: a key is present only when WhatsApp sent a non-empty, non-zero value, and+`conversion` or `media_info` is omitted entirely when it would be empty.++```json+{+ "event": "message",+ "device_id": "[email protected]",+ "payload": {+ "id": "3EB0C127D7BACC83D6B5",+ "chat_id": "[email protected]",+ "from": "[email protected]",+ "from_name": "Jane Customer",+ "timestamp": "2023-10-15T12:05:00Z",+ "is_from_me": false,+ "body": "Is this still available?",+ "image": {+ "url": "https://mmg.whatsapp.net/...",+ "caption": "Is this still available?"+ },+ "conversion": {+ "conversion_source": "FB_Ads",+ "conversion_data": "AQI=",+ "entry_point_conversion_source": "ctwa_ad",+ "entry_point_conversion_app": "instagram",+ "entry_point_conversion_delay_seconds": 4+ },+ "media_info": {+ "mime_type": "image/jpeg",+ "file_length": 204800,+ "file_sha256": "n4bQgYhMfWWaL+qgxVrQFaO/TxsrC4Is0V1sFbDwCgg=",+ "width": 1080,+ "height": 1350+ },+ "forwarding_score": 6,+ "mentioned_jids": ["[email protected]"],+ "expiration": 86400+ }+}+```++**Conversion fields** (`conversion`, from `contextInfo`):++| **Field** | **Type** | **Description** |+|------------------------------------------|----------|-------------------------------------------------------------------|+| `conversion_source` | string | Conversion source reported by WhatsApp (e.g., `"FB_Ads"`) |+| `conversion_data` | string | Opaque conversion data, standard base64-encoded |+| `conversion_delay_seconds` | integer | Delay between the conversion and the message, in seconds |+| `entry_point_conversion_source` | string | Entry point that opened the chat (e.g., `"ctwa_ad"`) |+| `entry_point_conversion_app` | string | App the entry point came from (e.g., `"instagram"`, `"facebook"`) |+| `entry_point_conversion_delay_seconds` | integer | Delay between the entry point and the message, in seconds |+| `entry_point_conversion_external_source` | string | External source of the entry point |+| `entry_point_conversion_external_medium` | string | External medium of the entry point |++**Media metadata fields** (`media_info`, for image, video, video note, audio, document and sticker messages). It+describes the media without download URLs or keys, and is present whether or not `WHATSAPP_AUTO_DOWNLOAD_MEDIA` is+enabled:++| **Field** | **Type** | **Description** |+|----------------|----------|---------------------------------------------------------------|+| `mime_type` | string | MIME type of the media |+| `file_name` | string | Original file name (documents only) |+| `file_length` | integer | File size in bytes |+| `file_sha256` | string | SHA-256 of the decrypted file, standard base64-encoded |+| `width` | integer | Width in pixels (image, video, video note and sticker) |+| `height` | integer | Height in pixels (image, video, video note and sticker) |+| `seconds` | integer | Duration in seconds (audio, video and video note) |+| `ptt` | boolean | `true` for voice notes; omitted otherwise |+| `is_animated` | boolean | `true` for animated stickers; omitted otherwise |+| `gif_playback` | boolean | `true` for videos sent as GIFs; omitted otherwise |++**Context fields** (top level of `payload`, from `contextInfo`):++| **Field** | **Type** | **Description** |+|--------------------|----------|-------------------------------------------------------------------------------------------------|+| `forwarding_score` | integer | How many times the message has been forwarded |+| `mentioned_jids` | array | JIDs mentioned in the message; LIDs are resolved to phone JIDs when possible, as with `from` |+| `expiration` | integer | Disappearing-message timer of the chat, in seconds |+## Integration Guide### Setting Up Webhook Endpointdiff --git a/src/infrastructure/whatsapp/event_message.go b/src/infrastructure/whatsapp/event_message.goindex 895bdd91..fa064d46 100644--- a/src/infrastructure/whatsapp/event_message.go+++ b/src/infrastructure/whatsapp/event_message.go@@ -372,6 +372,8 @@ func buildOptionalFields(ctx context.Context, client *whatsmeow.Client, evt *evebuildOtherMessageTypes(msg, payload)buildAlbumFields(evt, msg, payload)+ addMessageMetadataFields(ctx, client, msg, payload)+return nil}diff --git a/src/infrastructure/whatsapp/event_message_metadata.go b/src/infrastructure/whatsapp/event_message_metadata.gonew file mode 100644index 00000000..c4786475--- /dev/null+++ b/src/infrastructure/whatsapp/event_message_metadata.go@@ -0,0 +1,60 @@+package whatsapp++import (+ "context"++ "go.mau.fi/whatsmeow"+ "go.mau.fi/whatsmeow/proto/waE2E"+ "go.mau.fi/whatsmeow/types"++ "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"+)++// addMessageMetadataFields adds conversion attribution, media metadata and the+// message's own ContextInfo counters to a regular message payload. Absent+// values are omitted rather than sent empty.+func addMessageMetadataFields(ctx context.Context, client *whatsmeow.Client, msg *waE2E.Message, payload map[string]any) {+ if conversion := utils.ExtractConversion(msg); conversion != nil {+ payload["conversion"] = conversion+ }++ if mediaInfo := utils.ExtractMediaMetadata(msg); mediaInfo != nil {+ payload["media_info"] = mediaInfo+ }++ ci := utils.ExtractContextInfo(utils.UnwrapMessage(msg))+ if ci == nil {+ return+ }++ if score := ci.GetForwardingScore(); score != 0 {+ payload["forwarding_score"] = score+ }++ if mentions := normalizeMentionedJIDs(ctx, client, ci.GetMentionedJID()); len(mentions) > 0 {+ payload["mentioned_jids"] = mentions+ }++ if expiration := ci.GetExpiration(); expiration != 0 {+ payload["expiration"] = expiration+ }+}++func normalizeMentionedJIDs(ctx context.Context, client *whatsmeow.Client, mentions []string) []string {+ canResolve := client != nil && client.Store != nil && client.Store.LIDs != nil+ var normalized []string+ for _, mention := range mentions {+ if mention == "" {+ continue+ }+ if canResolve {+ if jid, err := types.ParseJID(mention); err == nil && jid.Server == types.HiddenUserServer {+ if resolved := NormalizeJIDFromLID(ctx, jid, client); resolved != jid {+ mention = resolved.ToNonAD().String()+ }+ }+ }+ normalized = append(normalized, mention)+ }+ return normalized+}diff --git a/src/infrastructure/whatsapp/event_message_metadata_test.go b/src/infrastructure/whatsapp/event_message_metadata_test.gonew file mode 100644index 00000000..269da8f2--- /dev/null+++ b/src/infrastructure/whatsapp/event_message_metadata_test.go@@ -0,0 +1,174 @@+package whatsapp++import (+ "context"+ "testing"+ "time"++ "github.com/aldinokemal/go-whatsapp-web-multidevice/config"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+ "go.mau.fi/whatsmeow"+ "go.mau.fi/whatsmeow/proto/waE2E"+ "go.mau.fi/whatsmeow/store"+ "go.mau.fi/whatsmeow/types"+ "go.mau.fi/whatsmeow/types/events"+ waLog "go.mau.fi/whatsmeow/util/log"+ "google.golang.org/protobuf/proto"+)++func TestBuildEventPayloadAddsMetadataFields(t *testing.T) {+ oldAutoDownload := config.WhatsappAutoDownloadMedia+ config.WhatsappAutoDownloadMedia = false+ defer func() { config.WhatsappAutoDownloadMedia = oldAutoDownload }()++ evt := &events.Message{+ Info: types.MessageInfo{+ MessageSource: types.MessageSource{+ Chat: types.NewJID("5541988887777", types.DefaultUserServer),+ Sender: types.NewJID("5541988887777", types.DefaultUserServer),+ },+ ID: "MSG900",+ Timestamp: time.Date(2026, time.October, 22, 10, 0, 0, 0, time.UTC),+ },+ Message: &waE2E.Message{+ ImageMessage: &waE2E.ImageMessage{+ URL: proto.String("https://mmg.whatsapp.net/image"),+ Caption: proto.String("look"),+ Mimetype: proto.String("image/jpeg"),+ FileLength: proto.Uint64(2048),+ Width: proto.Uint32(800),+ Height: proto.Uint32(600),+ ContextInfo: &waE2E.ContextInfo{+ ForwardingScore: proto.Uint32(6),+ MentionedJID: []string{"[email protected]"},+ Expiration: proto.Uint32(86400),+ ConversionSource: proto.String("FB_Ads"),+ },+ },+ },+ }++ eventType, payload, err := buildEventPayload(context.Background(), nil, evt)+ require.NoError(t, err)+ assert.Equal(t, EventTypeMessage, eventType)++ assert.Equal(t, uint32(6), payload["forwarding_score"])+ assert.Equal(t, []string{"[email protected]"}, payload["mentioned_jids"])+ assert.Equal(t, uint32(86400), payload["expiration"])+ assert.Equal(t, map[string]any{"conversion_source": "FB_Ads"}, payload["conversion"])+ assert.Equal(t, map[string]any{+ "mime_type": "image/jpeg",+ "file_length": uint64(2048),+ "width": uint32(800),+ "height": uint32(600),+ }, payload["media_info"])++ assert.Equal(t, map[string]any{+ "url": "https://mmg.whatsapp.net/image",+ "caption": "look",+ }, payload["image"])+ assert.Equal(t, "look", payload["body"])+}++func TestBuildEventPayloadOmitsAbsentMetadataFields(t *testing.T) {+ evt := &events.Message{+ Info: types.MessageInfo{+ MessageSource: types.MessageSource{+ Chat: types.NewJID("5541988887777", types.DefaultUserServer),+ Sender: types.NewJID("5541988887777", types.DefaultUserServer),+ },+ ID: "MSG901",+ Timestamp: time.Date(2026, time.October, 22, 10, 0, 0, 0, time.UTC),+ },+ Message: &waE2E.Message{+ ExtendedTextMessage: &waE2E.ExtendedTextMessage{+ Text: proto.String("reply"),+ ContextInfo: &waE2E.ContextInfo{+ StanzaID: proto.String("QUOTED1"),+ ForwardingScore: proto.Uint32(0),+ MentionedJID: []string{},+ QuotedMessage: &waE2E.Message{ExtendedTextMessage: &waE2E.ExtendedTextMessage{+ Text: proto.String("ad"),+ ContextInfo: &waE2E.ContextInfo{+ ConversionSource: proto.String("FB_Ads"),+ ForwardingScore: proto.Uint32(3),+ Expiration: proto.Uint32(86400),+ },+ }},+ },+ },+ },+ }++ _, payload, err := buildEventPayload(context.Background(), nil, evt)+ require.NoError(t, err)++ for _, key := range []string{"conversion", "media_info", "forwarding_score", "mentioned_jids", "expiration"} {+ assert.NotContains(t, payload, key)+ }+}++func TestAddMessageMetadataFieldsNormalizesMentionedLIDs(t *testing.T) {+ originalLog := log+ log = waLog.Noop+ defer func() { log = originalLog }()++ lid := types.NewJID("123456789012345", types.HiddenUserServer)+ pn := types.NewJID("5541977776666", types.DefaultUserServer)+ client := &whatsmeow.Client{Store: &store.Device{+ LIDs: &chatDisplayNameLIDStore{lid: lid, pn: pn},+ }}+ msg := &waE2E.Message{ExtendedTextMessage: &waE2E.ExtendedTextMessage{+ Text: proto.String("@123456789012345 @999 @5541955554444"),+ ContextInfo: &waE2E.ContextInfo{MentionedJID: []string{+ lid.String(),+ "999@lid",+ "[email protected]",+ }},+ }}++ t.Run("resolves known LIDs", func(t *testing.T) {+ payload := map[string]any{}+ addMessageMetadataFields(context.Background(), client, msg, payload)+ assert.Equal(t, []string{pn.String(), "999@lid", "[email protected]"}, payload["mentioned_jids"])+ })++ t.Run("keeps JIDs without a client", func(t *testing.T) {+ counter := &warnCountingLogger{Logger: waLog.Noop}+ log = counter+ defer func() { log = waLog.Noop }()++ payload := map[string]any{}+ addMessageMetadataFields(context.Background(), nil, msg, payload)+ assert.Equal(t, []string{lid.String(), "999@lid", "[email protected]"}, payload["mentioned_jids"])+ assert.Zero(t, counter.warns)+ })+}++func TestAddMessageMetadataFieldsUnwrapsMessage(t *testing.T) {+ msg := &waE2E.Message{EphemeralMessage: &waE2E.FutureProofMessage{Message: &waE2E.Message{+ ExtendedTextMessage: &waE2E.ExtendedTextMessage{+ Text: proto.String("disappearing"),+ ContextInfo: &waE2E.ContextInfo{+ Expiration: proto.Uint32(604800),+ ForwardingScore: proto.Uint32(2),+ },+ },+ }}}++ payload := map[string]any{}+ addMessageMetadataFields(context.Background(), nil, msg, payload)++ assert.Equal(t, uint32(604800), payload["expiration"])+ assert.Equal(t, uint32(2), payload["forwarding_score"])+}++type warnCountingLogger struct {+ waLog.Logger+ warns int+}++func (l *warnCountingLogger) Warnf(string, ...any) {+ l.warns+++}diff --git a/src/pkg/utils/whatsapp.go b/src/pkg/utils/whatsapp.goindex b0736fef..855c98cc 100644--- a/src/pkg/utils/whatsapp.go+++ b/src/pkg/utils/whatsapp.go@@ -744,6 +744,33 @@ func ExtractContextInfo(msg *waE2E.Message) *waE2E.ContextInfo {return msg.GetLiveLocationMessage().GetContextInfo()case msg.GetInteractiveMessage() != nil:return msg.GetInteractiveMessage().GetContextInfo()+ case msg.GetButtonsResponseMessage() != nil:+ return msg.GetButtonsResponseMessage().GetContextInfo()+ case msg.GetListResponseMessage() != nil:+ return msg.GetListResponseMessage().GetContextInfo()+ case msg.GetTemplateButtonReplyMessage() != nil:+ return msg.GetTemplateButtonReplyMessage().GetContextInfo()+ case msg.GetInteractiveResponseMessage() != nil:+ return msg.GetInteractiveResponseMessage().GetContextInfo()+ case msg.GetContactsArrayMessage() != nil:+ return msg.GetContactsArrayMessage().GetContextInfo()+ case msg.GetButtonsMessage() != nil:+ return msg.GetButtonsMessage().GetContextInfo()+ case msg.GetListMessage() != nil:+ return msg.GetListMessage().GetContextInfo()+ case msg.GetTemplateMessage() != nil:+ return msg.GetTemplateMessage().GetContextInfo()+ case msg.GetProductMessage() != nil:+ return msg.GetProductMessage().GetContextInfo()+ case msg.GetOrderMessage() != nil:+ return msg.GetOrderMessage().GetContextInfo()+ case msg.GetGroupInviteMessage() != nil:+ return msg.GetGroupInviteMessage().GetContextInfo()+ case msg.GetEventMessage() != nil:+ return msg.GetEventMessage().GetContextInfo()+ }+ if poll, _ := ExtractPollCreationMessage(msg); poll != nil {+ return poll.GetContextInfo()}return nil}diff --git a/src/pkg/utils/whatsapp_metadata.go b/src/pkg/utils/whatsapp_metadata.gonew file mode 100644index 00000000..75f5208e--- /dev/null+++ b/src/pkg/utils/whatsapp_metadata.go@@ -0,0 +1,114 @@+package utils++import (+ "encoding/base64"++ "go.mau.fi/whatsmeow/proto/waE2E"+)++// ExtractConversion extracts conversion attribution (e.g. Click-to-WhatsApp+// entry points) from the message's own ContextInfo. Returns nil when no+// attribution is present.+func ExtractConversion(msg *waE2E.Message) map[string]any {+ ci := ExtractContextInfo(UnwrapMessage(msg))+ if ci == nil {+ return nil+ }++ conversion := make(map[string]any)+ putNonEmptyString(conversion, "conversion_source", ci.GetConversionSource())+ putNonEmptyBytes(conversion, "conversion_data", ci.GetConversionData())+ putNonZeroUint32(conversion, "conversion_delay_seconds", ci.GetConversionDelaySeconds())+ putNonEmptyString(conversion, "entry_point_conversion_source", ci.GetEntryPointConversionSource())+ putNonEmptyString(conversion, "entry_point_conversion_app", ci.GetEntryPointConversionApp())+ putNonZeroUint32(conversion, "entry_point_conversion_delay_seconds", ci.GetEntryPointConversionDelaySeconds())+ putNonEmptyString(conversion, "entry_point_conversion_external_source", ci.GetEntryPointConversionExternalSource())+ putNonEmptyString(conversion, "entry_point_conversion_external_medium", ci.GetEntryPointConversionExternalMedium())++ if len(conversion) == 0 {+ return nil+ }+ return conversion+}++// ExtractMediaMetadata extracts descriptive media metadata (mime type, size,+// dimensions, duration and flags) without any download URL or key material.+// Returns nil when the message carries no media metadata.+func ExtractMediaMetadata(msg *waE2E.Message) map[string]any {+ msg = UnwrapMessage(msg)+ info := make(map[string]any)++ switch {+ case msg.GetImageMessage() != nil:+ image := msg.GetImageMessage()+ putMediaFileFields(info, image.GetMimetype(), image.GetFileLength(), image.GetFileSHA256())+ putNonZeroUint32(info, "width", image.GetWidth())+ putNonZeroUint32(info, "height", image.GetHeight())+ case msg.GetVideoMessage() != nil:+ putVideoFields(info, msg.GetVideoMessage())+ case msg.GetPtvMessage() != nil:+ putVideoFields(info, msg.GetPtvMessage())+ case msg.GetAudioMessage() != nil:+ audio := msg.GetAudioMessage()+ putMediaFileFields(info, audio.GetMimetype(), audio.GetFileLength(), audio.GetFileSHA256())+ putNonZeroUint32(info, "seconds", audio.GetSeconds())+ putTrue(info, "ptt", audio.GetPTT())+ case msg.GetDocumentMessage() != nil:+ document := msg.GetDocumentMessage()+ putMediaFileFields(info, document.GetMimetype(), document.GetFileLength(), document.GetFileSHA256())+ putNonEmptyString(info, "file_name", document.GetFileName())+ case msg.GetStickerMessage() != nil:+ sticker := msg.GetStickerMessage()+ putMediaFileFields(info, sticker.GetMimetype(), sticker.GetFileLength(), sticker.GetFileSHA256())+ putNonZeroUint32(info, "width", sticker.GetWidth())+ putNonZeroUint32(info, "height", sticker.GetHeight())+ putTrue(info, "is_animated", sticker.GetIsAnimated())+ default:+ return nil+ }++ if len(info) == 0 {+ return nil+ }+ return info+}++func putVideoFields(info map[string]any, video *waE2E.VideoMessage) {+ putMediaFileFields(info, video.GetMimetype(), video.GetFileLength(), video.GetFileSHA256())+ putNonZeroUint32(info, "width", video.GetWidth())+ putNonZeroUint32(info, "height", video.GetHeight())+ putNonZeroUint32(info, "seconds", video.GetSeconds())+ putTrue(info, "gif_playback", video.GetGifPlayback())+}++func putMediaFileFields(info map[string]any, mimeType string, fileLength uint64, fileSHA256 []byte) {+ putNonEmptyString(info, "mime_type", mimeType)+ if fileLength != 0 {+ info["file_length"] = fileLength+ }+ putNonEmptyBytes(info, "file_sha256", fileSHA256)+}++func putNonEmptyString(fields map[string]any, key, value string) {+ if value != "" {+ fields[key] = value+ }+}++func putNonEmptyBytes(fields map[string]any, key string, value []byte) {+ if len(value) > 0 {+ fields[key] = base64.StdEncoding.EncodeToString(value)+ }+}++func putNonZeroUint32(fields map[string]any, key string, value uint32) {+ if value != 0 {+ fields[key] = value+ }+}++func putTrue(fields map[string]any, key string, value bool) {+ if value {+ fields[key] = true+ }+}diff --git a/src/pkg/utils/whatsapp_metadata_test.go b/src/pkg/utils/whatsapp_metadata_test.gonew file mode 100644index 00000000..11eb6ec2--- /dev/null+++ b/src/pkg/utils/whatsapp_metadata_test.go@@ -0,0 +1,257 @@+package utils++import (+ "testing"++ "github.com/stretchr/testify/assert"+ "go.mau.fi/whatsmeow/proto/waE2E"+ "google.golang.org/protobuf/proto"+)++func TestExtractConversion(t *testing.T) {+ tests := []struct {+ name string+ msg *waE2E.Message+ want map[string]any+ }{+ {+ name: "entry point attribution",+ msg: &waE2E.Message{ExtendedTextMessage: &waE2E.ExtendedTextMessage{+ Text: proto.String("hi"),+ ContextInfo: &waE2E.ContextInfo{+ ConversionSource: proto.String("FB_Ads"),+ ConversionData: []byte{1, 2},+ EntryPointConversionSource: proto.String("ctwa_ad"),+ EntryPointConversionApp: proto.String("instagram"),+ EntryPointConversionDelaySeconds: proto.Uint32(4),+ },+ }},+ want: map[string]any{+ "conversion_source": "FB_Ads",+ "conversion_data": "AQI=",+ "entry_point_conversion_source": "ctwa_ad",+ "entry_point_conversion_app": "instagram",+ "entry_point_conversion_delay_seconds": uint32(4),+ },+ },+ {+ name: "delay and external entry point",+ msg: &waE2E.Message{ImageMessage: &waE2E.ImageMessage{+ ContextInfo: &waE2E.ContextInfo{+ ConversionDelaySeconds: proto.Uint32(30),+ EntryPointConversionExternalSource: proto.String("google"),+ EntryPointConversionExternalMedium: proto.String("cpc"),+ },+ }},+ want: map[string]any{+ "conversion_delay_seconds": uint32(30),+ "entry_point_conversion_external_source": "google",+ "entry_point_conversion_external_medium": "cpc",+ },+ },+ {+ name: "wrapped in ephemeral message",+ msg: &waE2E.Message{EphemeralMessage: &waE2E.FutureProofMessage{Message: &waE2E.Message{+ ExtendedTextMessage: &waE2E.ExtendedTextMessage{+ Text: proto.String("hi"),+ ContextInfo: &waE2E.ContextInfo{ConversionSource: proto.String("FB_Ads")},+ },+ }}},+ want: map[string]any{"conversion_source": "FB_Ads"},+ },+ {+ name: "empty conversion data is omitted",+ msg: &waE2E.Message{ExtendedTextMessage: &waE2E.ExtendedTextMessage{+ ContextInfo: &waE2E.ContextInfo{+ ConversionSource: proto.String("FB_Ads"),+ ConversionData: []byte{},+ },+ }},+ want: map[string]any{"conversion_source": "FB_Ads"},+ },+ {+ name: "only empty conversion data",+ msg: &waE2E.Message{ExtendedTextMessage: &waE2E.ExtendedTextMessage{+ ContextInfo: &waE2E.ContextInfo{ConversionData: []byte{}},+ }},+ want: nil,+ },+ {+ name: "attribution on the quoted message is ignored",+ msg: &waE2E.Message{ExtendedTextMessage: &waE2E.ExtendedTextMessage{+ Text: proto.String("replying to the ad"),+ ContextInfo: &waE2E.ContextInfo{+ StanzaID: proto.String("QUOTED1"),+ QuotedMessage: &waE2E.Message{ExtendedTextMessage: &waE2E.ExtendedTextMessage{+ Text: proto.String("original"),+ ContextInfo: &waE2E.ContextInfo{ConversionSource: proto.String("FB_Ads")},+ }},+ },+ }},+ want: nil,+ },+ {+ name: "no attribution fields",+ msg: &waE2E.Message{ExtendedTextMessage: &waE2E.ExtendedTextMessage{+ Text: proto.String("hi"),+ ContextInfo: &waE2E.ContextInfo{StanzaID: proto.String("X")},+ }},+ want: nil,+ },+ {+ name: "plain conversation",+ msg: &waE2E.Message{Conversation: proto.String("hi")},+ want: nil,+ },+ {+ name: "nil message",+ msg: nil,+ want: nil,+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ assert.Equal(t, tt.want, ExtractConversion(tt.msg))+ })+ }+}++func TestExtractMediaMetadata(t *testing.T) {+ tests := []struct {+ name string+ msg *waE2E.Message+ want map[string]any+ }{+ {+ name: "voice note",+ msg: &waE2E.Message{AudioMessage: &waE2E.AudioMessage{+ Mimetype: proto.String("audio/ogg; codecs=opus"),+ Seconds: proto.Uint32(7),+ PTT: proto.Bool(true),+ FileLength: proto.Uint64(1234),+ }},+ want: map[string]any{+ "mime_type": "audio/ogg; codecs=opus",+ "seconds": uint32(7),+ "ptt": true,+ "file_length": uint64(1234),+ },+ },+ {+ name: "audio file without ptt",+ msg: &waE2E.Message{AudioMessage: &waE2E.AudioMessage{+ Mimetype: proto.String("audio/mpeg"),+ PTT: proto.Bool(false),+ }},+ want: map[string]any{"mime_type": "audio/mpeg"},+ },+ {+ name: "document",+ msg: &waE2E.Message{DocumentMessage: &waE2E.DocumentMessage{+ FileName: proto.String("a.pdf"),+ }},+ want: map[string]any{"file_name": "a.pdf"},+ },+ {+ name: "image",+ msg: &waE2E.Message{ImageMessage: &waE2E.ImageMessage{+ Mimetype: proto.String("image/jpeg"),+ FileLength: proto.Uint64(2048),+ FileSHA256: []byte{1, 2},+ Width: proto.Uint32(800),+ Height: proto.Uint32(600),+ }},+ want: map[string]any{+ "mime_type": "image/jpeg",+ "file_length": uint64(2048),+ "file_sha256": "AQI=",+ "width": uint32(800),+ "height": uint32(600),+ },+ },+ {+ name: "gif video",+ msg: &waE2E.Message{VideoMessage: &waE2E.VideoMessage{+ Mimetype: proto.String("video/mp4"),+ Seconds: proto.Uint32(3),+ Width: proto.Uint32(320),+ Height: proto.Uint32(240),+ GifPlayback: proto.Bool(true),+ }},+ want: map[string]any{+ "mime_type": "video/mp4",+ "seconds": uint32(3),+ "width": uint32(320),+ "height": uint32(240),+ "gif_playback": true,+ },+ },+ {+ name: "video note",+ msg: &waE2E.Message{PtvMessage: &waE2E.VideoMessage{+ Mimetype: proto.String("video/mp4"),+ Seconds: proto.Uint32(12),+ Width: proto.Uint32(480),+ Height: proto.Uint32(480),+ }},+ want: map[string]any{+ "mime_type": "video/mp4",+ "seconds": uint32(12),+ "width": uint32(480),+ "height": uint32(480),+ },+ },+ {+ name: "animated sticker",+ msg: &waE2E.Message{StickerMessage: &waE2E.StickerMessage{+ Mimetype: proto.String("image/webp"),+ Width: proto.Uint32(512),+ Height: proto.Uint32(512),+ IsAnimated: proto.Bool(true),+ }},+ want: map[string]any{+ "mime_type": "image/webp",+ "width": uint32(512),+ "height": uint32(512),+ "is_animated": true,+ },+ },+ {+ name: "view once image",+ msg: &waE2E.Message{ViewOnceMessageV2: &waE2E.FutureProofMessage{Message: &waE2E.Message{+ ImageMessage: &waE2E.ImageMessage{Mimetype: proto.String("image/jpeg")},+ }}},+ want: map[string]any{"mime_type": "image/jpeg"},+ },+ {+ name: "empty sha256 is omitted",+ msg: &waE2E.Message{DocumentMessage: &waE2E.DocumentMessage{+ Mimetype: proto.String("application/pdf"),+ FileSHA256: []byte{},+ }},+ want: map[string]any{"mime_type": "application/pdf"},+ },+ {+ name: "media without metadata",+ msg: &waE2E.Message{ImageMessage: &waE2E.ImageMessage{}},+ want: nil,+ },+ {+ name: "plain text",+ msg: &waE2E.Message{Conversation: proto.String("hi")},+ want: nil,+ },+ {+ name: "nil message",+ msg: nil,+ want: nil,+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ assert.Equal(t, tt.want, ExtractMediaMetadata(tt.msg))+ })+ }+}diff --git a/src/pkg/utils/whatsapp_test.go b/src/pkg/utils/whatsapp_test.goindex e675307e..c46ae1fd 100644--- a/src/pkg/utils/whatsapp_test.go+++ b/src/pkg/utils/whatsapp_test.go@@ -832,3 +832,32 @@ func TestExtractContextInfoInteractiveMessage(t *testing.T) {}})}++// TestExtractContextInfoOtherMessageTypes pins the remaining message types that+// carry their own ContextInfo, so replies, mentions, forwarding and ad+// attribution are not lost when a customer answers a button, list or template,+// or sends a poll, contact list, group invite or event.+func TestExtractContextInfoOtherMessageTypes(t *testing.T) {+ ci := &waE2E.ContextInfo{StanzaID: proto.String("ABC123")}+ tests := map[string]*waE2E.Message{+ "buttons response": {ButtonsResponseMessage: &waE2E.ButtonsResponseMessage{ContextInfo: ci}},+ "list response": {ListResponseMessage: &waE2E.ListResponseMessage{ContextInfo: ci}},+ "template button reply": {TemplateButtonReplyMessage: &waE2E.TemplateButtonReplyMessage{ContextInfo: ci}},+ "interactive response": {InteractiveResponseMessage: &waE2E.InteractiveResponseMessage{ContextInfo: ci}},+ "contacts array": {ContactsArrayMessage: &waE2E.ContactsArrayMessage{ContextInfo: ci}},+ "buttons": {ButtonsMessage: &waE2E.ButtonsMessage{ContextInfo: ci}},+ "list": {ListMessage: &waE2E.ListMessage{ContextInfo: ci}},+ "template": {TemplateMessage: &waE2E.TemplateMessage{ContextInfo: ci}},+ "product": {ProductMessage: &waE2E.ProductMessage{ContextInfo: ci}},+ "order": {OrderMessage: &waE2E.OrderMessage{ContextInfo: ci}},+ "group invite": {GroupInviteMessage: &waE2E.GroupInviteMessage{ContextInfo: ci}},+ "event": {EventMessage: &waE2E.EventMessage{ContextInfo: ci}},+ "poll v3": {PollCreationMessageV3: &waE2E.PollCreationMessage{ContextInfo: ci}},+ "poll v4": {PollCreationMessageV4: &waE2E.FutureProofMessage{Message: &waE2E.Message{PollCreationMessage: &waE2E.PollCreationMessage{ContextInfo: ci}}}},+ }+ for name, msg := range tests {+ if got := ExtractContextInfo(msg).GetStanzaID(); got != "ABC123" {+ t.Errorf("%s: StanzaID = %q, want %q", name, got, "ABC123")+ }+ }+}