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.

feat(webhook): expose poll vote selections (#816)

Aldino Kemal04381b9ab9a2
diff --git a/docs/webhook-payload.md b/docs/webhook-payload.md
index 3fae6ba4..3b68d4ac 100644
--- a/docs/webhook-payload.md
+++ b/docs/webhook-payload.md
@@ -281,6 +281,112 @@ resolution order.
}
```
+### Poll Messages
+
+Poll creations, votes, edits, and added options keep the normal `message` event name. The structured `poll` object lets
+existing `WHATSAPP_WEBHOOK_EVENTS=message` subscriptions receive poll interactions without another event allow-list.
+Option hashes are lowercase hexadecimal SHA-256 hashes of the exact option names.
+
+Poll creation:
+
+```json
+{
+ "event": "message",
+ "device_id": "[email protected]",
+ "payload": {
+ "id": "POLL-1",
+ "chat_id": "[email protected]",
+ "body": "Poll: Lunch?",
+ "poll": {
+ "type": "creation",
+ "poll_id": "POLL-1",
+ "question": "Lunch?",
+ "options": [
+ {"name": "Pizza", "hash": "f12958816a49adfa2c6c8de8dd2144c163e92c5e375de964d533187c7d236c36"},
+ {"name": "Sushi", "hash": "670bd9ced0c6bc3fab9bcce97185cdb5a6c6008f0bb7a33c5e432b7faa0e27ed"}
+ ],
+ "selectable_options_count": 1,
+ "version": "v3"
+ }
+ }
+}
+```
+
+Resolved vote:
+
+```json
+{
+ "event": "message",
+ "device_id": "[email protected]",
+ "payload": {
+ "id": "VOTE-1",
+ "chat_id": "[email protected]",
+ "body": "Poll vote: Sushi",
+ "poll": {
+ "type": "vote",
+ "poll_id": "POLL-1",
+ "question": "Lunch?",
+ "options": [
+ {"name": "Pizza", "hash": "f12958816a49adfa2c6c8de8dd2144c163e92c5e375de964d533187c7d236c36"},
+ {"name": "Sushi", "hash": "670bd9ced0c6bc3fab9bcce97185cdb5a6c6008f0bb7a33c5e432b7faa0e27ed"}
+ ],
+ "selected_options": ["Sushi"],
+ "selected_option_hashes": ["670bd9ced0c6bc3fab9bcce97185cdb5a6c6008f0bb7a33c5e432b7faa0e27ed"],
+ "resolution_status": "resolved"
+ }
+ }
+}
+```
+
+Clearing all choices is distinct from a resolution failure. Both arrays are present and empty:
+
+```json
+{
+ "body": "Poll vote cleared",
+ "poll": {
+ "type": "vote",
+ "poll_id": "POLL-1",
+ "selected_options": [],
+ "selected_option_hashes": [],
+ "resolution_status": "resolved"
+ }
+}
+```
+
+Resolution statuses:
+
+| Status | Meaning |
+|---|---|
+| `resolved` | The vote decrypted and every selected hash matched a stored option. |
+| `partially_resolved` | The vote decrypted, but one or more hashes did not match the stored definition. All hashes and the matched names are returned. |
+| `definition_missing` | The vote decrypted, but the original poll definition was unavailable. Hashes are returned and names are empty. |
+| `decrypt_failed` | The original WhatsApp message secret was missing or authentication failed. Known poll details are returned, but selection fields are omitted. |
+
+Poll edits replace the stored definition and use `"type": "edit"`. Add-option messages use `"type": "add_option"`,
+return the current full `options` list when known, and add an `added_option` object:
+
+```json
+{
+ "body": "Poll option added: Ramen",
+ "poll": {
+ "type": "add_option",
+ "poll_id": "POLL-1",
+ "question": "Lunch?",
+ "options": [
+ {"name": "Pizza", "hash": "f12958816a49adfa2c6c8de8dd2144c163e92c5e375de964d533187c7d236c36"},
+ {"name": "Sushi", "hash": "670bd9ced0c6bc3fab9bcce97185cdb5a6c6008f0bb7a33c5e432b7faa0e27ed"},
+ {"name": "Ramen", "hash": "8930b1916b28f31f1e9c067cecce8301a2653982e8696f5b78d30229c3e0e988"}
+ ],
+ "added_option": {"name": "Ramen", "hash": "8930b1916b28f31f1e9c067cecce8301a2653982e8696f5b78d30229c3e0e988"}
+ }
+}
+```
+
+Poll definitions are persisted per device and chat from live messages, sent polls, and recent/bootstrap history sync, so
+votes can normally be resolved after a restart. Decryption still depends on WhatsApp having delivered the original
+message secret. Older/incomplete history and some upstream LID migration cases may therefore produce `decrypt_failed`;
+the webhook is still delivered with a safe degraded payload.
+
## Receipt Events
Receipt events are triggered when messages receive acknowledgments such as delivery confirmations and read receipts.
diff --git a/src/domains/chatstorage/chatstorage.go b/src/domains/chatstorage/chatstorage.go
index 229175d6..a38d5551 100644
--- a/src/domains/chatstorage/chatstorage.go
+++ b/src/domains/chatstorage/chatstorage.go
@@ -51,6 +51,26 @@ type MessageEdit struct {
CreatedAt time.Time `db:"created_at"`
}
+// PollOption is one stable poll choice and its lowercase SHA-256 name hash.
+type PollOption struct {
+ Name string `json:"name"`
+ Hash string `json:"hash"`
+}
+
+// PollDefinition stores the option catalogue required to resolve encrypted
+// poll vote hashes after restarts and history synchronization.
+type PollDefinition struct {
+ DeviceID string `db:"device_id"`
+ ChatJID string `db:"chat_jid"`
+ PollMessageID string `db:"poll_message_id"`
+ Question string `db:"question"`
+ Options []PollOption `db:"-"`
+ SelectableOptionCount uint32 `db:"selectable_option_count"`
+ Version string `db:"version"`
+ CreatedAt time.Time `db:"created_at"`
+ UpdatedAt time.Time `db:"updated_at"`
+}
+
// ChatwootMessageLink maps a WhatsApp message to the Chatwoot message created
// for it. It is device-scoped because the same WhatsApp message ID can appear
// in independent device stores.
diff --git a/src/domains/chatstorage/interfaces.go b/src/domains/chatstorage/interfaces.go
index 0cf8fc2b..36bf76ef 100644
--- a/src/domains/chatstorage/interfaces.go
+++ b/src/domains/chatstorage/interfaces.go
@@ -36,6 +36,12 @@ type IChatStorageRepository interface {
DeleteMessageByDevice(deviceID, id, chatJID string) error
StoreSentMessageWithContext(ctx context.Context, messageID string, senderJID string, recipientJID string, content string, timestamp time.Time, msg *waE2E.Message) error
+ // Poll definition operations
+ UpsertPollDefinition(definition *PollDefinition) error
+ GetPollDefinition(deviceID, chatJID, pollMessageID string) (*PollDefinition, error)
+ GetPollDefinitionByIDAndDevice(deviceID, pollMessageID string) (*PollDefinition, error)
+ AppendPollOption(deviceID, chatJID, pollMessageID string, option PollOption) error
+
// Chatwoot correlation operations
UpsertChatwootMessageLink(link *ChatwootMessageLink) error
GetChatwootMessageLinkByWhatsAppID(deviceID, waMessageID string) (*ChatwootMessageLink, error)
diff --git a/src/infrastructure/chatstorage/sqlite_repository.go b/src/infrastructure/chatstorage/sqlite_repository.go
index 6d4db1ba..86c8ff69 100644
--- a/src/infrastructure/chatstorage/sqlite_repository.go
+++ b/src/infrastructure/chatstorage/sqlite_repository.go
@@ -253,6 +253,9 @@ func (r *SQLiteRepository) DeleteChat(jid string) error {
if _, err := tx.Exec("DELETE FROM chatwoot_message_links WHERE wa_chat_jid = ?", jid); err != nil {
return err
}
+ if _, err := tx.Exec("DELETE FROM poll_definitions WHERE chat_jid = ?", jid); err != nil {
+ return err
+ }
// Delete messages after dependent rows to keep cleanup explicit.
_, err = tx.Exec("DELETE FROM messages WHERE chat_jid = ?", jid)
@@ -286,6 +289,9 @@ func (r *SQLiteRepository) DeleteChatByDevice(deviceID, jid string) error {
if _, err := tx.Exec("DELETE FROM chatwoot_message_links WHERE wa_chat_jid = ? AND device_id = ?", jid, deviceID); err != nil {
return err
}
+ if _, err := tx.Exec("DELETE FROM poll_definitions WHERE chat_jid = ? AND device_id = ?", jid, deviceID); err != nil {
+ return err
+ }
// Delete messages after dependent rows to keep cleanup explicit.
_, err = tx.Exec("DELETE FROM messages WHERE chat_jid = ? AND device_id = ?", jid, deviceID)
@@ -709,6 +715,9 @@ func (r *SQLiteRepository) DeleteMessage(id, chatJID string) error {
if _, err := tx.Exec("DELETE FROM message_edits WHERE original_message_id = ? AND chat_jid = ?", id, chatJID); err != nil {
return err
}
+ if _, err := tx.Exec("DELETE FROM poll_definitions WHERE poll_message_id = ? AND chat_jid = ?", id, chatJID); err != nil {
+ return err
+ }
if _, err := tx.Exec("DELETE FROM messages WHERE id = ? AND chat_jid = ?", id, chatJID); err != nil {
return err
}
@@ -730,12 +739,189 @@ func (r *SQLiteRepository) DeleteMessageByDevice(deviceID, id, chatJID string) e
if _, err := tx.Exec("DELETE FROM message_edits WHERE original_message_id = ? AND chat_jid = ? AND device_id = ?", id, chatJID, deviceID); err != nil {
return err
}
+ if _, err := tx.Exec("DELETE FROM poll_definitions WHERE poll_message_id = ? AND chat_jid = ? AND device_id = ?", id, chatJID, deviceID); err != nil {
+ return err
+ }
if _, err := tx.Exec("DELETE FROM messages WHERE id = ? AND chat_jid = ? AND device_id = ?", id, chatJID, deviceID); err != nil {
return err
}
return tx.Commit()
}
+// UpsertPollDefinition stores the ordered poll option catalogue used to map
+// decrypted vote hashes back to human-readable names.
+func (r *SQLiteRepository) UpsertPollDefinition(definition *domainChatStorage.PollDefinition) error {
+ if definition == nil {
+ return fmt.Errorf("poll definition is required")
+ }
+ if strings.TrimSpace(definition.DeviceID) == "" || strings.TrimSpace(definition.ChatJID) == "" || strings.TrimSpace(definition.PollMessageID) == "" {
+ return fmt.Errorf("poll definition requires device_id, chat_jid, and poll_message_id")
+ }
+
+ optionsJSON, err := json.Marshal(definition.Options)
+ if err != nil {
+ return fmt.Errorf("failed to marshal poll options: %w", err)
+ }
+ now := time.Now()
+ if definition.UpdatedAt.IsZero() {
+ definition.UpdatedAt = now
+ }
+ if definition.CreatedAt.IsZero() {
+ definition.CreatedAt = definition.UpdatedAt
+ }
+
+ tx, err := r.db.Begin()
+ if err != nil {
+ return err
+ }
+ defer tx.Rollback()
+
+ var existingUpdatedAt time.Time
+ err = tx.QueryRow(`
+ SELECT updated_at FROM poll_definitions
+ WHERE device_id = ? AND chat_jid = ? AND poll_message_id = ?
+ `, definition.DeviceID, definition.ChatJID, definition.PollMessageID).Scan(&existingUpdatedAt)
+ switch {
+ case err == nil:
+ if !definition.UpdatedAt.After(existingUpdatedAt) {
+ return tx.Commit()
+ }
+ _, err = tx.Exec(`
+ UPDATE poll_definitions
+ SET question = ?, options_json = ?, selectable_option_count = ?, version = ?, updated_at = ?
+ WHERE device_id = ? AND chat_jid = ? AND poll_message_id = ?
+ `, definition.Question, string(optionsJSON), definition.SelectableOptionCount, definition.Version, definition.UpdatedAt,
+ definition.DeviceID, definition.ChatJID, definition.PollMessageID)
+ if err != nil {
+ return err
+ }
+ return tx.Commit()
+ case err != sql.ErrNoRows:
+ return err
+ }
+
+ _, err = tx.Exec(`
+ INSERT INTO poll_definitions (
+ device_id, chat_jid, poll_message_id, question, options_json,
+ selectable_option_count, version, created_at, updated_at
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
+ `, definition.DeviceID, definition.ChatJID, definition.PollMessageID, definition.Question, string(optionsJSON),
+ definition.SelectableOptionCount, definition.Version, definition.CreatedAt, definition.UpdatedAt)
+ if err != nil {
+ return err
+ }
+ return tx.Commit()
+}
+
+// GetPollDefinition retrieves one poll definition using its full device/chat identity.
+func (r *SQLiteRepository) GetPollDefinition(deviceID, chatJID, pollMessageID string) (*domainChatStorage.PollDefinition, error) {
+ var definition domainChatStorage.PollDefinition
+ var optionsJSON string
+ err := r.db.QueryRow(`
+ SELECT device_id, chat_jid, poll_message_id, question, options_json,
+ selectable_option_count, version, created_at, updated_at
+ FROM poll_definitions
+ WHERE device_id = ? AND chat_jid = ? AND poll_message_id = ?
+ `, deviceID, chatJID, pollMessageID).Scan(
+ &definition.DeviceID, &definition.ChatJID, &definition.PollMessageID, &definition.Question, &optionsJSON,
+ &definition.SelectableOptionCount, &definition.Version, &definition.CreatedAt, &definition.UpdatedAt,
+ )
+ if err == sql.ErrNoRows {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, err
+ }
+ if err := json.Unmarshal([]byte(optionsJSON), &definition.Options); err != nil {
+ return nil, fmt.Errorf("failed to decode poll options for %s: %w", pollMessageID, err)
+ }
+ return &definition, nil
+}
+
+// GetPollDefinitionByIDAndDevice resolves a poll when a direct chat transitions
+// between PN and LID identities and no mapping is available. It refuses an
+// ambiguous message ID rather than selecting a definition from the wrong chat.
+func (r *SQLiteRepository) GetPollDefinitionByIDAndDevice(deviceID, pollMessageID string) (*domainChatStorage.PollDefinition, error) {
+ rows, err := r.db.Query(`
+ SELECT device_id, chat_jid, poll_message_id, question, options_json,
+ selectable_option_count, version, created_at, updated_at
+ FROM poll_definitions
+ WHERE device_id = ? AND poll_message_id = ?
+ ORDER BY chat_jid
+ LIMIT 2
+ `, deviceID, pollMessageID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+
+ var match *domainChatStorage.PollDefinition
+ for rows.Next() {
+ if match != nil {
+ return nil, fmt.Errorf("poll definition %s is ambiguous for device %s", pollMessageID, deviceID)
+ }
+ definition := &domainChatStorage.PollDefinition{}
+ var optionsJSON string
+ if err := rows.Scan(
+ &definition.DeviceID, &definition.ChatJID, &definition.PollMessageID, &definition.Question, &optionsJSON,
+ &definition.SelectableOptionCount, &definition.Version, &definition.CreatedAt, &definition.UpdatedAt,
+ ); err != nil {
+ return nil, err
+ }
+ if err := json.Unmarshal([]byte(optionsJSON), &definition.Options); err != nil {
+ return nil, fmt.Errorf("failed to decode poll options for %s: %w", pollMessageID, err)
+ }
+ match = definition
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return match, nil
+}
+
+// AppendPollOption atomically appends a new option while treating a repeated
+// hash as an idempotent delivery of the same add-option event.
+func (r *SQLiteRepository) AppendPollOption(deviceID, chatJID, pollMessageID string, option domainChatStorage.PollOption) error {
+ tx, err := r.db.Begin()
+ if err != nil {
+ return err
+ }
+ defer tx.Rollback()
+
+ var optionsJSON string
+ err = tx.QueryRow(`
+ SELECT options_json FROM poll_definitions
+ WHERE device_id = ? AND chat_jid = ? AND poll_message_id = ?
+ `, deviceID, chatJID, pollMessageID).Scan(&optionsJSON)
+ if err == sql.ErrNoRows {
+ return fmt.Errorf("poll definition %s not found", pollMessageID)
+ }
+ if err != nil {
+ return err
+ }
+ var options []domainChatStorage.PollOption
+ if err := json.Unmarshal([]byte(optionsJSON), &options); err != nil {
+ return fmt.Errorf("failed to decode poll options for %s: %w", pollMessageID, err)
+ }
+ for _, existing := range options {
+ if existing.Hash == option.Hash {
+ return tx.Commit()
+ }
+ }
+ options = append(options, option)
+ encoded, err := json.Marshal(options)
+ if err != nil {
+ return fmt.Errorf("failed to marshal poll options: %w", err)
+ }
+ if _, err := tx.Exec(`
+ UPDATE poll_definitions SET options_json = ?, updated_at = ?
+ WHERE device_id = ? AND chat_jid = ? AND poll_message_id = ?
+ `, string(encoded), time.Now(), deviceID, chatJID, pollMessageID); err != nil {
+ return err
+ }
+ return tx.Commit()
+}
+
// UpsertChatwootMessageLink records the stable mapping between a WhatsApp
// message and the Chatwoot row created for it.
func (r *SQLiteRepository) UpsertChatwootMessageLink(link *domainChatStorage.ChatwootMessageLink) error {
@@ -1299,6 +1485,11 @@ func (r *SQLiteRepository) TruncateAllChats() error {
return fmt.Errorf("failed to delete chatwoot forward queue: %w", err)
}
+ _, err = tx.Exec("DELETE FROM poll_definitions")
+ if err != nil {
+ return fmt.Errorf("failed to delete poll definitions: %w", err)
+ }
+
// Delete messages after dependent rows to keep cleanup explicit.
_, err = tx.Exec("DELETE FROM messages")
if err != nil {
@@ -1342,6 +1533,10 @@ func (r *SQLiteRepository) DeleteDeviceData(deviceID string) error {
return fmt.Errorf("failed to delete device chatwoot forward queue: %w", err)
}
+ if _, err := tx.Exec(`DELETE FROM poll_definitions WHERE device_id = ?`, deviceID); err != nil {
+ return fmt.Errorf("failed to delete device poll definitions: %w", err)
+ }
+
// Delete messages after dependent rows via direct device_id filter.
if _, err := tx.Exec(`DELETE FROM messages WHERE device_id = ?`, deviceID); err != nil {
return fmt.Errorf("failed to delete device messages: %w", err)
@@ -2596,5 +2791,18 @@ func (r *SQLiteRepository) getMigrations() []string {
`CREATE INDEX IF NOT EXISTS idx_chatwoot_links_conversation_account ON chatwoot_message_links(chatwoot_conversation_id, chatwoot_account_id, updated_at)`,
// Migration 43: Count/delete message links by owning config without a full-table scan
`CREATE INDEX IF NOT EXISTS idx_chatwoot_links_config ON chatwoot_message_links(chatwoot_config_id)`,
+ // Migration 44: Persist poll option catalogues for encrypted vote resolution
+ `CREATE TABLE IF NOT EXISTS poll_definitions (
+ device_id VARCHAR(255) NOT NULL DEFAULT '',
+ chat_jid VARCHAR(255) NOT NULL,
+ poll_message_id VARCHAR(255) NOT NULL,
+ question TEXT NOT NULL DEFAULT '',
+ options_json TEXT NOT NULL DEFAULT '[]',
+ selectable_option_count INTEGER NOT NULL DEFAULT 0,
+ version VARCHAR(16) NOT NULL DEFAULT '',
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (device_id, chat_jid, poll_message_id)
+ )`,
}
}
diff --git a/src/infrastructure/chatstorage/sqlite_repository_poll_test.go b/src/infrastructure/chatstorage/sqlite_repository_poll_test.go
new file mode 100644
index 00000000..75b1a84e
--- /dev/null
+++ b/src/infrastructure/chatstorage/sqlite_repository_poll_test.go
@@ -0,0 +1,173 @@
+package chatstorage
+
+import (
+ "testing"
+ "time"
+
+ domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func TestPollDefinitionRoundTripAndIsolation(t *testing.T) {
+ repo := newTestSQLiteRepository(t)
+ definition := &domainChatStorage.PollDefinition{
+ DeviceID: "[email protected]",
+ ChatJID: "[email protected]",
+ PollMessageID: "POLL-1",
+ Question: "Lunch?",
+ SelectableOptionCount: 1,
+ Version: "v3",
+ Options: []domainChatStorage.PollOption{
+ {Name: "Pizza", Hash: "hash-pizza"},
+ {Name: "Sushi", Hash: "hash-sushi"},
+ },
+ }
+
+ require.NoError(t, repo.UpsertPollDefinition(definition))
+ got, err := repo.GetPollDefinition(definition.DeviceID, definition.ChatJID, definition.PollMessageID)
+ require.NoError(t, err)
+ require.NotNil(t, got)
+ assert.Equal(t, "Lunch?", got.Question)
+ assert.Equal(t, "v3", got.Version)
+ assert.Equal(t, uint32(1), got.SelectableOptionCount)
+ require.Len(t, got.Options, 2)
+ assert.Equal(t, "Pizza", got.Options[0].Name)
+ assert.Equal(t, "hash-sushi", got.Options[1].Hash)
+
+ other, err := repo.GetPollDefinition("[email protected]", definition.ChatJID, definition.PollMessageID)
+ require.NoError(t, err)
+ assert.Nil(t, other, "definition leaked across devices")
+}
+
+func TestAppendPollOptionIsOrderedAndIdempotent(t *testing.T) {
+ repo := newTestSQLiteRepository(t)
+ definition := &domainChatStorage.PollDefinition{
+ DeviceID: "[email protected]",
+ ChatJID: "[email protected]",
+ PollMessageID: "POLL-2",
+ Question: "Lunch?",
+ Options: []domainChatStorage.PollOption{{Name: "Pizza", Hash: "hash-pizza"}},
+ }
+ require.NoError(t, repo.UpsertPollDefinition(definition))
+ option := domainChatStorage.PollOption{Name: "Sushi", Hash: "hash-sushi"}
+ require.NoError(t, repo.AppendPollOption(definition.DeviceID, definition.ChatJID, definition.PollMessageID, option))
+ require.NoError(t, repo.AppendPollOption(definition.DeviceID, definition.ChatJID, definition.PollMessageID, option))
+
+ got, err := repo.GetPollDefinition(definition.DeviceID, definition.ChatJID, definition.PollMessageID)
+ require.NoError(t, err)
+ require.NotNil(t, got)
+ require.Len(t, got.Options, 2)
+ assert.Equal(t, "Pizza", got.Options[0].Name)
+ assert.Equal(t, "Sushi", got.Options[1].Name)
+}
+
+func TestGetPollDefinitionRejectsMalformedOptionsJSON(t *testing.T) {
+ repo := newTestSQLiteRepository(t)
+ definition := &domainChatStorage.PollDefinition{
+ DeviceID: "device-a", ChatJID: "chat-a", PollMessageID: "poll-bad-json", Question: "Q",
+ }
+ require.NoError(t, repo.UpsertPollDefinition(definition))
+ _, err := repo.db.Exec(`UPDATE poll_definitions SET options_json = ? WHERE device_id = ? AND chat_jid = ? AND poll_message_id = ?`,
+ "{", definition.DeviceID, definition.ChatJID, definition.PollMessageID)
+ require.NoError(t, err)
+ _, err = repo.GetPollDefinition(definition.DeviceID, definition.ChatJID, definition.PollMessageID)
+ assert.Error(t, err, "expected malformed options JSON to return an error")
+}
+
+func TestUpsertPollDefinitionDoesNotReplaceNewerDefinition(t *testing.T) {
+ repo := newTestSQLiteRepository(t)
+ newerTime := time.Date(2026, time.August, 27, 10, 0, 0, 0, time.UTC)
+ olderTime := newerTime.Add(-time.Hour)
+ newer := &domainChatStorage.PollDefinition{
+ DeviceID: "device-a",
+ ChatJID: "chat-a",
+ PollMessageID: "poll-monotonic",
+ Question: "Edited question",
+ Options: []domainChatStorage.PollOption{
+ {Name: "Original", Hash: "hash-original"},
+ {Name: "Added live", Hash: "hash-added"},
+ },
+ UpdatedAt: newerTime,
+ }
+ replayedCreation := &domainChatStorage.PollDefinition{
+ DeviceID: newer.DeviceID,
+ ChatJID: newer.ChatJID,
+ PollMessageID: newer.PollMessageID,
+ Question: "Original question",
+ Options: []domainChatStorage.PollOption{{Name: "Original", Hash: "hash-original"}},
+ UpdatedAt: olderTime,
+ }
+
+ require.NoError(t, repo.UpsertPollDefinition(newer))
+ require.NoError(t, repo.UpsertPollDefinition(replayedCreation))
+ got, err := repo.GetPollDefinition(newer.DeviceID, newer.ChatJID, newer.PollMessageID)
+ require.NoError(t, err)
+ require.NotNil(t, got)
+ assert.Equal(t, "Edited question", got.Question)
+ assert.True(t, got.UpdatedAt.Equal(newerTime), "updated_at = %s, want %s", got.UpdatedAt, newerTime)
+ require.Len(t, got.Options, 2)
+ assert.Equal(t, "Added live", got.Options[1].Name)
+}
+
+func TestGetPollDefinitionByIDAndDeviceResolvesChatAliasOnlyWhenUnambiguous(t *testing.T) {
+ t.Run("single matching poll", func(t *testing.T) {
+ repo := newTestSQLiteRepository(t)
+ require.NoError(t, repo.UpsertPollDefinition(&domainChatStorage.PollDefinition{
+ DeviceID: "device-a", ChatJID: "[email protected]", PollMessageID: "poll-alias", Question: "Q",
+ }))
+ got, err := repo.GetPollDefinitionByIDAndDevice("device-a", "poll-alias")
+ require.NoError(t, err)
+ require.NotNil(t, got)
+ assert.Equal(t, "[email protected]", got.ChatJID)
+ })
+
+ t.Run("ambiguous message id", func(t *testing.T) {
+ repo := newTestSQLiteRepository(t)
+ for _, chatJID := range []string{"chat-a", "chat-b"} {
+ require.NoError(t, repo.UpsertPollDefinition(&domainChatStorage.PollDefinition{
+ DeviceID: "device-a", ChatJID: chatJID, PollMessageID: "poll-duplicate", Question: "Q",
+ }))
+ }
+ got, err := repo.GetPollDefinitionByIDAndDevice("device-a", "poll-duplicate")
+ assert.Error(t, err)
+ assert.Nil(t, got)
+ })
+}
+
+func TestPollDefinitionsFollowCleanupPaths(t *testing.T) {
+ tests := []struct {
+ name string
+ cleanup func(repo *SQLiteRepository) error
+ }{
+ {
+ name: "delete message",
+ cleanup: func(repo *SQLiteRepository) error { return repo.DeleteMessageByDevice("device-a", "poll-a", "chat-a") },
+ },
+ {
+ name: "delete chat",
+ cleanup: func(repo *SQLiteRepository) error { return repo.DeleteChatByDevice("device-a", "chat-a") },
+ },
+ {
+ name: "delete device",
+ cleanup: func(repo *SQLiteRepository) error { return repo.DeleteDeviceData("device-a") },
+ },
+ {
+ name: "truncate",
+ cleanup: func(repo *SQLiteRepository) error { return repo.TruncateAllChats() },
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ repo := newTestSQLiteRepository(t)
+ require.NoError(t, repo.UpsertPollDefinition(&domainChatStorage.PollDefinition{
+ DeviceID: "device-a", ChatJID: "chat-a", PollMessageID: "poll-a", Question: "Q",
+ }))
+ require.NoError(t, tt.cleanup(repo))
+ got, err := repo.GetPollDefinition("device-a", "chat-a", "poll-a")
+ require.NoError(t, err)
+ assert.Nil(t, got, "poll definition should be cleaned up")
+ })
+ }
+}
diff --git a/src/infrastructure/whatsapp/chatstorage_wrapper.go b/src/infrastructure/whatsapp/chatstorage_wrapper.go
index 83fef99b..b2bd5097 100644
--- a/src/infrastructure/whatsapp/chatstorage_wrapper.go
+++ b/src/infrastructure/whatsapp/chatstorage_wrapper.go
@@ -247,6 +247,37 @@ func (r *deviceChatStorage) StoreSentMessageWithContext(ctx context.Context, mes
return r.base.StoreSentMessageWithContext(ctx, messageID, senderJID, recipientJID, content, timestamp, msg)
}
+func (r *deviceChatStorage) UpsertPollDefinition(definition *domainChatStorage.PollDefinition) error {
+ if definition != nil && definition.DeviceID == "" {
+ definition.DeviceID = r.deviceID
+ }
+ return r.base.UpsertPollDefinition(definition)
+}
+
+func (r *deviceChatStorage) GetPollDefinition(deviceID, chatJID, pollMessageID string) (*domainChatStorage.PollDefinition, error) {
+ targetDeviceID := deviceID
+ if targetDeviceID == "" {
+ targetDeviceID = r.deviceID
+ }
+ return r.base.GetPollDefinition(targetDeviceID, chatJID, pollMessageID)
+}
+
+func (r *deviceChatStorage) GetPollDefinitionByIDAndDevice(deviceID, pollMessageID string) (*domainChatStorage.PollDefinition, error) {
+ targetDeviceID := deviceID
+ if targetDeviceID == "" {
+ targetDeviceID = r.deviceID
+ }
+ return r.base.GetPollDefinitionByIDAndDevice(targetDeviceID, pollMessageID)
+}
+
+func (r *deviceChatStorage) AppendPollOption(deviceID, chatJID, pollMessageID string, option domainChatStorage.PollOption) error {
+ targetDeviceID := deviceID
+ if targetDeviceID == "" {
+ targetDeviceID = r.deviceID
+ }
+ return r.base.AppendPollOption(targetDeviceID, chatJID, pollMessageID, option)
+}
+
func (r *deviceChatStorage) GetChatMessageCount(chatJID string) (int64, error) {
return r.base.GetChatMessageCountByDevice(r.deviceID, chatJID)
}
diff --git a/src/infrastructure/whatsapp/event_message.go b/src/infrastructure/whatsapp/event_message.go
index e40f88ad..b37c4c00 100644
--- a/src/infrastructure/whatsapp/event_message.go
+++ b/src/infrastructure/whatsapp/event_message.go
@@ -42,8 +42,8 @@ type webhookContactPayload struct {
}
// forwardMessageToWebhook is a helper function to forward message event to webhook url
-func forwardMessageToWebhook(ctx context.Context, client *whatsmeow.Client, evt *events.Message) error {
- webhookEvent, err := createWebhookEvent(ctx, client, evt)
+func forwardMessageToWebhook(ctx context.Context, client *whatsmeow.Client, evt *events.Message, preparedPoll ...*webhookPollPayload) error {
+ webhookEvent, err := createWebhookEvent(ctx, client, evt, preparedPoll...)
if err != nil {
return err
}
@@ -65,7 +65,7 @@ func isReactionMessage(evt *events.Message) bool {
return utils.UnwrapMessage(evt.Message).GetReactionMessage() != nil
}
-func createWebhookEvent(ctx context.Context, client *whatsmeow.Client, evt *events.Message) (*WebhookEvent, error) {
+func createWebhookEvent(ctx context.Context, client *whatsmeow.Client, evt *events.Message, preparedPoll ...*webhookPollPayload) (*WebhookEvent, error) {
webhookEvent := &WebhookEvent{
Event: EventTypeMessage,
Payload: make(map[string]any),
@@ -78,7 +78,7 @@ func createWebhookEvent(ctx context.Context, client *whatsmeow.Client, evt *even
}
// Determine event type and build payload
- eventType, payload, err := buildEventPayload(ctx, client, evt)
+ eventType, payload, err := buildEventPayload(ctx, client, evt, preparedPoll...)
if err != nil {
return nil, err
}
@@ -89,7 +89,7 @@ func createWebhookEvent(ctx context.Context, client *whatsmeow.Client, evt *even
return webhookEvent, nil
}
-func buildEventPayload(ctx context.Context, client *whatsmeow.Client, evt *events.Message) (string, map[string]any, error) {
+func buildEventPayload(ctx context.Context, client *whatsmeow.Client, evt *events.Message, preparedPoll ...*webhookPollPayload) (string, map[string]any, error) {
payload := make(map[string]any)
msg := utils.UnwrapMessage(evt.Message)
@@ -172,6 +172,13 @@ func buildEventPayload(ctx context.Context, client *whatsmeow.Client, evt *event
return "", nil, err
}
+ if len(preparedPoll) > 0 && preparedPoll[0] != nil {
+ payload["poll"] = preparedPoll[0]
+ if _, hasBody := payload["body"]; !hasBody {
+ payload["body"] = pollWebhookBody(preparedPoll[0])
+ }
+ }
+
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/
diff --git a/src/infrastructure/whatsapp/event_message_handler.go b/src/infrastructure/whatsapp/event_message_handler.go
index 063ea0da..295369ea 100644
--- a/src/infrastructure/whatsapp/event_message_handler.go
+++ b/src/infrastructure/whatsapp/event_message_handler.go
@@ -32,13 +32,14 @@ func handleMessage(ctx context.Context, evt *events.Message, chatStorageRepo dom
// edit-handling paths unchanged. No-op when the envelope is absent or when
// decryption fails.
evt = materializeSecretEditMessage(ctx, evt, client)
+ pollPayload := preparePollWebhookPayload(ctx, client, chatStorageRepo, evt)
if isReactionMessage(evt) {
if err := chatStorageRepo.CreateReaction(ctx, evt); err != nil {
log.Errorf("Failed to store incoming reaction %s: %v", evt.Info.ID, err)
}
- handleWebhookForward(ctx, evt, client)
+ handleWebhookForward(ctx, evt, client, pollPayload)
return
}
@@ -57,7 +58,7 @@ func handleMessage(ctx context.Context, evt *events.Message, chatStorageRepo dom
handleAutoReply(ctx, evt, chatStorageRepo, client)
// Forward to webhook if configured
- handleWebhookForward(ctx, evt, client)
+ handleWebhookForward(ctx, evt, client, pollPayload)
}
func buildMessageMetaParts(evt *events.Message) []string {
@@ -148,7 +149,7 @@ func materializeSecretEditMessage(ctx context.Context, evt *events.Message, clie
return &cloned
}
-func handleWebhookForward(ctx context.Context, evt *events.Message, client *whatsmeow.Client) {
+func handleWebhookForward(ctx context.Context, evt *events.Message, client *whatsmeow.Client, preparedPoll ...*webhookPollPayload) {
// Skip webhook for protocol messages that are internal sync messages
if protocolMessage := evt.Message.GetProtocolMessage(); protocolMessage != nil {
protocolType := protocolMessage.GetType().String()
@@ -173,11 +174,15 @@ 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) {
+ var pollPayload *webhookPollPayload
+ if len(preparedPoll) > 0 {
+ pollPayload = preparedPoll[0]
+ }
+ go func(e *events.Message, c *whatsmeow.Client, poll *webhookPollPayload) {
webhookCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
defer cancel()
- if err := forwardMessageToWebhook(webhookCtx, c, e); err != nil {
+ if err := forwardMessageToWebhook(webhookCtx, c, e, poll); err != nil {
logrus.Error("Failed forward to webhook: ", err)
}
- }(evt, client)
+ }(evt, client, pollPayload)
}
diff --git a/src/infrastructure/whatsapp/event_message_handler_test.go b/src/infrastructure/whatsapp/event_message_handler_test.go
index 38ccd0ce..5268c944 100644
--- a/src/infrastructure/whatsapp/event_message_handler_test.go
+++ b/src/infrastructure/whatsapp/event_message_handler_test.go
@@ -74,6 +74,62 @@ func TestHandleMessageReactionStoresReactionAndForwardsWebhook(t *testing.T) {
}
}
+func TestHandleMessagePersistsPollBeforeForwardingWebhook(t *testing.T) {
+ originalWebhookURLs := config.WhatsappWebhook
+ originalWebhookEvents := config.WhatsappWebhookEvents
+ originalSubmit := submitWebhookFn
+ originalLog := log
+ defer func() {
+ config.WhatsappWebhook = originalWebhookURLs
+ config.WhatsappWebhookEvents = originalWebhookEvents
+ submitWebhookFn = originalSubmit
+ log = originalLog
+ }()
+ log = waLog.Noop
+ config.WhatsappWebhook = []string{"https://example.test/webhook"}
+ config.WhatsappWebhookEvents = nil
+
+ repo := &messageHandlerRepoSpy{}
+ done := make(chan map[string]any, 1)
+ submitWebhookFn = func(_ context.Context, payload map[string]any, _ string, _ *domainChatStorage.DeviceWebhookConfig) error {
+ done <- payload
+ return nil
+ }
+ ctx := ContextWithDevice(context.Background(), NewDeviceInstance("device-a", nil, nil))
+ evt := &events.Message{
+ Info: types.MessageInfo{
+ MessageSource: types.MessageSource{Chat: types.NewJID("120363000000", types.GroupServer)},
+ ID: "POLL-HANDLER-1",
+ Timestamp: time.Date(2026, time.August, 26, 10, 0, 0, 0, time.UTC),
+ },
+ Message: &waE2E.Message{PollCreationMessageV3: &waE2E.PollCreationMessage{
+ Name: protoString("Lunch?"),
+ Options: []*waE2E.PollCreationMessage_Option{
+ {OptionName: protoString("Pizza")},
+ {OptionName: protoString("Sushi")},
+ },
+ }},
+ }
+
+ handleMessage(ctx, evt, repo, nil)
+ select {
+ case delivered := <-done:
+ payload := delivered["payload"].(map[string]any)
+ poll, ok := payload["poll"].(*webhookPollPayload)
+ if !ok || poll.Type != "creation" || len(poll.Options) != 2 || payload["body"] != "Poll: Lunch?" {
+ t.Fatalf("unexpected webhook payload: %+v", payload)
+ }
+ repo.mu.Lock()
+ definition := repo.pollDefinition
+ repo.mu.Unlock()
+ if definition == nil || definition.PollMessageID != "POLL-HANDLER-1" {
+ t.Fatalf("poll was not persisted before webhook delivery: %+v", definition)
+ }
+ case <-time.After(2 * time.Second):
+ t.Fatal("timed out waiting for poll webhook")
+ }
+}
+
func TestHandleWebhookForwardSkipsBroadcastRegardlessOfChatwoot(t *testing.T) {
originalWebhookURLs := config.WhatsappWebhook
originalWebhookEvents := config.WhatsappWebhookEvents
@@ -159,6 +215,29 @@ type messageHandlerRepoSpy struct {
mu sync.Mutex
createMessageCalls int
createReactionCalls int
+ pollDefinition *domainChatStorage.PollDefinition
+}
+
+func (r *messageHandlerRepoSpy) UpsertPollDefinition(definition *domainChatStorage.PollDefinition) error {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ r.pollDefinition = definition
+ return nil
+}
+
+func (r *messageHandlerRepoSpy) GetPollDefinition(_, _, _ string) (*domainChatStorage.PollDefinition, error) {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ return r.pollDefinition, nil
+}
+
+func (r *messageHandlerRepoSpy) AppendPollOption(_, _, _ string, option domainChatStorage.PollOption) error {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ if r.pollDefinition != nil {
+ r.pollDefinition.Options = append(r.pollDefinition.Options, option)
+ }
+ return nil
}
func (r *messageHandlerRepoSpy) CreateMessage(context.Context, *events.Message) error {
diff --git a/src/infrastructure/whatsapp/event_message_test.go b/src/infrastructure/whatsapp/event_message_test.go
index 78690967..08eec010 100644
--- a/src/infrastructure/whatsapp/event_message_test.go
+++ b/src/infrastructure/whatsapp/event_message_test.go
@@ -45,6 +45,44 @@ func TestBuildEventPayloadIncludesIsFromMe(t *testing.T) {
}
}
+func TestBuildEventPayloadIncludesPreparedPollAndStableBody(t *testing.T) {
+ selected := []string{"Sushi"}
+ hashes := []string{pollOptionHash("Sushi")}
+ evt := &events.Message{
+ Info: types.MessageInfo{
+ MessageSource: types.MessageSource{
+ Chat: types.NewJID("120363000000", types.GroupServer),
+ Sender: types.NewJID("628222", types.DefaultUserServer),
+ },
+ ID: "VOTE-1",
+ Timestamp: time.Date(2026, time.August, 26, 10, 0, 0, 0, time.UTC),
+ },
+ Message: &waE2E.Message{PollUpdateMessage: &waE2E.PollUpdateMessage{}},
+ }
+ poll := &webhookPollPayload{
+ Type: "vote",
+ PollID: "POLL-1",
+ Question: "Lunch?",
+ SelectedOptions: &selected,
+ SelectedOptionHashes: &hashes,
+ ResolutionStatus: pollResolutionResolved,
+ }
+
+ eventType, payload, err := buildEventPayload(context.Background(), nil, evt, poll)
+ if err != nil {
+ t.Fatalf("buildEventPayload: %v", err)
+ }
+ if eventType != EventTypeMessage {
+ t.Fatalf("event type = %q, want %q", eventType, EventTypeMessage)
+ }
+ if payload["poll"] != poll {
+ t.Fatalf("poll payload = %#v, want prepared payload", payload["poll"])
+ }
+ if payload["body"] != "Poll vote: Sushi" {
+ t.Fatalf("body = %v, want stable poll summary", payload["body"])
+ }
+}
+
func TestBuildEventPayloadRevokedIncludesIsFromMe(t *testing.T) {
key := &waCommon.MessageKey{
RemoteJID: protoString("[email protected]"),
diff --git a/src/infrastructure/whatsapp/history_sync.go b/src/infrastructure/whatsapp/history_sync.go
index 0237d6d6..f6336fdd 100644
--- a/src/infrastructure/whatsapp/history_sync.go
+++ b/src/infrastructure/whatsapp/history_sync.go
@@ -238,6 +238,13 @@ func processConversationMessages(ctx context.Context, data *waHistorySync.Histor
continue
}
+ if poll, version := utils.ExtractPollCreationMessage(msg.GetMessage()); poll != nil {
+ definition := pollDefinitionFromCreation(deviceID, chatJID, messageID, version, poll, timestamp)
+ if err := chatStorageRepo.UpsertPollDefinition(definition); err != nil {
+ log.Warnf("Failed to store history poll definition %s for chat %s: %v", messageID, chatJID, err)
+ }
+ }
+
// Extract message content and media info
content := utils.ExtractMessageTextFromProto(msg.GetMessage())
mediaType, filename, mediaURL, directPath, mediaKey, fileSHA256, fileEncSHA256, fileLength := utils.ExtractMediaInfo(msg.GetMessage())
diff --git a/src/infrastructure/whatsapp/history_sync_test.go b/src/infrastructure/whatsapp/history_sync_test.go
index 708fae15..4a63990f 100644
--- a/src/infrastructure/whatsapp/history_sync_test.go
+++ b/src/infrastructure/whatsapp/history_sync_test.go
@@ -6,6 +6,7 @@ import (
"time"
domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
+ "github.com/stretchr/testify/assert"
"go.mau.fi/whatsmeow/proto/waCommon"
"go.mau.fi/whatsmeow/proto/waE2E"
"go.mau.fi/whatsmeow/proto/waHistorySync"
@@ -77,12 +78,73 @@ func TestProcessConversationMessagesPersistsReactionEvents(t *testing.T) {
}
}
+func TestProcessConversationMessagesPersistsPollDefinitionWithoutText(t *testing.T) {
+ originalLog := log
+ log = waLog.Noop
+ defer func() { log = originalLog }()
+
+ deviceID := "[email protected]"
+ chatJID := "[email protected]"
+ repo := &historyPollRepoSpy{}
+ ctx := ContextWithDevice(context.Background(), NewDeviceInstance(deviceID, nil, nil))
+ syncType := waHistorySync.HistorySync_RECENT
+ timestamp := uint64(time.Date(2026, time.August, 26, 8, 2, 0, 0, time.UTC).Unix())
+ data := &waHistorySync.HistorySync{
+ SyncType: &syncType,
+ Conversations: []*waHistorySync.Conversation{{
+ ID: proto.String(chatJID),
+ Messages: []*waHistorySync.HistorySyncMsg{{Message: &waWeb.WebMessageInfo{
+ Key: &waCommon.MessageKey{RemoteJID: proto.String(chatJID), ID: proto.String("POLL-HISTORY-1")},
+ Message: &waE2E.Message{PollCreationMessageV3: &waE2E.PollCreationMessage{
+ Name: proto.String("History poll"),
+ Options: []*waE2E.PollCreationMessage_Option{
+ {OptionName: proto.String("One")},
+ {OptionName: proto.String("Two")},
+ },
+ }},
+ MessageTimestamp: &timestamp,
+ }}},
+ }},
+ }
+
+ if err := processConversationMessages(ctx, data, repo, nil); err != nil {
+ t.Fatalf("processConversationMessages: %v", err)
+ }
+ if repo.definition == nil || repo.definition.DeviceID != deviceID || repo.definition.PollMessageID != "POLL-HISTORY-1" {
+ t.Fatalf("poll definition not persisted: %+v", repo.definition)
+ }
+ if repo.definition.Question != "History poll" || len(repo.definition.Options) != 2 || repo.definition.Version != "v3" {
+ t.Fatalf("unexpected poll definition: %+v", repo.definition)
+ }
+ wantTimestamp := time.Unix(int64(timestamp), 0)
+ assert.True(t, repo.definition.UpdatedAt.Equal(wantTimestamp),
+ "poll definition updated_at = %s, want history timestamp %s",
+ repo.definition.UpdatedAt, wantTimestamp)
+}
+
type historyReactionRepoSpy struct {
domainChatStorage.IChatStorageRepository
createReactionCalls int
lastReaction *events.Message
}
+type historyPollRepoSpy struct {
+ domainChatStorage.IChatStorageRepository
+ definition *domainChatStorage.PollDefinition
+}
+
+func (r *historyPollRepoSpy) UpsertPollDefinition(definition *domainChatStorage.PollDefinition) error {
+ r.definition = definition
+ return nil
+}
+
+func (r *historyPollRepoSpy) GetChatNameWithPushName(jid types.JID, _ string, _ string, pushName string) string {
+ if pushName != "" {
+ return pushName
+ }
+ return jid.String()
+}
+
func (r *historyReactionRepoSpy) CreateReaction(_ context.Context, evt *events.Message) error {
r.createReactionCalls++
r.lastReaction = evt
diff --git a/src/infrastructure/whatsapp/poll_event.go b/src/infrastructure/whatsapp/poll_event.go
new file mode 100644
index 00000000..7727c460
--- /dev/null
+++ b/src/infrastructure/whatsapp/poll_event.go
@@ -0,0 +1,384 @@
+package whatsapp
+
+import (
+ "context"
+ "encoding/hex"
+ "fmt"
+ "strings"
+ "time"
+
+ domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
+ "github.com/sirupsen/logrus"
+ "go.mau.fi/whatsmeow"
+ "go.mau.fi/whatsmeow/proto/waE2E"
+ "go.mau.fi/whatsmeow/types"
+ "go.mau.fi/whatsmeow/types/events"
+)
+
+const (
+ pollResolutionResolved = "resolved"
+ pollResolutionPartiallyResolved = "partially_resolved"
+ pollResolutionDefinitionMissing = "definition_missing"
+ pollResolutionDecryptFailed = "decrypt_failed"
+)
+
+type pollDefinitionStore interface {
+ UpsertPollDefinition(definition *domainChatStorage.PollDefinition) error
+ GetPollDefinition(deviceID, chatJID, pollMessageID string) (*domainChatStorage.PollDefinition, error)
+ GetPollDefinitionByIDAndDevice(deviceID, pollMessageID string) (*domainChatStorage.PollDefinition, error)
+ AppendPollOption(deviceID, chatJID, pollMessageID string, option domainChatStorage.PollOption) error
+}
+
+type webhookPollOptionPayload struct {
+ Name string `json:"name"`
+ Hash string `json:"hash"`
+}
+
+type webhookPollPayload struct {
+ Type string `json:"type"`
+ PollID string `json:"poll_id"`
+ Question string `json:"question,omitempty"`
+ Options []webhookPollOptionPayload `json:"options,omitempty"`
+ SelectableOptionCount uint32 `json:"selectable_options_count,omitempty"`
+ Version string `json:"version,omitempty"`
+ SelectedOptions *[]string `json:"selected_options,omitempty"`
+ SelectedOptionHashes *[]string `json:"selected_option_hashes,omitempty"`
+ ResolutionStatus string `json:"resolution_status,omitempty"`
+ AddedOption *webhookPollOptionPayload `json:"added_option,omitempty"`
+}
+
+func pollOptionHash(name string) string {
+ hashes := whatsmeow.HashPollOptions([]string{name})
+ if len(hashes) == 0 {
+ return ""
+ }
+ return hex.EncodeToString(hashes[0])
+}
+
+func pollOptionsFromProto(options []*waE2E.PollCreationMessage_Option) []domainChatStorage.PollOption {
+ result := make([]domainChatStorage.PollOption, 0, len(options))
+ for _, option := range options {
+ if option == nil {
+ continue
+ }
+ name := option.GetOptionName()
+ result = append(result, domainChatStorage.PollOption{Name: name, Hash: pollOptionHash(name)})
+ }
+ return result
+}
+
+func pollDeviceID(ctx context.Context, client *whatsmeow.Client) string {
+ if instance, ok := DeviceFromContext(ctx); ok && instance != nil {
+ if jid := instance.JID(); jid != "" {
+ return jid
+ }
+ return instance.ID()
+ }
+ if client != nil && client.Store != nil && client.Store.ID != nil {
+ return client.Store.ID.ToNonAD().String()
+ }
+ return ""
+}
+
+func pollChatIDs(ctx context.Context, client *whatsmeow.Client, evt *events.Message, referencedChats ...string) []string {
+ if evt == nil {
+ return nil
+ }
+ var result []string
+ seen := make(map[string]struct{})
+ add := func(jid types.JID) {
+ if jid.IsEmpty() {
+ return
+ }
+ for _, candidate := range []string{
+ NormalizeJIDFromLID(ctx, jid, client).ToNonAD().String(),
+ jid.ToNonAD().String(),
+ } {
+ if candidate == "" {
+ continue
+ }
+ if _, exists := seen[candidate]; exists {
+ continue
+ }
+ seen[candidate] = struct{}{}
+ result = append(result, candidate)
+ }
+ }
+ add(evt.Info.Chat)
+ for _, chat := range referencedChats {
+ jid, err := types.ParseJID(chat)
+ if err == nil {
+ add(jid)
+ }
+ }
+ return result
+}
+
+func pollDefinitionFromCreation(deviceID, chatJID, pollID, version string, poll *waE2E.PollCreationMessage, updatedAt ...time.Time) *domainChatStorage.PollDefinition {
+ if poll == nil {
+ return nil
+ }
+ definition := &domainChatStorage.PollDefinition{
+ DeviceID: deviceID,
+ ChatJID: chatJID,
+ PollMessageID: pollID,
+ Question: poll.GetName(),
+ Options: pollOptionsFromProto(poll.GetOptions()),
+ SelectableOptionCount: poll.GetSelectableOptionsCount(),
+ Version: version,
+ }
+ if len(updatedAt) > 0 {
+ definition.UpdatedAt = updatedAt[0]
+ }
+ return definition
+}
+
+func webhookPollFromDefinition(kind string, definition *domainChatStorage.PollDefinition) *webhookPollPayload {
+ payload := &webhookPollPayload{Type: kind}
+ if definition == nil {
+ return payload
+ }
+ payload.PollID = definition.PollMessageID
+ payload.Question = definition.Question
+ payload.SelectableOptionCount = definition.SelectableOptionCount
+ payload.Version = definition.Version
+ payload.Options = make([]webhookPollOptionPayload, 0, len(definition.Options))
+ for _, option := range definition.Options {
+ payload.Options = append(payload.Options, webhookPollOptionPayload{Name: option.Name, Hash: option.Hash})
+ }
+ return payload
+}
+
+func loadPollDefinition(store pollDefinitionStore, deviceID, pollID string, chatIDs ...string) *domainChatStorage.PollDefinition {
+ if store == nil || deviceID == "" || pollID == "" {
+ return nil
+ }
+ seen := make(map[string]struct{})
+ for _, chatID := range chatIDs {
+ if chatID == "" {
+ continue
+ }
+ if _, exists := seen[chatID]; exists {
+ continue
+ }
+ seen[chatID] = struct{}{}
+ definition, err := store.GetPollDefinition(deviceID, chatID, pollID)
+ if err != nil {
+ logrus.Warnf("Failed to load poll definition %s for chat %s: %v", pollID, chatID, err)
+ continue
+ }
+ if definition != nil {
+ return definition
+ }
+ }
+ definition, err := store.GetPollDefinitionByIDAndDevice(deviceID, pollID)
+ if err != nil {
+ logrus.Warnf("Failed to resolve poll definition %s by device-scoped message ID: %v", pollID, err)
+ return nil
+ }
+ return definition
+}
+
+func resolvePollSelections(definition *domainChatStorage.PollDefinition, selected [][]byte) (names, hashes []string, status string) {
+ names = make([]string, 0, len(selected))
+ hashes = make([]string, 0, len(selected))
+ nameByHash := make(map[string]string)
+ if definition != nil {
+ for _, option := range definition.Options {
+ nameByHash[strings.ToLower(option.Hash)] = option.Name
+ }
+ }
+ unmatched := 0
+ for _, selectedHash := range selected {
+ hash := hex.EncodeToString(selectedHash)
+ hashes = append(hashes, hash)
+ if name, ok := nameByHash[hash]; ok {
+ names = append(names, name)
+ } else {
+ unmatched++
+ }
+ }
+ if definition == nil {
+ return names, hashes, pollResolutionDefinitionMissing
+ }
+ if unmatched > 0 {
+ return names, hashes, pollResolutionPartiallyResolved
+ }
+ return names, hashes, pollResolutionResolved
+}
+
+func preparePollWebhookPayload(ctx context.Context, client *whatsmeow.Client, store pollDefinitionStore, evt *events.Message) *webhookPollPayload {
+ if evt == nil || evt.Message == nil {
+ return nil
+ }
+ // The event handler runs with the context captured at registration; for
+ // REST-initiated logins that is the HTTP request context, canceled once
+ // the request returns. Detach so LID normalization and message-secret
+ // reads during vote/edit decryption survive, keeping device-scoped values.
+ ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
+ defer cancel()
+ deviceID := pollDeviceID(ctx, client)
+ chatIDs := pollChatIDs(ctx, client, evt)
+ chatJID := ""
+ if len(chatIDs) > 0 {
+ chatJID = chatIDs[0]
+ }
+ msg := utils.UnwrapMessage(evt.Message)
+
+ if poll, version := utils.ExtractPollCreationMessage(msg); poll != nil {
+ definition := pollDefinitionFromCreation(deviceID, chatJID, evt.Info.ID, version, poll, evt.Info.Timestamp)
+ if store != nil && definition.DeviceID != "" && definition.ChatJID != "" {
+ if err := store.UpsertPollDefinition(definition); err != nil {
+ logrus.Warnf("Failed to persist poll definition %s: %v", evt.Info.ID, err)
+ }
+ }
+ return webhookPollFromDefinition("creation", definition)
+ }
+
+ if update := msg.GetPollUpdateMessage(); update != nil {
+ pollID := update.GetPollCreationMessageKey().GetID()
+ voteChatIDs := pollChatIDs(ctx, client, evt, update.GetPollCreationMessageKey().GetRemoteJID())
+ definition := loadPollDefinition(store, deviceID, pollID, voteChatIDs...)
+ payload := webhookPollFromDefinition("vote", definition)
+ payload.PollID = pollID
+ if client == nil {
+ payload.ResolutionStatus = pollResolutionDecryptFailed
+ return payload
+ }
+ vote, err := client.DecryptPollVote(ctx, evt)
+ if err != nil {
+ logrus.Warnf("Failed to decrypt poll vote %s for poll %s: %v", evt.Info.ID, pollID, err)
+ payload.ResolutionStatus = pollResolutionDecryptFailed
+ return payload
+ }
+ names, hashes, status := resolvePollSelections(definition, vote.GetSelectedOptions())
+ payload.SelectedOptions = &names
+ payload.SelectedOptionHashes = &hashes
+ payload.ResolutionStatus = status
+ return payload
+ }
+
+ if add := msg.GetPollAddOptionMessage(); add != nil {
+ addChatIDs := pollChatIDs(ctx, client, evt, add.GetPollCreationMessageKey().GetRemoteJID())
+ addChatID := chatJID
+ if definition := loadPollDefinition(store, deviceID, add.GetPollCreationMessageKey().GetID(), addChatIDs...); definition != nil {
+ addChatID = definition.ChatJID
+ }
+ return preparePollAddOptionPayload(store, deviceID, addChatID, add)
+ }
+
+ secret := msg.GetSecretEncryptedMessage()
+ if secret == nil || (secret.GetSecretEncType() != waE2E.SecretEncryptedMessage_POLL_EDIT && secret.GetSecretEncType() != waE2E.SecretEncryptedMessage_POLL_ADD_OPTION) {
+ return nil
+ }
+ kind := "edit"
+ if secret.GetSecretEncType() == waE2E.SecretEncryptedMessage_POLL_ADD_OPTION {
+ kind = "add_option"
+ }
+ pollID := secret.GetTargetMessageKey().GetID()
+ updateChatIDs := pollChatIDs(ctx, client, evt, secret.GetTargetMessageKey().GetRemoteJID())
+ degraded := func() *webhookPollPayload {
+ payload := webhookPollFromDefinition(kind, loadPollDefinition(store, deviceID, pollID, updateChatIDs...))
+ payload.PollID = pollID
+ payload.ResolutionStatus = pollResolutionDecryptFailed
+ return payload
+ }
+ if client == nil {
+ return degraded()
+ }
+ decrypted, err := client.DecryptSecretEncryptedMessage(ctx, evt)
+ if err != nil {
+ logrus.Warnf("Failed to decrypt poll update %s for poll %s: %v", evt.Info.ID, pollID, err)
+ return degraded()
+ }
+ decrypted = utils.UnwrapMessage(decrypted)
+ if kind == "add_option" {
+ if add := decrypted.GetPollAddOptionMessage(); add != nil {
+ addChatID := chatJID
+ if definition := loadPollDefinition(store, deviceID, pollID, updateChatIDs...); definition != nil {
+ addChatID = definition.ChatJID
+ }
+ return preparePollAddOptionPayload(store, deviceID, addChatID, add, pollID)
+ }
+ return degraded()
+ }
+ poll, version := utils.ExtractPollCreationMessage(decrypted)
+ if poll == nil {
+ return degraded()
+ }
+ if existing := loadPollDefinition(store, deviceID, pollID, updateChatIDs...); existing != nil {
+ chatJID = existing.ChatJID
+ }
+ definition := pollDefinitionFromCreation(deviceID, chatJID, pollID, version, poll, evt.Info.Timestamp)
+ if store != nil {
+ if err := store.UpsertPollDefinition(definition); err != nil {
+ logrus.Warnf("Failed to persist edited poll definition %s: %v", pollID, err)
+ }
+ }
+ return webhookPollFromDefinition("edit", definition)
+}
+
+func preparePollAddOptionPayload(store pollDefinitionStore, deviceID, chatJID string, add *waE2E.PollAddOptionMessage, fallbackPollID ...string) *webhookPollPayload {
+ if add == nil {
+ return nil
+ }
+ pollID := add.GetPollCreationMessageKey().GetID()
+ if pollID == "" && len(fallbackPollID) > 0 {
+ pollID = fallbackPollID[0]
+ }
+ option := domainChatStorage.PollOption{Name: add.GetAddOption().GetOptionName()}
+ option.Hash = pollOptionHash(option.Name)
+ if store != nil && option.Name != "" {
+ if err := store.AppendPollOption(deviceID, chatJID, pollID, option); err != nil {
+ logrus.Warnf("Failed to append option to poll %s: %v", pollID, err)
+ }
+ }
+ payload := webhookPollFromDefinition("add_option", loadPollDefinition(store, deviceID, pollID, chatJID))
+ payload.PollID = pollID
+ payload.AddedOption = &webhookPollOptionPayload{Name: option.Name, Hash: option.Hash}
+ if payload.Question == "" {
+ payload.ResolutionStatus = pollResolutionDefinitionMissing
+ }
+ return payload
+}
+
+func pollWebhookBody(payload *webhookPollPayload) string {
+ if payload == nil {
+ return ""
+ }
+ switch payload.Type {
+ case "creation":
+ if payload.Question != "" {
+ return "Poll: " + payload.Question
+ }
+ return "Poll"
+ case "edit":
+ if payload.Question != "" {
+ return "Poll edited: " + payload.Question
+ }
+ return "Poll edited"
+ case "add_option":
+ if payload.AddedOption != nil && payload.AddedOption.Name != "" {
+ return "Poll option added: " + payload.AddedOption.Name
+ }
+ return "Poll option added"
+ case "vote":
+ if payload.ResolutionStatus == pollResolutionResolved && payload.SelectedOptions != nil {
+ if len(*payload.SelectedOptions) == 0 {
+ return "Poll vote cleared"
+ }
+ return "Poll vote: " + strings.Join(*payload.SelectedOptions, ", ")
+ }
+ if payload.ResolutionStatus == pollResolutionPartiallyResolved && payload.SelectedOptions != nil && len(*payload.SelectedOptions) > 0 {
+ return fmt.Sprintf("Poll vote: %s (partially resolved)", strings.Join(*payload.SelectedOptions, ", "))
+ }
+ label := strings.ReplaceAll(payload.ResolutionStatus, "_", " ")
+ if payload.PollID != "" {
+ return fmt.Sprintf("Poll vote: %s (%s)", payload.PollID, label)
+ }
+ return "Poll vote (" + label + ")"
+ default:
+ return "Poll"
+ }
+}
diff --git a/src/infrastructure/whatsapp/poll_event_test.go b/src/infrastructure/whatsapp/poll_event_test.go
new file mode 100644
index 00000000..8c80b0c7
--- /dev/null
+++ b/src/infrastructure/whatsapp/poll_event_test.go
@@ -0,0 +1,608 @@
+package whatsapp
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "testing"
+
+ domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
+ projectSQLite "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/sqlite"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+ "go.mau.fi/whatsmeow"
+ "go.mau.fi/whatsmeow/proto/waAdv"
+ "go.mau.fi/whatsmeow/proto/waCommon"
+ "go.mau.fi/whatsmeow/proto/waE2E"
+ "go.mau.fi/whatsmeow/store/sqlstore"
+ "go.mau.fi/whatsmeow/types"
+ "go.mau.fi/whatsmeow/types/events"
+ "go.mau.fi/whatsmeow/util/gcmutil"
+ "go.mau.fi/whatsmeow/util/hkdfutil"
+ waLog "go.mau.fi/whatsmeow/util/log"
+ "google.golang.org/protobuf/proto"
+)
+
+type memoryPollStore struct {
+ definitions map[string]*domainChatStorage.PollDefinition
+}
+
+func newMemoryPollStore() *memoryPollStore {
+ return &memoryPollStore{definitions: make(map[string]*domainChatStorage.PollDefinition)}
+}
+
+func pollStoreKey(deviceID, chatJID, pollID string) string {
+ return deviceID + "\x00" + chatJID + "\x00" + pollID
+}
+
+func (s *memoryPollStore) UpsertPollDefinition(definition *domainChatStorage.PollDefinition) error {
+ copyDefinition := *definition
+ copyDefinition.Options = append([]domainChatStorage.PollOption(nil), definition.Options...)
+ s.definitions[pollStoreKey(definition.DeviceID, definition.ChatJID, definition.PollMessageID)] = &copyDefinition
+ return nil
+}
+
+func (s *memoryPollStore) GetPollDefinition(deviceID, chatJID, pollMessageID string) (*domainChatStorage.PollDefinition, error) {
+ definition := s.definitions[pollStoreKey(deviceID, chatJID, pollMessageID)]
+ if definition == nil {
+ return nil, nil
+ }
+ copyDefinition := *definition
+ copyDefinition.Options = append([]domainChatStorage.PollOption(nil), definition.Options...)
+ return &copyDefinition, nil
+}
+
+func (s *memoryPollStore) GetPollDefinitionByIDAndDevice(deviceID, pollMessageID string) (*domainChatStorage.PollDefinition, error) {
+ var match *domainChatStorage.PollDefinition
+ for _, definition := range s.definitions {
+ if definition.DeviceID != deviceID || definition.PollMessageID != pollMessageID {
+ continue
+ }
+ if match != nil {
+ return nil, fmt.Errorf("poll definition %s is ambiguous", pollMessageID)
+ }
+ copyDefinition := *definition
+ copyDefinition.Options = append([]domainChatStorage.PollOption(nil), definition.Options...)
+ match = &copyDefinition
+ }
+ return match, nil
+}
+
+func (s *memoryPollStore) AppendPollOption(deviceID, chatJID, pollMessageID string, option domainChatStorage.PollOption) error {
+ definition := s.definitions[pollStoreKey(deviceID, chatJID, pollMessageID)]
+ if definition == nil {
+ return fmt.Errorf("poll definition %s not found", pollMessageID)
+ }
+ for _, existing := range definition.Options {
+ if existing.Hash == option.Hash {
+ return nil
+ }
+ }
+ definition.Options = append(definition.Options, option)
+ return nil
+}
+
+func TestPreparePollWebhookPayloadStoresCreation(t *testing.T) {
+ store := newMemoryPollStore()
+ ctx := ContextWithDevice(context.Background(), NewDeviceInstance("device-a", nil, nil))
+ evt := &events.Message{
+ Info: types.MessageInfo{
+ MessageSource: types.MessageSource{Chat: types.NewJID("120363000000", types.GroupServer)},
+ ID: "POLL-1",
+ },
+ Message: &waE2E.Message{PollCreationMessageV3: &waE2E.PollCreationMessage{
+ Name: proto.String("Lunch?"),
+ SelectableOptionsCount: proto.Uint32(1),
+ Options: []*waE2E.PollCreationMessage_Option{
+ {OptionName: proto.String("Pizza")},
+ {OptionName: proto.String("Sushi")},
+ },
+ }},
+ }
+
+ payload := preparePollWebhookPayload(ctx, nil, store, evt)
+ if payload == nil || payload.Type != "creation" || payload.PollID != "POLL-1" || payload.Question != "Lunch?" {
+ t.Fatalf("unexpected payload: %+v", payload)
+ }
+ if len(payload.Options) != 2 || payload.Options[1].Name != "Sushi" || payload.Options[1].Hash == "" {
+ t.Fatalf("unexpected options: %+v", payload.Options)
+ }
+ stored, err := store.GetPollDefinition("device-a", evt.Info.Chat.String(), "POLL-1")
+ if err != nil || stored == nil || stored.Version != "v3" || len(stored.Options) != 2 {
+ t.Fatalf("stored definition=%+v err=%v", stored, err)
+ }
+}
+
+func TestResolvePollSelectionsStatuses(t *testing.T) {
+ definition := &domainChatStorage.PollDefinition{Options: []domainChatStorage.PollOption{
+ {Name: "Pizza", Hash: pollOptionHash("Pizza")},
+ {Name: "Sushi", Hash: pollOptionHash("Sushi")},
+ }}
+
+ t.Run("resolved", func(t *testing.T) {
+ names, hashes, status := resolvePollSelections(definition, [][]byte{
+ whatsmeow.HashPollOptions([]string{"Sushi"})[0],
+ })
+ if status != "resolved" || len(names) != 1 || names[0] != "Sushi" || len(hashes) != 1 {
+ t.Fatalf("names=%v hashes=%v status=%s", names, hashes, status)
+ }
+ })
+
+ t.Run("cleared", func(t *testing.T) {
+ names, hashes, status := resolvePollSelections(definition, nil)
+ if status != "resolved" || names == nil || hashes == nil || len(names) != 0 || len(hashes) != 0 {
+ t.Fatalf("names=%v hashes=%v status=%s", names, hashes, status)
+ }
+ })
+
+ t.Run("partially resolved", func(t *testing.T) {
+ names, hashes, status := resolvePollSelections(definition, [][]byte{
+ whatsmeow.HashPollOptions([]string{"Pizza"})[0],
+ bytes.Repeat([]byte{0xff}, 32),
+ })
+ if status != "partially_resolved" || len(names) != 1 || len(hashes) != 2 {
+ t.Fatalf("names=%v hashes=%v status=%s", names, hashes, status)
+ }
+ })
+
+ t.Run("definition missing", func(t *testing.T) {
+ names, hashes, status := resolvePollSelections(nil, [][]byte{
+ whatsmeow.HashPollOptions([]string{"Pizza"})[0],
+ })
+ if status != "definition_missing" || names == nil || len(names) != 0 || len(hashes) != 1 {
+ t.Fatalf("names=%v hashes=%v status=%s", names, hashes, status)
+ }
+ })
+}
+
+func TestPreparePollWebhookPayloadDecryptsRealVote(t *testing.T) {
+ ctx := context.Background()
+ container, err := sqlstore.New(ctx, projectSQLite.DriverName, projectSQLite.FormatChatStorageURI("file:poll-event-test?mode=memory&cache=shared", false, true), nil)
+ if err != nil {
+ t.Fatalf("sqlstore.New: %v", err)
+ }
+ defer container.Close()
+
+ device := container.NewDevice()
+ voter := types.NewJID("628222", types.DefaultUserServer)
+ device.ID = &voter
+ device.Account = &waAdv.ADVSignedDeviceIdentity{
+ Details: []byte{0},
+ AccountSignatureKey: make([]byte, 32),
+ AccountSignature: make([]byte, 64),
+ DeviceSignature: make([]byte, 64),
+ }
+ if err := device.Save(ctx); err != nil {
+ t.Fatalf("device.Save: %v", err)
+ }
+ client := whatsmeow.NewClient(device, nil)
+ chat := types.NewJID("120363000000", types.GroupServer)
+ creator := types.NewJID("628111", types.DefaultUserServer)
+ pollID := types.MessageID("POLL-CRYPTO-1")
+ if err := device.MsgSecrets.PutMessageSecret(ctx, chat, creator, pollID, bytes.Repeat([]byte{0x42}, 32)); err != nil {
+ t.Fatalf("PutMessageSecret: %v", err)
+ }
+
+ voteMessage, err := client.BuildPollVote(ctx, &types.MessageInfo{
+ MessageSource: types.MessageSource{Chat: chat, Sender: creator, IsGroup: true},
+ ID: pollID,
+ }, []string{"Sushi"})
+ if err != nil {
+ t.Fatalf("BuildPollVote: %v", err)
+ }
+ store := newMemoryPollStore()
+ if err := store.UpsertPollDefinition(&domainChatStorage.PollDefinition{
+ DeviceID: voter.String(), ChatJID: chat.String(), PollMessageID: string(pollID), Question: "Lunch?",
+ Options: []domainChatStorage.PollOption{
+ {Name: "Pizza", Hash: pollOptionHash("Pizza")},
+ {Name: "Sushi", Hash: pollOptionHash("Sushi")},
+ },
+ }); err != nil {
+ t.Fatalf("UpsertPollDefinition: %v", err)
+ }
+
+ payload := preparePollWebhookPayload(ctx, client, store, &events.Message{
+ Info: types.MessageInfo{
+ MessageSource: types.MessageSource{Chat: chat, Sender: voter, IsGroup: true, IsFromMe: true},
+ ID: "VOTE-1",
+ },
+ Message: voteMessage,
+ })
+ if payload == nil || payload.ResolutionStatus != "resolved" || payload.SelectedOptions == nil || len(*payload.SelectedOptions) != 1 || (*payload.SelectedOptions)[0] != "Sushi" {
+ t.Fatalf("unexpected decrypted payload: %+v", payload)
+ }
+
+ badContainer, err := sqlstore.New(ctx, projectSQLite.DriverName, projectSQLite.FormatChatStorageURI("file:poll-event-bad-secret-test?mode=memory&cache=shared", false, true), nil)
+ if err != nil {
+ t.Fatalf("bad sqlstore.New: %v", err)
+ }
+ defer badContainer.Close()
+ badDevice := badContainer.NewDevice()
+ badDevice.ID = &voter
+ badDevice.Account = &waAdv.ADVSignedDeviceIdentity{
+ Details: []byte{0},
+ AccountSignatureKey: make([]byte, 32),
+ AccountSignature: make([]byte, 64),
+ DeviceSignature: make([]byte, 64),
+ }
+ if err := badDevice.Save(ctx); err != nil {
+ t.Fatalf("bad device.Save: %v", err)
+ }
+ if err := badDevice.MsgSecrets.PutMessageSecret(ctx, chat, creator, pollID, bytes.Repeat([]byte{0x99}, 32)); err != nil {
+ t.Fatalf("store mismatched message secret: %v", err)
+ }
+ failed := preparePollWebhookPayload(ctx, whatsmeow.NewClient(badDevice, nil), store, &events.Message{
+ Info: types.MessageInfo{
+ MessageSource: types.MessageSource{Chat: chat, Sender: voter, IsGroup: true, IsFromMe: true},
+ ID: "VOTE-FAILED-1",
+ },
+ Message: voteMessage,
+ })
+ if failed == nil || failed.ResolutionStatus != pollResolutionDecryptFailed || failed.Question != "Lunch?" || failed.SelectedOptions != nil || failed.SelectedOptionHashes != nil {
+ t.Fatalf("unexpected authentication-failure payload: %+v", failed)
+ }
+}
+
+// newPollCryptoClient builds a whatsmeow client over an isolated in-memory
+// device store so tests can exercise real message-secret encryption.
+func newPollCryptoClient(t *testing.T, dbName string, deviceJID types.JID) *whatsmeow.Client {
+ t.Helper()
+ ctx := context.Background()
+ container, err := sqlstore.New(ctx, projectSQLite.DriverName, projectSQLite.FormatChatStorageURI("file:"+dbName+"?mode=memory&cache=shared", false, true), nil)
+ require.NoError(t, err)
+ t.Cleanup(func() { _ = container.Close() })
+ device := container.NewDevice()
+ device.ID = &deviceJID
+ device.Account = &waAdv.ADVSignedDeviceIdentity{
+ Details: []byte{0},
+ AccountSignatureKey: make([]byte, 32),
+ AccountSignature: make([]byte, 64),
+ DeviceSignature: make([]byte, 64),
+ }
+ require.NoError(t, device.Save(ctx))
+ return whatsmeow.NewClient(device, nil)
+}
+
+func TestPreparePollWebhookPayloadDecryptsVoteAfterHandlerContextCanceled(t *testing.T) {
+ setupCtx := context.Background()
+ voter := types.NewJID("628222", types.DefaultUserServer)
+ client := newPollCryptoClient(t, "poll-event-canceled-ctx-test", voter)
+ chat := types.NewJID("120363000000", types.GroupServer)
+ creator := types.NewJID("628111", types.DefaultUserServer)
+ pollID := types.MessageID("POLL-CANCELED-CTX-1")
+ require.NoError(t, client.Store.MsgSecrets.PutMessageSecret(setupCtx, chat, creator, pollID, bytes.Repeat([]byte{0x42}, 32)))
+
+ voteMessage, err := client.BuildPollVote(setupCtx, &types.MessageInfo{
+ MessageSource: types.MessageSource{Chat: chat, Sender: creator, IsGroup: true},
+ ID: pollID,
+ }, []string{"Sushi"})
+ require.NoError(t, err)
+ store := newMemoryPollStore()
+ require.NoError(t, store.UpsertPollDefinition(&domainChatStorage.PollDefinition{
+ DeviceID: voter.String(), ChatJID: chat.String(), PollMessageID: string(pollID), Question: "Lunch?",
+ Options: []domainChatStorage.PollOption{
+ {Name: "Pizza", Hash: pollOptionHash("Pizza")},
+ {Name: "Sushi", Hash: pollOptionHash("Sushi")},
+ },
+ }))
+
+ // The whatsmeow event handler runs with the context captured at
+ // registration; for REST-initiated logins that is the HTTP request
+ // context, already canceled by the time later poll events arrive.
+ handlerCtx, cancelHandlerCtx := context.WithCancel(context.Background())
+ cancelHandlerCtx()
+
+ payload := preparePollWebhookPayload(handlerCtx, client, store, &events.Message{
+ Info: types.MessageInfo{
+ MessageSource: types.MessageSource{Chat: chat, Sender: voter, IsGroup: true, IsFromMe: true},
+ ID: "VOTE-CANCELED-CTX-1",
+ },
+ Message: voteMessage,
+ })
+ require.NotNil(t, payload)
+ assert.Equal(t, pollResolutionResolved, payload.ResolutionStatus)
+ require.NotNil(t, payload.SelectedOptions)
+ assert.Equal(t, []string{"Sushi"}, *payload.SelectedOptions)
+}
+
+func TestPreparePollWebhookPayloadDegradesAddOptionWithoutInnerMessage(t *testing.T) {
+ ctx := context.Background()
+ voter := types.NewJID("628222", types.DefaultUserServer)
+ client := newPollCryptoClient(t, "poll-event-add-option-empty-test", voter)
+ chat := types.NewJID("120363000000", types.GroupServer)
+ pollID := "POLL-ADD-EMPTY-1"
+ secret := bytes.Repeat([]byte{0x37}, 32)
+ require.NoError(t, client.Store.MsgSecrets.PutMessageSecret(ctx, chat, voter, pollID, secret))
+
+ store := newMemoryPollStore()
+ require.NoError(t, store.UpsertPollDefinition(&domainChatStorage.PollDefinition{
+ DeviceID: voter.String(), ChatJID: chat.String(), PollMessageID: pollID, Question: "Lunch?",
+ Options: []domainChatStorage.PollOption{{Name: "Pizza", Hash: pollOptionHash("Pizza")}},
+ }))
+
+ // Encrypt an inner message that carries no PollAddOptionMessage, using the
+ // same "Poll Edit" secret derivation whatsmeow applies to POLL_ADD_OPTION.
+ plaintext, err := proto.Marshal(&waE2E.Message{})
+ require.NoError(t, err)
+ useCaseSecret := pollID + voter.ToNonAD().String() + voter.ToNonAD().String() + "Poll Edit"
+ secretKey := hkdfutil.SHA256(secret, nil, []byte(useCaseSecret), 32)
+ iv := bytes.Repeat([]byte{0x11}, 12)
+ ciphertext, err := gcmutil.Encrypt(secretKey, iv, plaintext, nil)
+ require.NoError(t, err)
+
+ payload := preparePollWebhookPayload(ctx, client, store, &events.Message{
+ Info: types.MessageInfo{
+ MessageSource: types.MessageSource{Chat: chat, Sender: voter, IsGroup: true, IsFromMe: true},
+ ID: "ADD-EMPTY-1",
+ },
+ Message: &waE2E.Message{SecretEncryptedMessage: &waE2E.SecretEncryptedMessage{
+ SecretEncType: waE2E.SecretEncryptedMessage_POLL_ADD_OPTION.Enum(),
+ TargetMessageKey: &waCommon.MessageKey{RemoteJID: proto.String(chat.String()), FromMe: proto.Bool(true), ID: proto.String(pollID)},
+ EncIV: iv,
+ EncPayload: ciphertext,
+ }},
+ })
+ require.NotNil(t, payload)
+ assert.Equal(t, "add_option", payload.Type)
+ assert.Equal(t, pollID, payload.PollID)
+ assert.Equal(t, "Lunch?", payload.Question)
+ assert.Equal(t, pollResolutionDecryptFailed, payload.ResolutionStatus)
+ assert.Nil(t, payload.AddedOption)
+}
+
+func TestPreparePollWebhookPayloadDecryptsLIDGroupVote(t *testing.T) {
+ ctx := context.Background()
+ container, err := sqlstore.New(ctx, projectSQLite.DriverName, projectSQLite.FormatChatStorageURI("file:poll-event-lid-test?mode=memory&cache=shared", false, true), nil)
+ if err != nil {
+ t.Fatalf("sqlstore.New: %v", err)
+ }
+ defer container.Close()
+
+ device := container.NewDevice()
+ voterPN := types.NewJID("628222", types.DefaultUserServer)
+ voterLID := types.NewJID("222000000000", types.HiddenUserServer)
+ device.ID = &voterPN
+ device.LID = voterLID
+ device.Account = &waAdv.ADVSignedDeviceIdentity{
+ Details: []byte{0},
+ AccountSignatureKey: make([]byte, 32),
+ AccountSignature: make([]byte, 64),
+ DeviceSignature: make([]byte, 64),
+ }
+ if err := device.Save(ctx); err != nil {
+ t.Fatalf("device.Save: %v", err)
+ }
+ client := whatsmeow.NewClient(device, nil)
+ chat := types.NewJID("120363000001", types.GroupServer)
+ creatorLID := types.NewJID("111000000000", types.HiddenUserServer)
+ pollID := types.MessageID("POLL-LID-1")
+ if err := device.MsgSecrets.PutMessageSecret(ctx, chat, creatorLID, pollID, bytes.Repeat([]byte{0x24}, 32)); err != nil {
+ t.Fatalf("PutMessageSecret: %v", err)
+ }
+ voteMessage, err := client.BuildPollVote(ctx, &types.MessageInfo{
+ MessageSource: types.MessageSource{Chat: chat, Sender: creatorLID, IsGroup: true, AddressingMode: types.AddressingModeLID},
+ ID: pollID,
+ }, []string{"Yes"})
+ if err != nil {
+ t.Fatalf("BuildPollVote: %v", err)
+ }
+ store := newMemoryPollStore()
+ if err := store.UpsertPollDefinition(&domainChatStorage.PollDefinition{
+ DeviceID: voterPN.String(), ChatJID: chat.String(), PollMessageID: string(pollID), Question: "LID poll",
+ Options: []domainChatStorage.PollOption{{Name: "Yes", Hash: pollOptionHash("Yes")}},
+ }); err != nil {
+ t.Fatalf("UpsertPollDefinition: %v", err)
+ }
+ payload := preparePollWebhookPayload(ctx, client, store, &events.Message{
+ Info: types.MessageInfo{
+ MessageSource: types.MessageSource{Chat: chat, Sender: voterLID, IsGroup: true, IsFromMe: true, AddressingMode: types.AddressingModeLID},
+ ID: "VOTE-LID-1",
+ },
+ Message: voteMessage,
+ })
+ if payload == nil || payload.ResolutionStatus != pollResolutionResolved || payload.SelectedOptions == nil || len(*payload.SelectedOptions) != 1 || (*payload.SelectedOptions)[0] != "Yes" {
+ t.Fatalf("unexpected LID payload: %+v", payload)
+ }
+}
+
+func TestPreparePollWebhookPayloadFindsDefinitionStoredBeforeLIDMapping(t *testing.T) {
+ originalLog := log
+ log = waLog.Noop
+ defer func() { log = originalLog }()
+
+ ctx := context.Background()
+ voterPN := types.NewJID("628222", types.DefaultUserServer)
+ voterLID := types.NewJID("222000000000", types.HiddenUserServer)
+ chatPN := types.NewJID("628111", types.DefaultUserServer)
+ chatLID := types.NewJID("111000000000", types.HiddenUserServer)
+ client := newPollCryptoClient(t, "poll-event-late-lid-map-test", voterPN)
+ client.Store.LID = voterLID
+ pollID := types.MessageID("POLL-LATE-LID-1")
+ require.NoError(t, client.Store.MsgSecrets.PutMessageSecret(ctx, chatLID, chatLID, pollID, bytes.Repeat([]byte{0x63}, 32)))
+
+ voteMessage, err := client.BuildPollVote(ctx, &types.MessageInfo{
+ MessageSource: types.MessageSource{
+ Chat: chatLID,
+ Sender: chatLID,
+ AddressingMode: types.AddressingModeLID,
+ },
+ ID: pollID,
+ }, []string{"Yes"})
+ require.NoError(t, err)
+
+ store := newMemoryPollStore()
+ require.NoError(t, store.UpsertPollDefinition(&domainChatStorage.PollDefinition{
+ DeviceID: voterPN.String(),
+ ChatJID: chatLID.String(),
+ PollMessageID: string(pollID),
+ Question: "Mapped later?",
+ Options: []domainChatStorage.PollOption{{Name: "Yes", Hash: pollOptionHash("Yes")}},
+ }))
+
+ // The poll was stored while the chat only had a LID. The mapping becomes
+ // available before the vote, so normalization now produces the PN alias.
+ require.NoError(t, client.Store.LIDs.PutLIDMapping(ctx, chatLID, chatPN))
+ payload := preparePollWebhookPayload(ctx, client, store, &events.Message{
+ Info: types.MessageInfo{
+ MessageSource: types.MessageSource{
+ Chat: chatLID,
+ Sender: voterLID,
+ IsFromMe: true,
+ AddressingMode: types.AddressingModeLID,
+ },
+ ID: "VOTE-LATE-LID-1",
+ },
+ Message: voteMessage,
+ })
+ require.NotNil(t, payload)
+ assert.Equal(t, pollResolutionResolved, payload.ResolutionStatus)
+ require.NotNil(t, payload.SelectedOptions)
+ assert.Equal(t, []string{"Yes"}, *payload.SelectedOptions)
+}
+
+func TestPreparePollWebhookPayloadFindsPNDefinitionForUnmappedLIDVote(t *testing.T) {
+ originalLog := log
+ log = waLog.Noop
+ defer func() { log = originalLog }()
+
+ ctx := context.Background()
+ voterPN := types.NewJID("628222", types.DefaultUserServer)
+ voterLID := types.NewJID("222000000000", types.HiddenUserServer)
+ chatPN := types.NewJID("628111", types.DefaultUserServer)
+ chatLID := types.NewJID("111000000000", types.HiddenUserServer)
+ client := newPollCryptoClient(t, "poll-event-unmapped-lid-test", voterPN)
+ client.Store.LID = voterLID
+ pollID := types.MessageID("POLL-UNMAPPED-LID-1")
+ require.NoError(t, client.Store.MsgSecrets.PutMessageSecret(ctx, chatLID, chatLID, pollID, bytes.Repeat([]byte{0x73}, 32)))
+
+ voteMessage, err := client.BuildPollVote(ctx, &types.MessageInfo{
+ MessageSource: types.MessageSource{
+ Chat: chatLID,
+ Sender: chatLID,
+ AddressingMode: types.AddressingModeLID,
+ },
+ ID: pollID,
+ }, []string{"Yes"})
+ require.NoError(t, err)
+
+ store := newMemoryPollStore()
+ require.NoError(t, store.UpsertPollDefinition(&domainChatStorage.PollDefinition{
+ DeviceID: voterPN.String(),
+ ChatJID: chatPN.String(),
+ PollMessageID: string(pollID),
+ Question: "PN creation",
+ Options: []domainChatStorage.PollOption{{Name: "Yes", Hash: pollOptionHash("Yes")}},
+ }))
+
+ // No LID mapping is available. The poll message ID is the only stable chat-
+ // independent identity shared by the PN creation and the LID-only vote.
+ payload := preparePollWebhookPayload(ctx, client, store, &events.Message{
+ Info: types.MessageInfo{
+ MessageSource: types.MessageSource{
+ Chat: chatLID,
+ Sender: voterLID,
+ IsFromMe: true,
+ AddressingMode: types.AddressingModeLID,
+ },
+ ID: "VOTE-UNMAPPED-LID-1",
+ },
+ Message: voteMessage,
+ })
+ require.NotNil(t, payload)
+ assert.Equal(t, pollResolutionResolved, payload.ResolutionStatus)
+ require.NotNil(t, payload.SelectedOptions)
+ assert.Equal(t, []string{"Yes"}, *payload.SelectedOptions)
+}
+
+func TestPreparePollWebhookPayloadAppliesAddOptionIdempotently(t *testing.T) {
+ store := newMemoryPollStore()
+ deviceID := "device-a"
+ chat := types.NewJID("120363000000", types.GroupServer)
+ ctx := ContextWithDevice(context.Background(), NewDeviceInstance(deviceID, nil, nil))
+ if err := store.UpsertPollDefinition(&domainChatStorage.PollDefinition{
+ DeviceID: deviceID, ChatJID: chat.String(), PollMessageID: "POLL-ADD-1", Question: "Lunch?",
+ Options: []domainChatStorage.PollOption{{Name: "Pizza", Hash: pollOptionHash("Pizza")}},
+ }); err != nil {
+ t.Fatalf("UpsertPollDefinition: %v", err)
+ }
+ evt := &events.Message{
+ Info: types.MessageInfo{MessageSource: types.MessageSource{Chat: chat}, ID: "ADD-1"},
+ Message: &waE2E.Message{PollAddOptionMessage: &waE2E.PollAddOptionMessage{
+ PollCreationMessageKey: &waCommon.MessageKey{ID: proto.String("POLL-ADD-1")},
+ AddOption: &waE2E.PollCreationMessage_Option{OptionName: proto.String("Sushi")},
+ }},
+ }
+
+ for range 2 {
+ payload := preparePollWebhookPayload(ctx, nil, store, evt)
+ if payload == nil || payload.Type != "add_option" || payload.AddedOption == nil || payload.AddedOption.Name != "Sushi" {
+ t.Fatalf("unexpected add-option payload: %+v", payload)
+ }
+ }
+ definition, err := store.GetPollDefinition(deviceID, chat.String(), "POLL-ADD-1")
+ if err != nil || definition == nil || len(definition.Options) != 2 || definition.Options[1].Name != "Sushi" {
+ t.Fatalf("definition=%+v err=%v", definition, err)
+ }
+}
+
+func TestPreparePollWebhookPayloadDegradesEncryptedPollUpdateWithoutClient(t *testing.T) {
+ store := newMemoryPollStore()
+ deviceID := "device-a"
+ chat := types.NewJID("120363000000", types.GroupServer)
+ ctx := ContextWithDevice(context.Background(), NewDeviceInstance(deviceID, nil, nil))
+ if err := store.UpsertPollDefinition(&domainChatStorage.PollDefinition{
+ DeviceID: deviceID, ChatJID: chat.String(), PollMessageID: "POLL-EDIT-1", Question: "Old question",
+ }); err != nil {
+ t.Fatalf("UpsertPollDefinition: %v", err)
+ }
+ payload := preparePollWebhookPayload(ctx, nil, store, &events.Message{
+ Info: types.MessageInfo{MessageSource: types.MessageSource{Chat: chat}, ID: "EDIT-1"},
+ Message: &waE2E.Message{SecretEncryptedMessage: &waE2E.SecretEncryptedMessage{
+ SecretEncType: waE2E.SecretEncryptedMessage_POLL_EDIT.Enum(),
+ TargetMessageKey: &waCommon.MessageKey{ID: proto.String("POLL-EDIT-1")},
+ }},
+ })
+ if payload == nil || payload.Type != "edit" || payload.PollID != "POLL-EDIT-1" || payload.Question != "Old question" || payload.ResolutionStatus != pollResolutionDecryptFailed {
+ t.Fatalf("unexpected degraded payload: %+v", payload)
+ }
+}
+
+func TestWebhookPollPayloadKeepsClearedSelectionArrays(t *testing.T) {
+ names := make([]string, 0)
+ hashes := make([]string, 0)
+ encoded, err := json.Marshal(&webhookPollPayload{
+ Type: "vote", PollID: "POLL-1", SelectedOptions: &names, SelectedOptionHashes: &hashes,
+ ResolutionStatus: pollResolutionResolved,
+ })
+ if err != nil {
+ t.Fatalf("json.Marshal: %v", err)
+ }
+ var decoded map[string]any
+ if err := json.Unmarshal(encoded, &decoded); err != nil {
+ t.Fatalf("json.Unmarshal: %v", err)
+ }
+ if selected, ok := decoded["selected_options"].([]any); !ok || len(selected) != 0 {
+ t.Fatalf("selected_options missing or non-empty: %#v", decoded["selected_options"])
+ }
+ if selected, ok := decoded["selected_option_hashes"].([]any); !ok || len(selected) != 0 {
+ t.Fatalf("selected_option_hashes missing or non-empty: %#v", decoded["selected_option_hashes"])
+ }
+}
+
+func TestPreparePollAddOptionPayloadUsesEncryptedEnvelopePollID(t *testing.T) {
+ store := newMemoryPollStore()
+ deviceID := "device-a"
+ chatJID := "[email protected]"
+ if err := store.UpsertPollDefinition(&domainChatStorage.PollDefinition{
+ DeviceID: deviceID, ChatJID: chatJID, PollMessageID: "POLL-FALLBACK-1", Question: "Q",
+ }); err != nil {
+ t.Fatalf("UpsertPollDefinition: %v", err)
+ }
+ payload := preparePollAddOptionPayload(store, deviceID, chatJID, &waE2E.PollAddOptionMessage{
+ AddOption: &waE2E.PollCreationMessage_Option{OptionName: proto.String("New")},
+ }, "POLL-FALLBACK-1")
+ if payload == nil || payload.PollID != "POLL-FALLBACK-1" || payload.Question != "Q" {
+ t.Fatalf("unexpected payload: %+v", payload)
+ }
+}
diff --git a/src/pkg/utils/whatsapp.go b/src/pkg/utils/whatsapp.go
index 40017900..f99e6c0a 100644
--- a/src/pkg/utils/whatsapp.go
+++ b/src/pkg/utils/whatsapp.go
@@ -252,6 +252,34 @@ func ExtractMessageTextFromProto(msg *waE2E.Message) string {
return ""
}
+// ExtractPollCreationMessage returns the poll creation payload regardless of
+// which versioned Message field WhatsApp used. V4 is a FutureProofMessage
+// wrapper whose inner message carries the actual poll creation.
+func ExtractPollCreationMessage(msg *waE2E.Message) (*waE2E.PollCreationMessage, string) {
+ msg = UnwrapMessage(msg)
+ if msg == nil {
+ return nil, ""
+ }
+
+ switch {
+ case msg.GetPollCreationMessage() != nil:
+ return msg.GetPollCreationMessage(), "v1"
+ case msg.GetPollCreationMessageV2() != nil:
+ return msg.GetPollCreationMessageV2(), "v2"
+ case msg.GetPollCreationMessageV3() != nil:
+ return msg.GetPollCreationMessageV3(), "v3"
+ case msg.GetPollCreationMessageV4().GetMessage() != nil:
+ inner, _ := ExtractPollCreationMessage(msg.GetPollCreationMessageV4().GetMessage())
+ return inner, "v4"
+ case msg.GetPollCreationMessageV5() != nil:
+ return msg.GetPollCreationMessageV5(), "v5"
+ case msg.GetPollCreationMessageV6() != nil:
+ return msg.GetPollCreationMessageV6(), "v6"
+ default:
+ return nil, ""
+ }
+}
+
// ExtractMediaCaption extracts caption text from media messages (image, video, document, PTV).
func ExtractMediaCaption(msg *waE2E.Message) string {
if msg == nil {
@@ -482,12 +510,12 @@ func BuildForwardMessageFromStorage(message *domainChatStorage.Message, opts For
}
var (
- mediaURL string
- directPath string
- mediaKey []byte
- fileSHA256 []byte
- fileEncSHA256 []byte
- fileLength uint64
+ mediaURL string
+ directPath string
+ mediaKey []byte
+ fileSHA256 []byte
+ fileEncSHA256 []byte
+ fileLength uint64
)
if opts.Upload != nil {
diff --git a/src/pkg/utils/whatsapp_poll_test.go b/src/pkg/utils/whatsapp_poll_test.go
new file mode 100644
index 00000000..f0e41831
--- /dev/null
+++ b/src/pkg/utils/whatsapp_poll_test.go
@@ -0,0 +1,58 @@
+package utils
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+ "go.mau.fi/whatsmeow/proto/waE2E"
+ "google.golang.org/protobuf/proto"
+)
+
+func TestExtractPollCreationMessageSupportsAllVersions(t *testing.T) {
+ poll := func(question string) *waE2E.PollCreationMessage {
+ return &waE2E.PollCreationMessage{Name: proto.String(question)}
+ }
+
+ tests := []struct {
+ name string
+ message *waE2E.Message
+ wantVersion string
+ }{
+ {name: "v1", message: &waE2E.Message{PollCreationMessage: poll("v1")}, wantVersion: "v1"},
+ {name: "v2", message: &waE2E.Message{PollCreationMessageV2: poll("v2")}, wantVersion: "v2"},
+ {name: "v3", message: &waE2E.Message{PollCreationMessageV3: poll("v3")}, wantVersion: "v3"},
+ {
+ name: "v4 future proof wrapper",
+ message: &waE2E.Message{PollCreationMessageV4: &waE2E.FutureProofMessage{
+ Message: &waE2E.Message{PollCreationMessage: poll("v4")},
+ }},
+ wantVersion: "v4",
+ },
+ {name: "v5", message: &waE2E.Message{PollCreationMessageV5: poll("v5")}, wantVersion: "v5"},
+ {name: "v6", message: &waE2E.Message{PollCreationMessageV6: poll("v6")}, wantVersion: "v6"},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got, version := ExtractPollCreationMessage(tt.message)
+ require.NotNil(t, got)
+ assert.Equal(t, tt.wantVersion, version)
+ assert.Equal(t, tt.wantVersion, got.GetName())
+ })
+ }
+}
+
+func TestExtractPollCreationMessageHandlesNilAndWrappedMessages(t *testing.T) {
+ poll, version := ExtractPollCreationMessage(nil)
+ assert.Nil(t, poll)
+ assert.Empty(t, version)
+
+ wrapper := &waE2E.Message{EphemeralMessage: &waE2E.FutureProofMessage{
+ Message: &waE2E.Message{PollCreationMessageV3: &waE2E.PollCreationMessage{Name: proto.String("wrapped")}},
+ }}
+ poll, version = ExtractPollCreationMessage(wrapper)
+ require.NotNil(t, poll)
+ assert.Equal(t, "wrapped", poll.GetName())
+ assert.Equal(t, "v3", version)
+}
diff --git a/src/usecase/send.go b/src/usecase/send.go
index 729811c4..3ef6fdb1 100644
--- a/src/usecase/send.go
+++ b/src/usecase/send.go
@@ -1474,10 +1474,47 @@ func (service serviceSend) SendPoll(ctx context.Context, request domainSend.Poll
}
response.MessageID = ts.ID
+ if err := service.persistSentPollDefinition(ctx, dataWaRecipient, ts.ID, request, ts.Timestamp); err != nil {
+ // The WhatsApp send already succeeded. Keep the API response successful
+ // while making the loss of future vote resolution visible in logs.
+ logrus.Warnf("Failed to persist sent poll definition %s: %v", ts.ID, err)
+ }
response.Status = fmt.Sprintf("Send poll success %s (server timestamp: %s)", request.BaseRequest.Phone, ts.Timestamp.String())
return response, nil
}
+func (service serviceSend) persistSentPollDefinition(ctx context.Context, recipient types.JID, pollID string, request domainSend.PollRequest, sentAt ...time.Time) error {
+ if service.chatStorageRepo == nil {
+ return fmt.Errorf("chat storage repository is not configured")
+ }
+ deviceID := deviceIDFromContext(ctx)
+ if deviceID == "" {
+ return domainChatStorage.ErrMissingDeviceContext
+ }
+ options := make([]domainChatStorage.PollOption, 0, len(request.Options))
+ for _, name := range request.Options {
+ hash := whatsmeow.HashPollOptions([]string{name})
+ hashHex := ""
+ if len(hash) > 0 {
+ hashHex = fmt.Sprintf("%x", hash[0])
+ }
+ options = append(options, domainChatStorage.PollOption{Name: name, Hash: hashHex})
+ }
+ definition := &domainChatStorage.PollDefinition{
+ DeviceID: deviceID,
+ ChatJID: recipient.ToNonAD().String(),
+ PollMessageID: pollID,
+ Question: request.Question,
+ Options: options,
+ SelectableOptionCount: uint32(request.MaxAnswer),
+ Version: "v1",
+ }
+ if len(sentAt) > 0 {
+ definition.UpdatedAt = sentAt[0]
+ }
+ return service.chatStorageRepo.UpsertPollDefinition(definition)
+}
+
func (service serviceSend) SendPresence(ctx context.Context, request domainSend.PresenceRequest) (response domainSend.GenericResponse, err error) {
err = validations.ValidateSendPresence(ctx, request)
if err != nil {
diff --git a/src/usecase/send_test.go b/src/usecase/send_test.go
index 47642989..192b3c8a 100644
--- a/src/usecase/send_test.go
+++ b/src/usecase/send_test.go
@@ -20,6 +20,7 @@ import (
"github.com/stretchr/testify/require"
"go.mau.fi/whatsmeow"
"go.mau.fi/whatsmeow/proto/waE2E"
+ "go.mau.fi/whatsmeow/types"
"google.golang.org/protobuf/proto"
)
@@ -219,6 +220,42 @@ func TestWithoutCancelPreservesDeviceContext(t *testing.T) {
}
}
+type pollDefinitionRepoSpy struct {
+ domainChatStorage.IChatStorageRepository
+ definition *domainChatStorage.PollDefinition
+ err error
+}
+
+func (r *pollDefinitionRepoSpy) UpsertPollDefinition(definition *domainChatStorage.PollDefinition) error {
+ r.definition = definition
+ return r.err
+}
+
+func TestPersistSentPollDefinitionStoresReadableOptions(t *testing.T) {
+ repo := &pollDefinitionRepoSpy{}
+ service := serviceSend{chatStorageRepo: repo}
+ deviceID := "[email protected]"
+ ctx := whatsapp.ContextWithDevice(context.Background(), whatsapp.NewDeviceInstance(deviceID, nil, nil))
+ recipient := types.NewJID("120363000000", types.GroupServer)
+ request := domainSend.PollRequest{
+ Question: "Lunch?",
+ Options: []string{"Pizza", "Sushi"},
+ MaxAnswer: 1,
+ }
+
+ require.NoError(t, service.persistSentPollDefinition(ctx, recipient, "POLL-SENT-1", request))
+ require.NotNil(t, repo.definition)
+ assert.Equal(t, deviceID, repo.definition.DeviceID)
+ assert.Equal(t, recipient.String(), repo.definition.ChatJID)
+ assert.Equal(t, "POLL-SENT-1", repo.definition.PollMessageID)
+ assert.Equal(t, "Lunch?", repo.definition.Question)
+ assert.Equal(t, uint32(1), repo.definition.SelectableOptionCount)
+ assert.Equal(t, "v1", repo.definition.Version)
+ require.Len(t, repo.definition.Options, 2)
+ assert.Equal(t, "Sushi", repo.definition.Options[1].Name)
+ assert.NotEmpty(t, repo.definition.Options[1].Hash)
+}
+
func TestResolveDocumentMIME(t *testing.T) {
tests := []struct {
name string
diff --git a/src/validations/send_validation.go b/src/validations/send_validation.go
index 4a625679..13182fba 100644
--- a/src/validations/send_validation.go
+++ b/src/validations/send_validation.go
@@ -3,6 +3,7 @@ package validations
import (
"context"
"fmt"
+ "math"
"sort"
"strings"
@@ -452,6 +453,9 @@ func ValidateSendPoll(ctx context.Context, request domainSend.PollRequest) error
if len(request.Options) == 0 {
return pkgError.ValidationError("options: cannot be blank.")
}
+ if request.MaxAnswer > 0 && uint64(request.MaxAnswer) > uint64(math.MaxUint32) {
+ return pkgError.ValidationError(fmt.Sprintf("max_answer: must be no greater than %d.", uint64(math.MaxUint32)))
+ }
err := validation.ValidateStructWithContext(ctx, &request,
validation.Field(&request.Phone, validation.Required),
diff --git a/src/validations/send_validation_test.go b/src/validations/send_validation_test.go
index 3dd2a764..6282b194 100644
--- a/src/validations/send_validation_test.go
+++ b/src/validations/send_validation_test.go
@@ -2,7 +2,9 @@ package validations
import (
"context"
+ "math"
"mime/multipart"
+ "strconv"
"testing"
domainMessage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/message"
@@ -795,6 +797,20 @@ func TestValidateSendPoll(t *testing.T) {
}
}
+func TestValidateSendPollRejectsMaxAnswerOutsideUint32(t *testing.T) {
+ if strconv.IntSize < 64 {
+ t.Skip("int cannot represent a value above uint32 on this architecture")
+ }
+ tooLarge := uint64(math.MaxUint32) + 1
+ err := ValidateSendPoll(context.Background(), domainSend.PollRequest{
+ BaseRequest: domainSend.BaseRequest{Phone: "[email protected]"},
+ Question: "Question?",
+ Options: []string{"One"},
+ MaxAnswer: int(tooLarge),
+ })
+ assert.Equal(t, pkgError.ValidationError("max_answer: must be no greater than 4294967295."), err)
+}
+
func TestValidateSendPresence(t *testing.T) {
type args struct {
request domainSend.PresenceRequest