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: persist chat message reactions

Aldino Kemal66065fc747b1
diff --git a/docs/openapi.yaml b/docs/openapi.yaml
index 98f4ca03..99e57eb3 100644
--- a/docs/openapi.yaml
+++ b/docs/openapi.yaml
@@ -4229,6 +4229,11 @@ components:
example: 'image'
nullable: true
description: Type of media (image, video, audio, document, etc.). Value `call` indicates a stored incoming call log.
+ reactions:
+ type: array
+ description: Emoji reactions attached to this message
+ items:
+ $ref: '#/components/schemas/ChatReaction'
call_metadata:
type: string
example: '{"call_id":"ABC","auto_rejected":false}'
@@ -4259,6 +4264,27 @@ components:
example: '2024-01-15T10:30:00Z'
description: Record last update timestamp
+ ChatReaction:
+ type: object
+ properties:
+ emoji:
+ type: string
+ example: '👍'
+ description: Emoji used in the reaction
+ sender_jid:
+ type: string
+ example: '[email protected]'
+ description: JID of the user who reacted
+ is_from_me:
+ type: boolean
+ example: false
+ description: Whether the reaction was made by the current user
+ timestamp:
+ type: string
+ format: date-time
+ example: '2024-01-15T10:31:00Z'
+ description: When the reaction was received
+
LabelChatResponse:
type: object
properties:
diff --git a/src/domains/chat/chat.go b/src/domains/chat/chat.go
index 8db1cc91..b3df4612 100644
--- a/src/domains/chat/chat.go
+++ b/src/domains/chat/chat.go
@@ -56,13 +56,14 @@ type ChatInfo struct {
}
type MessageInfo struct {
- ID string `json:"id"`
- ChatJID string `json:"chat_jid"`
- SenderJID string `json:"sender_jid"`
- Content string `json:"content"`
- Timestamp string `json:"timestamp"`
- IsFromMe bool `json:"is_from_me"`
- MediaType string `json:"media_type"`
+ ID string `json:"id"`
+ ChatJID string `json:"chat_jid"`
+ SenderJID string `json:"sender_jid"`
+ Content string `json:"content"`
+ Timestamp string `json:"timestamp"`
+ IsFromMe bool `json:"is_from_me"`
+ MediaType string `json:"media_type"`
+ Reactions []ReactionInfo `json:"reactions,omitempty"`
// CallMetadata is JSON when media_type is "call" (incoming call log).
CallMetadata string `json:"call_metadata,omitempty"`
Filename string `json:"filename"`
diff --git a/src/domains/chat/reaction.go b/src/domains/chat/reaction.go
new file mode 100644
index 00000000..0f3183ca
--- /dev/null
+++ b/src/domains/chat/reaction.go
@@ -0,0 +1,9 @@
+package chat
+
+// ReactionInfo represents a single emoji reaction attached to a message.
+type ReactionInfo struct {
+ Emoji string `json:"emoji"`
+ SenderJID string `json:"sender_jid"`
+ IsFromMe bool `json:"is_from_me"`
+ Timestamp string `json:"timestamp"`
+}
diff --git a/src/domains/chatstorage/chatstorage.go b/src/domains/chatstorage/chatstorage.go
index c4865784..64dff4e7 100644
--- a/src/domains/chatstorage/chatstorage.go
+++ b/src/domains/chatstorage/chatstorage.go
@@ -16,24 +16,25 @@ type Chat struct {
// Message represents a WhatsApp message
type Message struct {
- ID string `db:"id"`
- ChatJID string `db:"chat_jid"`
- DeviceID string `db:"device_id"`
- Sender string `db:"sender"`
- Content string `db:"content"`
- Timestamp time.Time `db:"timestamp"`
- IsFromMe bool `db:"is_from_me"`
- MediaType string `db:"media_type"`
- CallMetadata string `db:"call_metadata"`
- Filename string `db:"filename"`
- URL string `db:"url"`
- MediaKey []byte `db:"media_key"`
- FileSHA256 []byte `db:"file_sha256"`
- FileEncSHA256 []byte `db:"file_enc_sha256"`
- FileLength uint64 `db:"file_length"`
- ReferralMetadata string `db:"referral_metadata"`
- CreatedAt time.Time `db:"created_at"`
- UpdatedAt time.Time `db:"updated_at"`
+ ID string `db:"id"`
+ ChatJID string `db:"chat_jid"`
+ DeviceID string `db:"device_id"`
+ Sender string `db:"sender"`
+ Content string `db:"content"`
+ Timestamp time.Time `db:"timestamp"`
+ IsFromMe bool `db:"is_from_me"`
+ MediaType string `db:"media_type"`
+ CallMetadata string `db:"call_metadata"`
+ Filename string `db:"filename"`
+ URL string `db:"url"`
+ MediaKey []byte `db:"media_key"`
+ FileSHA256 []byte `db:"file_sha256"`
+ FileEncSHA256 []byte `db:"file_enc_sha256"`
+ FileLength uint64 `db:"file_length"`
+ ReferralMetadata string `db:"referral_metadata"`
+ Reactions []Reaction `db:"-"`
+ CreatedAt time.Time `db:"created_at"`
+ UpdatedAt time.Time `db:"updated_at"`
}
// MediaInfo represents downloadable media information
diff --git a/src/domains/chatstorage/interfaces.go b/src/domains/chatstorage/interfaces.go
index 2b14afc4..5dda273b 100644
--- a/src/domains/chatstorage/interfaces.go
+++ b/src/domains/chatstorage/interfaces.go
@@ -12,6 +12,7 @@ import (
type IChatStorageRepository interface {
// Chat operations
CreateMessage(ctx context.Context, evt *events.Message) error
+ CreateReaction(ctx context.Context, evt *events.Message) error
// CreateIncomingCallRecord persists an incoming call as a synthetic message (media_type "call") for chat history.
CreateIncomingCallRecord(ctx context.Context, evt *events.CallOffer, autoRejected bool) error
StoreChat(chat *Chat) error
diff --git a/src/domains/chatstorage/reaction.go b/src/domains/chatstorage/reaction.go
new file mode 100644
index 00000000..8883e2a1
--- /dev/null
+++ b/src/domains/chatstorage/reaction.go
@@ -0,0 +1,16 @@
+package chatstorage
+
+import "time"
+
+// Reaction represents a single reaction stored alongside a message.
+type Reaction struct {
+ MessageID string `db:"message_id"`
+ ChatJID string `db:"chat_jid"`
+ DeviceID string `db:"device_id"`
+ ReactorJID string `db:"reactor_jid"`
+ Emoji string `db:"emoji"`
+ IsFromMe bool `db:"is_from_me"`
+ Timestamp time.Time `db:"reaction_timestamp"`
+ CreatedAt time.Time `db:"created_at"`
+ UpdatedAt time.Time `db:"updated_at"`
+}
diff --git a/src/infrastructure/chatstorage/sqlite_repository.go b/src/infrastructure/chatstorage/sqlite_repository.go
index 1a452a0c..df4e351b 100644
--- a/src/infrastructure/chatstorage/sqlite_repository.go
+++ b/src/infrastructure/chatstorage/sqlite_repository.go
@@ -189,7 +189,12 @@ func (r *SQLiteRepository) DeleteChat(jid string) error {
}
defer tx.Rollback()
- // Delete messages first (foreign key constraint)
+ _, err = tx.Exec("DELETE FROM message_reactions WHERE chat_jid = ?", jid)
+ if err != nil {
+ return err
+ }
+
+ // Delete messages after reactions to keep cleanup explicit.
_, err = tx.Exec("DELETE FROM messages WHERE chat_jid = ?", jid)
if err != nil {
return err
@@ -212,7 +217,12 @@ func (r *SQLiteRepository) DeleteChatByDevice(deviceID, jid string) error {
}
defer tx.Rollback()
- // Delete messages first (foreign key constraint)
+ _, err = tx.Exec("DELETE FROM message_reactions WHERE chat_jid = ? AND device_id = ?", jid, deviceID)
+ if err != nil {
+ return err
+ }
+
+ // Delete messages after reactions to keep cleanup explicit.
_, err = tx.Exec("DELETE FROM messages WHERE chat_jid = ? AND device_id = ?", jid, deviceID)
if err != nil {
return err
@@ -340,6 +350,60 @@ func (r *SQLiteRepository) StoreMessagesBatch(messages []*domainChatStorage.Mess
return tx.Commit()
}
+// StoreReaction creates, updates, or removes a message reaction.
+func (r *SQLiteRepository) StoreReaction(reaction *domainChatStorage.Reaction) error {
+ if reaction == nil {
+ return nil
+ }
+ if reaction.MessageID == "" || reaction.ChatJID == "" || reaction.DeviceID == "" || reaction.ReactorJID == "" {
+ return fmt.Errorf("reaction requires message_id, chat_jid, device_id, and reactor_jid")
+ }
+ if reaction.Emoji == "" {
+ return r.DeleteReaction(reaction.MessageID, reaction.ReactorJID, reaction.DeviceID)
+ }
+
+ now := time.Now()
+ if reaction.CreatedAt.IsZero() {
+ reaction.CreatedAt = now
+ }
+ reaction.UpdatedAt = now
+
+ result, err := r.db.Exec(`
+ UPDATE message_reactions
+ SET chat_jid = ?, emoji = ?, is_from_me = ?, reaction_timestamp = ?, updated_at = ?
+ WHERE message_id = ? AND reactor_jid = ? AND device_id = ?
+ `, reaction.ChatJID, reaction.Emoji, reaction.IsFromMe, reaction.Timestamp, reaction.UpdatedAt,
+ reaction.MessageID, reaction.ReactorJID, reaction.DeviceID)
+ if err != nil {
+ return err
+ }
+
+ rowsAffected, _ := result.RowsAffected()
+ if rowsAffected == 0 {
+ _, err = r.db.Exec(`
+ INSERT INTO message_reactions (
+ message_id, chat_jid, device_id, reactor_jid, emoji, is_from_me,
+ reaction_timestamp, created_at, updated_at
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
+ `, reaction.MessageID, reaction.ChatJID, reaction.DeviceID, reaction.ReactorJID,
+ reaction.Emoji, reaction.IsFromMe, reaction.Timestamp, reaction.CreatedAt, reaction.UpdatedAt)
+ }
+ return err
+}
+
+// DeleteReaction removes a single stored reaction.
+func (r *SQLiteRepository) DeleteReaction(messageID, reactorJID, deviceID string) error {
+ if messageID == "" || reactorJID == "" || deviceID == "" {
+ return nil
+ }
+
+ _, err := r.db.Exec(`
+ DELETE FROM message_reactions
+ WHERE message_id = ? AND reactor_jid = ? AND device_id = ?
+ `, messageID, reactorJID, deviceID)
+ return err
+}
+
// GetMessages retrieves messages with filtering
func (r *SQLiteRepository) GetMessages(filter *domainChatStorage.MessageFilter) ([]*domainChatStorage.Message, error) {
// Require device_id for data isolation - fail fast if missing
@@ -414,7 +478,15 @@ func (r *SQLiteRepository) GetMessages(filter *domainChatStorage.MessageFilter)
messages = append(messages, message)
}
- return messages, rows.Err()
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+
+ if err := r.loadMessageReactions(filter.DeviceID, filter.ChatJID, messages); err != nil {
+ return nil, err
+ }
+
+ return messages, nil
}
// SearchMessages performs database-level search for messages containing specific text
@@ -478,17 +550,99 @@ func (r *SQLiteRepository) SearchMessages(deviceID, chatJID, searchText string,
return nil, fmt.Errorf("error iterating messages: %w", err)
}
+ if err := r.loadMessageReactions(deviceID, chatJID, messages); err != nil {
+ return nil, fmt.Errorf("failed to load message reactions: %w", err)
+ }
+
return messages, nil
}
+func (r *SQLiteRepository) loadMessageReactions(deviceID, chatJID string, messages []*domainChatStorage.Message) error {
+ if len(messages) == 0 {
+ return nil
+ }
+
+ messageIDs := make([]string, 0, len(messages))
+ for _, message := range messages {
+ if message != nil && message.ID != "" {
+ messageIDs = append(messageIDs, message.ID)
+ }
+ }
+ if len(messageIDs) == 0 {
+ return nil
+ }
+
+ reactionsByMessageID := make(map[string][]domainChatStorage.Reaction)
+ for start := 0; start < len(messageIDs); start += 500 {
+ end := start + 500
+ if end > len(messageIDs) {
+ end = len(messageIDs)
+ }
+
+ batchIDs := messageIDs[start:end]
+ placeholders := make([]string, 0, len(batchIDs))
+ args := make([]any, 0, len(batchIDs)+2)
+ args = append(args, deviceID, chatJID)
+ for _, messageID := range batchIDs {
+ placeholders = append(placeholders, "?")
+ args = append(args, messageID)
+ }
+
+ query := `
+ SELECT message_id, chat_jid, device_id, reactor_jid, emoji, is_from_me,
+ reaction_timestamp, created_at, updated_at
+ FROM message_reactions
+ WHERE device_id = ? AND chat_jid = ? AND message_id IN (` + strings.Join(placeholders, ",") + `)
+ ORDER BY reaction_timestamp ASC, created_at ASC
+ `
+
+ rows, err := r.db.Query(query, args...)
+ if err != nil {
+ return err
+ }
+
+ for rows.Next() {
+ var reaction domainChatStorage.Reaction
+ if err := rows.Scan(
+ &reaction.MessageID, &reaction.ChatJID, &reaction.DeviceID, &reaction.ReactorJID,
+ &reaction.Emoji, &reaction.IsFromMe, &reaction.Timestamp, &reaction.CreatedAt, &reaction.UpdatedAt,
+ ); err != nil {
+ rows.Close()
+ return err
+ }
+ reactionsByMessageID[reaction.MessageID] = append(reactionsByMessageID[reaction.MessageID], reaction)
+ }
+ if err := rows.Err(); err != nil {
+ rows.Close()
+ return err
+ }
+ rows.Close()
+ }
+
+ for _, message := range messages {
+ if message == nil {
+ continue
+ }
+ message.Reactions = reactionsByMessageID[message.ID]
+ }
+
+ return nil
+}
+
// DeleteMessage deletes a specific message
func (r *SQLiteRepository) DeleteMessage(id, chatJID string) error {
+ if _, err := r.db.Exec("DELETE FROM message_reactions WHERE message_id = ? AND chat_jid = ?", id, chatJID); err != nil {
+ return err
+ }
_, err := r.db.Exec("DELETE FROM messages WHERE id = ? AND chat_jid = ?", id, chatJID)
return err
}
// DeleteMessageByDevice deletes a specific message for a specific device
func (r *SQLiteRepository) DeleteMessageByDevice(deviceID, id, chatJID string) error {
+ if _, err := r.db.Exec("DELETE FROM message_reactions WHERE message_id = ? AND chat_jid = ? AND device_id = ?", id, chatJID, deviceID); err != nil {
+ return err
+ }
_, err := r.db.Exec("DELETE FROM messages WHERE id = ? AND chat_jid = ? AND device_id = ?", id, chatJID, deviceID)
return err
}
@@ -565,7 +719,12 @@ func (r *SQLiteRepository) TruncateAllChats() error {
}
defer tx.Rollback()
- // Delete messages first (foreign key constraint)
+ _, err = tx.Exec("DELETE FROM message_reactions")
+ if err != nil {
+ return fmt.Errorf("failed to delete message reactions: %w", err)
+ }
+
+ // Delete messages after reactions to keep cleanup explicit.
_, err = tx.Exec("DELETE FROM messages")
if err != nil {
return fmt.Errorf("failed to delete messages: %w", err)
@@ -593,7 +752,11 @@ func (r *SQLiteRepository) DeleteDeviceData(deviceID string) error {
}
defer tx.Rollback()
- // Delete messages first via direct device_id filter
+ if _, err := tx.Exec(`DELETE FROM message_reactions WHERE device_id = ?`, deviceID); err != nil {
+ return fmt.Errorf("failed to delete device reactions: %w", err)
+ }
+
+ // Delete messages after reactions 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)
}
@@ -875,6 +1038,83 @@ func (r *SQLiteRepository) CreateMessage(ctx context.Context, evt *events.Messag
return r.StoreMessage(message)
}
+// CreateReaction stores or removes a reaction event as its own row in message_reactions.
+func (r *SQLiteRepository) CreateReaction(ctx context.Context, evt *events.Message) error {
+ reaction, err := r.reactionFromEvent(ctx, evt)
+ if err != nil {
+ return err
+ }
+ if reaction == nil {
+ return nil
+ }
+ return r.StoreReaction(reaction)
+}
+
+func (r *SQLiteRepository) reactionFromEvent(ctx context.Context, evt *events.Message) (*domainChatStorage.Reaction, error) {
+ if evt == nil || evt.Message == nil {
+ return nil, nil
+ }
+
+ msg := utils.UnwrapMessage(evt.Message)
+ reactionMessage := msg.GetReactionMessage()
+ if reactionMessage == nil {
+ return nil, nil
+ }
+
+ key := reactionMessage.GetKey()
+ if key == nil || key.GetID() == "" {
+ logrus.Debugf("Skipping reaction event %s - missing reacted message id", evt.Info.ID)
+ return nil, nil
+ }
+
+ client := whatsapp.ClientFromContext(ctx)
+ deviceID := ""
+ if inst, ok := whatsapp.DeviceFromContext(ctx); ok && inst != nil {
+ deviceID = inst.JID()
+ if deviceID == "" {
+ deviceID = inst.ID()
+ }
+ }
+ if deviceID == "" && client != nil && client.Store != nil && client.Store.ID != nil {
+ deviceID = client.Store.ID.ToNonAD().String()
+ }
+ if deviceID == "" {
+ return nil, domainChatStorage.ErrMissingDeviceContext
+ }
+
+ chatJID := evt.Info.Chat
+ if chatJID.IsEmpty() && key.GetRemoteJID() != "" {
+ parsed, err := types.ParseJID(key.GetRemoteJID())
+ if err != nil {
+ return nil, fmt.Errorf("failed to parse reaction chat jid %q: %w", key.GetRemoteJID(), err)
+ }
+ chatJID = parsed
+ }
+ if chatJID.IsEmpty() {
+ return nil, fmt.Errorf("reaction chat jid is required")
+ }
+ normalizedChatJID := whatsapp.NormalizeJIDFromLID(ctx, chatJID, client)
+
+ reactorJID := evt.Info.Sender
+ if reactorJID.IsEmpty() && evt.Info.IsFromMe && client != nil && client.Store != nil && client.Store.ID != nil {
+ reactorJID = client.Store.ID.ToNonAD()
+ }
+ if reactorJID.IsEmpty() {
+ return nil, fmt.Errorf("reaction sender jid is required")
+ }
+ normalizedReactorJID := whatsapp.NormalizeJIDFromLID(ctx, reactorJID, client)
+
+ return &domainChatStorage.Reaction{
+ MessageID: key.GetID(),
+ ChatJID: normalizedChatJID.String(),
+ DeviceID: deviceID,
+ ReactorJID: normalizedReactorJID.ToNonAD().String(),
+ Emoji: reactionMessage.GetText(),
+ IsFromMe: evt.Info.IsFromMe,
+ Timestamp: evt.Info.Timestamp,
+ }, nil
+}
+
// CreateIncomingCallRecord stores an incoming call as a synthetic message row (media_type "call").
func (r *SQLiteRepository) CreateIncomingCallRecord(ctx context.Context, evt *events.CallOffer, autoRejected bool) error {
if evt == nil {
@@ -1269,5 +1509,22 @@ func (r *SQLiteRepository) getMigrations() []string {
// Migration 16: JSON metadata for Meta Ads referral/attribution (CTWA)
`ALTER TABLE messages ADD COLUMN referral_metadata TEXT DEFAULT ''`,
+
+ // Migration 17: Store emoji reactions per message
+ `CREATE TABLE IF NOT EXISTS message_reactions (
+ message_id VARCHAR(255) NOT NULL,
+ chat_jid VARCHAR(255) NOT NULL,
+ device_id VARCHAR(255) NOT NULL DEFAULT '',
+ reactor_jid VARCHAR(255) NOT NULL,
+ emoji TEXT NOT NULL DEFAULT '',
+ is_from_me BOOLEAN DEFAULT FALSE,
+ reaction_timestamp TIMESTAMP NOT NULL,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (message_id, reactor_jid, device_id)
+ )`,
+
+ // Migration 18: Index reactions by message and chat for history hydration
+ `CREATE INDEX IF NOT EXISTS idx_message_reactions_lookup ON message_reactions(device_id, chat_jid, message_id)`,
}
}
diff --git a/src/infrastructure/chatstorage/sqlite_repository_test.go b/src/infrastructure/chatstorage/sqlite_repository_test.go
new file mode 100644
index 00000000..12852d70
--- /dev/null
+++ b/src/infrastructure/chatstorage/sqlite_repository_test.go
@@ -0,0 +1,221 @@
+package chatstorage
+
+import (
+ "database/sql"
+ "path/filepath"
+ "testing"
+ "time"
+
+ domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/sqlite"
+)
+
+func newTestSQLiteRepository(t *testing.T) *SQLiteRepository {
+ t.Helper()
+
+ db, err := sql.Open(sqlite.DriverName, filepath.Join(t.TempDir(), "chatstorage.db"))
+ if err != nil {
+ t.Fatalf("open sqlite database: %v", err)
+ }
+ t.Cleanup(func() { _ = db.Close() })
+
+ repo := &SQLiteRepository{db: db}
+ if err := repo.InitializeSchema(); err != nil {
+ t.Fatalf("initialize schema: %v", err)
+ }
+ return repo
+}
+
+func TestSQLiteRepositoryInitializesMessageReactionsSchema(t *testing.T) {
+ repo := newTestSQLiteRepository(t)
+
+ var tableName string
+ err := repo.db.QueryRow(`
+ SELECT name
+ FROM sqlite_master
+ WHERE type = 'table' AND name = 'message_reactions'
+ `).Scan(&tableName)
+ if err != nil {
+ t.Fatalf("expected message_reactions table to exist: %v", err)
+ }
+ if tableName != "message_reactions" {
+ t.Fatalf("expected message_reactions table, got %q", tableName)
+ }
+}
+
+func TestSQLiteRepositoryStoresUpdatesRemovesAndHydratesReactions(t *testing.T) {
+ repo := newTestSQLiteRepository(t)
+ deviceID := "[email protected]"
+ otherDeviceID := "[email protected]"
+ chatJID := "[email protected]"
+ now := time.Date(2026, time.May, 16, 8, 0, 0, 0, time.UTC)
+
+ seedChatMessage(t, repo, deviceID, chatJID, "msg-1", "hello reaction", now)
+ seedChatMessage(t, repo, otherDeviceID, chatJID, "msg-1", "hello other device", now)
+
+ if err := repo.StoreReaction(&domainChatStorage.Reaction{
+ MessageID: "msg-1",
+ ChatJID: chatJID,
+ DeviceID: deviceID,
+ ReactorJID: "[email protected]",
+ Emoji: "\U0001f44d",
+ IsFromMe: false,
+ Timestamp: now.Add(time.Minute),
+ }); err != nil {
+ t.Fatalf("store reaction: %v", err)
+ }
+ if err := repo.StoreReaction(&domainChatStorage.Reaction{
+ MessageID: "msg-1",
+ ChatJID: chatJID,
+ DeviceID: otherDeviceID,
+ ReactorJID: "[email protected]",
+ Emoji: "\U0001f525",
+ IsFromMe: false,
+ Timestamp: now.Add(2 * time.Minute),
+ }); err != nil {
+ t.Fatalf("store other device reaction: %v", err)
+ }
+
+ messages := getMessagesForTest(t, repo, deviceID, chatJID)
+ if got := len(messages[0].Reactions); got != 1 {
+ t.Fatalf("expected one device-scoped reaction, got %d", got)
+ }
+ if got := messages[0].Reactions[0].Emoji; got != "\U0001f44d" {
+ t.Fatalf("expected hydrated thumbs-up reaction, got %q", got)
+ }
+
+ if err := repo.StoreReaction(&domainChatStorage.Reaction{
+ MessageID: "msg-1",
+ ChatJID: chatJID,
+ DeviceID: deviceID,
+ ReactorJID: "[email protected]",
+ Emoji: "\U0001f525",
+ IsFromMe: false,
+ Timestamp: now.Add(3 * time.Minute),
+ }); err != nil {
+ t.Fatalf("update reaction: %v", err)
+ }
+
+ messages = getMessagesForTest(t, repo, deviceID, chatJID)
+ if got := len(messages[0].Reactions); got != 1 {
+ t.Fatalf("expected one updated reaction, got %d", got)
+ }
+ if got := messages[0].Reactions[0].Emoji; got != "\U0001f525" {
+ t.Fatalf("expected updated fire reaction, got %q", got)
+ }
+
+ searchResults, err := repo.SearchMessages(deviceID, chatJID, "reaction", 10)
+ if err != nil {
+ t.Fatalf("search messages: %v", err)
+ }
+ if got := len(searchResults); got != 1 {
+ t.Fatalf("expected one search result, got %d", got)
+ }
+ if got := len(searchResults[0].Reactions); got != 1 {
+ t.Fatalf("expected search result to hydrate reactions, got %d", got)
+ }
+
+ if err := repo.StoreReaction(&domainChatStorage.Reaction{
+ MessageID: "msg-1",
+ ChatJID: chatJID,
+ DeviceID: deviceID,
+ ReactorJID: "[email protected]",
+ Emoji: "",
+ Timestamp: now.Add(4 * time.Minute),
+ }); err != nil {
+ t.Fatalf("remove reaction: %v", err)
+ }
+
+ messages = getMessagesForTest(t, repo, deviceID, chatJID)
+ if got := len(messages[0].Reactions); got != 0 {
+ t.Fatalf("expected reaction removal to clear reactions, got %d", got)
+ }
+}
+
+func TestSQLiteRepositoryDeletesReactionsWithMessagesAndDevices(t *testing.T) {
+ repo := newTestSQLiteRepository(t)
+ deviceID := "[email protected]"
+ otherDeviceID := "[email protected]"
+ chatJID := "[email protected]"
+ now := time.Date(2026, time.May, 16, 8, 0, 0, 0, time.UTC)
+
+ seedChatMessage(t, repo, deviceID, chatJID, "msg-1", "hello", now)
+ seedReaction(t, repo, deviceID, chatJID, "msg-1", "[email protected]")
+ seedChatMessage(t, repo, otherDeviceID, chatJID, "msg-1", "hello", now)
+ seedReaction(t, repo, otherDeviceID, chatJID, "msg-1", "[email protected]")
+
+ if err := repo.DeleteMessageByDevice(deviceID, "msg-1", chatJID); err != nil {
+ t.Fatalf("delete message by device: %v", err)
+ }
+ if got := countMessageReactions(t, repo); got != 1 {
+ t.Fatalf("expected only other device reaction to remain, got %d", got)
+ }
+
+ if err := repo.DeleteDeviceData(otherDeviceID); err != nil {
+ t.Fatalf("delete device data: %v", err)
+ }
+ if got := countMessageReactions(t, repo); got != 0 {
+ t.Fatalf("expected device cleanup to delete reactions, got %d", got)
+ }
+}
+
+func seedChatMessage(t *testing.T, repo *SQLiteRepository, deviceID, chatJID, messageID, content string, timestamp time.Time) {
+ t.Helper()
+ if err := repo.StoreChat(&domainChatStorage.Chat{
+ DeviceID: deviceID,
+ JID: chatJID,
+ Name: chatJID,
+ LastMessageTime: timestamp,
+ }); err != nil {
+ t.Fatalf("store chat: %v", err)
+ }
+ if err := repo.StoreMessage(&domainChatStorage.Message{
+ ID: messageID,
+ ChatJID: chatJID,
+ DeviceID: deviceID,
+ Sender: "[email protected]",
+ Content: content,
+ Timestamp: timestamp,
+ }); err != nil {
+ t.Fatalf("store message: %v", err)
+ }
+}
+
+func seedReaction(t *testing.T, repo *SQLiteRepository, deviceID, chatJID, messageID, reactorJID string) {
+ t.Helper()
+ if err := repo.StoreReaction(&domainChatStorage.Reaction{
+ MessageID: messageID,
+ ChatJID: chatJID,
+ DeviceID: deviceID,
+ ReactorJID: reactorJID,
+ Emoji: "\U0001f44d",
+ Timestamp: time.Date(2026, time.May, 16, 8, 1, 0, 0, time.UTC),
+ }); err != nil {
+ t.Fatalf("store reaction: %v", err)
+ }
+}
+
+func getMessagesForTest(t *testing.T, repo *SQLiteRepository, deviceID, chatJID string) []*domainChatStorage.Message {
+ t.Helper()
+ messages, err := repo.GetMessages(&domainChatStorage.MessageFilter{
+ DeviceID: deviceID,
+ ChatJID: chatJID,
+ Limit: 10,
+ })
+ if err != nil {
+ t.Fatalf("get messages: %v", err)
+ }
+ if len(messages) != 1 {
+ t.Fatalf("expected one message, got %d", len(messages))
+ }
+ return messages
+}
+
+func countMessageReactions(t *testing.T, repo *SQLiteRepository) int {
+ t.Helper()
+ var count int
+ if err := repo.db.QueryRow(`SELECT COUNT(*) FROM message_reactions`).Scan(&count); err != nil {
+ t.Fatalf("count message reactions: %v", err)
+ }
+ return count
+}
diff --git a/src/infrastructure/whatsapp/chatstorage_wrapper.go b/src/infrastructure/whatsapp/chatstorage_wrapper.go
index 94f9d4e5..14e10bef 100644
--- a/src/infrastructure/whatsapp/chatstorage_wrapper.go
+++ b/src/infrastructure/whatsapp/chatstorage_wrapper.go
@@ -41,6 +41,10 @@ func (r *deviceChatStorage) CreateMessage(ctx context.Context, evt *events.Messa
return r.base.CreateMessage(ctx, evt)
}
+func (r *deviceChatStorage) CreateReaction(ctx context.Context, evt *events.Message) error {
+ return r.base.CreateReaction(ctx, evt)
+}
+
func (r *deviceChatStorage) CreateIncomingCallRecord(ctx context.Context, evt *events.CallOffer, autoRejected bool) error {
return r.base.CreateIncomingCallRecord(ctx, evt, autoRejected)
}
diff --git a/src/infrastructure/whatsapp/event_message.go b/src/infrastructure/whatsapp/event_message.go
index 105c8226..3d7dc116 100644
--- a/src/infrastructure/whatsapp/event_message.go
+++ b/src/infrastructure/whatsapp/event_message.go
@@ -57,6 +57,14 @@ func forwardMessageToWebhook(ctx context.Context, client *whatsmeow.Client, evt
return forwardPayloadToConfiguredWebhooks(ctx, payload, webhookEvent.Event)
}
+func isReactionMessage(evt *events.Message) bool {
+ if evt == nil || evt.Message == nil {
+ return false
+ }
+
+ return utils.UnwrapMessage(evt.Message).GetReactionMessage() != nil
+}
+
func createWebhookEvent(ctx context.Context, client *whatsmeow.Client, evt *events.Message) (*WebhookEvent, error) {
webhookEvent := &WebhookEvent{
Event: EventTypeMessage,
diff --git a/src/infrastructure/whatsapp/event_message_handler.go b/src/infrastructure/whatsapp/event_message_handler.go
index 06bfbd53..c4158fdb 100644
--- a/src/infrastructure/whatsapp/event_message_handler.go
+++ b/src/infrastructure/whatsapp/event_message_handler.go
@@ -25,6 +25,15 @@ func handleMessage(ctx context.Context, evt *events.Message, chatStorageRepo dom
evt.Message,
)
+ 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)
+ return
+ }
+
if err := chatStorageRepo.CreateMessage(ctx, evt); err != nil {
// Log storage errors to avoid silent failures that could lead to data loss
log.Errorf("Failed to store incoming message %s: %v", evt.Info.ID, err)
diff --git a/src/infrastructure/whatsapp/event_message_handler_test.go b/src/infrastructure/whatsapp/event_message_handler_test.go
new file mode 100644
index 00000000..4ef4f9b5
--- /dev/null
+++ b/src/infrastructure/whatsapp/event_message_handler_test.go
@@ -0,0 +1,132 @@
+package whatsapp
+
+import (
+ "context"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/config"
+ domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
+ "go.mau.fi/whatsmeow/proto/waCommon"
+ "go.mau.fi/whatsmeow/proto/waE2E"
+ "go.mau.fi/whatsmeow/types"
+ "go.mau.fi/whatsmeow/types/events"
+ waLog "go.mau.fi/whatsmeow/util/log"
+)
+
+func TestHandleMessageReactionStoresReactionAndForwardsWebhook(t *testing.T) {
+ originalWebhookURLs := config.WhatsappWebhook
+ originalWebhookEvents := config.WhatsappWebhookEvents
+ originalAutoReply := config.WhatsappAutoReplyMessage
+ originalAutoMarkRead := config.WhatsappAutoMarkRead
+ originalSubmit := submitWebhookFn
+ originalLog := log
+ defer func() {
+ config.WhatsappWebhook = originalWebhookURLs
+ config.WhatsappWebhookEvents = originalWebhookEvents
+ config.WhatsappAutoReplyMessage = originalAutoReply
+ config.WhatsappAutoMarkRead = originalAutoMarkRead
+ submitWebhookFn = originalSubmit
+ log = originalLog
+ }()
+
+ log = waLog.Noop
+ config.WhatsappWebhook = []string{"https://example.test/webhook"}
+ config.WhatsappWebhookEvents = nil
+ config.WhatsappAutoReplyMessage = ""
+ config.WhatsappAutoMarkRead = false
+
+ repo := &messageHandlerRepoSpy{}
+ done := make(chan map[string]any, 1)
+ submitWebhookFn = func(_ context.Context, payload map[string]any, _ string) error {
+ done <- payload
+ return nil
+ }
+
+ evt := reactionEventForTest("reaction-event-1", "msg-1", "\U0001f44d")
+ handleMessage(context.Background(), evt, repo, nil)
+
+ if got := repo.createReactionCount(); got != 1 {
+ t.Fatalf("expected reaction path to call CreateReaction once, got %d", got)
+ }
+ if got := repo.createMessageCount(); got != 0 {
+ t.Fatalf("expected reaction path not to call CreateMessage, got %d", got)
+ }
+
+ select {
+ case payload := <-done:
+ if got := payload["event"]; got != EventTypeMessageReaction {
+ t.Fatalf("expected webhook event %q, got %v", EventTypeMessageReaction, got)
+ }
+ eventPayload, ok := payload["payload"].(map[string]any)
+ if !ok {
+ t.Fatalf("expected payload map, got %T", payload["payload"])
+ }
+ if got := eventPayload["reaction"]; got != "\U0001f44d" {
+ t.Fatalf("expected reaction in webhook payload, got %v", got)
+ }
+ if got := eventPayload["reacted_message_id"]; got != "msg-1" {
+ t.Fatalf("expected reacted message id, got %v", got)
+ }
+ case <-time.After(2 * time.Second):
+ t.Fatal("timed out waiting for webhook submission")
+ }
+}
+
+type messageHandlerRepoSpy struct {
+ domainChatStorage.IChatStorageRepository
+ mu sync.Mutex
+ createMessageCalls int
+ createReactionCalls int
+}
+
+func (r *messageHandlerRepoSpy) CreateMessage(context.Context, *events.Message) error {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ r.createMessageCalls++
+ return nil
+}
+
+func (r *messageHandlerRepoSpy) CreateReaction(context.Context, *events.Message) error {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ r.createReactionCalls++
+ return nil
+}
+
+func (r *messageHandlerRepoSpy) createMessageCount() int {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ return r.createMessageCalls
+}
+
+func (r *messageHandlerRepoSpy) createReactionCount() int {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ return r.createReactionCalls
+}
+
+func reactionEventForTest(eventID, targetID, emoji string) *events.Message {
+ return &events.Message{
+ Info: types.MessageInfo{
+ MessageSource: types.MessageSource{
+ Chat: types.NewJID("628123456789", types.DefaultUserServer),
+ Sender: types.NewJID("628111111111", types.DefaultUserServer),
+ IsFromMe: false,
+ },
+ ID: eventID,
+ Timestamp: time.Date(2026, time.May, 16, 8, 0, 0, 0, time.UTC),
+ },
+ Message: &waE2E.Message{
+ ReactionMessage: &waE2E.ReactionMessage{
+ Key: &waCommon.MessageKey{
+ RemoteJID: protoString("[email protected]"),
+ FromMe: protoBool(false),
+ ID: protoString(targetID),
+ },
+ Text: protoString(emoji),
+ },
+ },
+ }
+}
diff --git a/src/infrastructure/whatsapp/event_message_test.go b/src/infrastructure/whatsapp/event_message_test.go
index 0a5363b8..d5ba7e25 100644
--- a/src/infrastructure/whatsapp/event_message_test.go
+++ b/src/infrastructure/whatsapp/event_message_test.go
@@ -80,6 +80,40 @@ func TestBuildEventPayloadRevokedIncludesIsFromMe(t *testing.T) {
}
}
+func TestBuildEventPayloadReactionIncludesTargetMessageID(t *testing.T) {
+ evt := reactionEventForTest("reaction-event-1", "MSG100", "\U0001f44d")
+
+ eventType, payload, err := buildEventPayload(context.Background(), nil, evt)
+ if err != nil {
+ t.Fatalf("expected no error, got %v", err)
+ }
+ if eventType != EventTypeMessageReaction {
+ t.Fatalf("expected event type %s, got %s", EventTypeMessageReaction, eventType)
+ }
+ if got := payload["reaction"]; got != "\U0001f44d" {
+ t.Fatalf("expected reaction payload, got %v", got)
+ }
+ if got := payload["reacted_message_id"]; got != "MSG100" {
+ t.Fatalf("expected reacted message id MSG100, got %v", got)
+ }
+}
+
+func TestBuildEventPayloadReactionWithoutKeyDoesNotPanic(t *testing.T) {
+ evt := reactionEventForTest("reaction-event-2", "MSG101", "\U0001f44d")
+ evt.Message.ReactionMessage.Key = nil
+
+ eventType, payload, err := buildEventPayload(context.Background(), nil, evt)
+ if err != nil {
+ t.Fatalf("expected no error, got %v", err)
+ }
+ if eventType != EventTypeMessageReaction {
+ t.Fatalf("expected event type %s, got %s", EventTypeMessageReaction, eventType)
+ }
+ if _, ok := payload["reacted_message_id"]; ok {
+ t.Fatalf("expected no reacted_message_id when reaction key is missing")
+ }
+}
+
func protoString(value string) *string {
return &value
}
diff --git a/src/infrastructure/whatsapp/history_sync.go b/src/infrastructure/whatsapp/history_sync.go
index f185f7b6..01ad3d9a 100644
--- a/src/infrastructure/whatsapp/history_sync.go
+++ b/src/infrastructure/whatsapp/history_sync.go
@@ -148,22 +148,15 @@ func processConversationMessages(ctx context.Context, data *waHistorySync.Histor
continue
}
- // Extract message content and media info
- content := utils.ExtractMessageTextFromProto(msg.GetMessage())
- mediaType, filename, url, mediaKey, fileSHA256, fileEncSHA256, fileLength := utils.ExtractMediaInfo(msg.GetMessage())
-
- // Skip if there's no content and no media
- if content == "" && mediaType == "" {
- continue
- }
-
// Determine sender
sender := ""
+ senderJID := types.EmptyJID
isFromMe := msgKey.GetFromMe()
if isFromMe {
// For self-messages, use the full JID format to match regular message processing
if client != nil && client.Store.ID != nil {
- sender = client.Store.ID.ToNonAD().String() // Use full JID instead of just User part
+ senderJID = client.Store.ID.ToNonAD()
+ sender = senderJID.String() // Use full JID instead of just User part
} else {
// Skip messages where we can't determine the sender to avoid NOT NULL violations
log.Warnf("Skipping self-message %s: client ID unavailable", messageID)
@@ -173,9 +166,9 @@ func processConversationMessages(ctx context.Context, data *waHistorySync.Histor
participant := msgKey.GetParticipant()
if participant != "" {
// For group messages, participant contains the actual sender
- if senderJID, err := types.ParseJID(participant); err == nil {
+ if parsedSenderJID, err := types.ParseJID(participant); err == nil {
// Normalize sender JID (convert @lid to @s.whatsapp.net if possible)
- senderJID = NormalizeJIDFromLID(ctx, senderJID, client)
+ senderJID = NormalizeJIDFromLID(ctx, parsedSenderJID, client)
sender = senderJID.ToNonAD().String() // Use full JID format for consistency
} else {
// Fallback to participant string, but ensure it's not empty
@@ -195,7 +188,8 @@ func processConversationMessages(ctx context.Context, data *waHistorySync.Histor
continue
}
// For individual chats, use the chat JID as sender with full format
- sender = jid.String() // Use full JID format for consistency
+ senderJID = jid
+ sender = senderJID.String() // Use full JID format for consistency
}
}
@@ -203,6 +197,48 @@ func processConversationMessages(ctx context.Context, data *waHistorySync.Histor
// WhatsApp history sync timestamps are in seconds, not milliseconds
timestamp := time.Unix(int64(msg.GetMessageTimestamp()), 0)
+ if msg.GetMessage().GetReactionMessage() != nil {
+ if senderJID.IsEmpty() {
+ parsed, err := types.ParseJID(sender)
+ if err != nil {
+ log.Warnf("Skipping reaction %s: failed to parse sender %q: %v", messageID, sender, err)
+ continue
+ }
+ senderJID = parsed
+ }
+
+ reactionEvt := &events.Message{
+ Info: types.MessageInfo{
+ MessageSource: types.MessageSource{
+ Chat: jid,
+ Sender: senderJID,
+ IsFromMe: isFromMe,
+ IsGroup: jid.Server == types.GroupServer,
+ },
+ ID: messageID,
+ PushName: msg.GetPushName(),
+ Timestamp: timestamp,
+ },
+ Message: msg.GetMessage(),
+ }
+ if err := chatStorageRepo.CreateReaction(ctx, reactionEvt); err != nil {
+ log.Warnf("Failed to store history reaction %s for chat %s: %v", messageID, chatJID, err)
+ }
+ if timestamp.After(latestTimestamp) {
+ latestTimestamp = timestamp
+ }
+ continue
+ }
+
+ // Extract message content and media info
+ content := utils.ExtractMessageTextFromProto(msg.GetMessage())
+ mediaType, filename, url, mediaKey, fileSHA256, fileEncSHA256, fileLength := utils.ExtractMediaInfo(msg.GetMessage())
+
+ // Skip if there's no content and no media
+ if content == "" && mediaType == "" {
+ continue
+ }
+
// Track latest timestamp
if timestamp.After(latestTimestamp) {
latestTimestamp = timestamp
diff --git a/src/infrastructure/whatsapp/history_sync_test.go b/src/infrastructure/whatsapp/history_sync_test.go
new file mode 100644
index 00000000..708fae15
--- /dev/null
+++ b/src/infrastructure/whatsapp/history_sync_test.go
@@ -0,0 +1,97 @@
+package whatsapp
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
+ "go.mau.fi/whatsmeow/proto/waCommon"
+ "go.mau.fi/whatsmeow/proto/waE2E"
+ "go.mau.fi/whatsmeow/proto/waHistorySync"
+ "go.mau.fi/whatsmeow/proto/waWeb"
+ "go.mau.fi/whatsmeow/types"
+ "go.mau.fi/whatsmeow/types/events"
+ waLog "go.mau.fi/whatsmeow/util/log"
+ "google.golang.org/protobuf/proto"
+)
+
+func TestProcessConversationMessagesPersistsReactionEvents(t *testing.T) {
+ originalLog := log
+ log = waLog.Noop
+ defer func() { log = originalLog }()
+
+ deviceID := "[email protected]"
+ chatJID := "[email protected]"
+ repo := &historyReactionRepoSpy{}
+
+ ctx := ContextWithDevice(context.Background(), NewDeviceInstance(deviceID, nil, nil))
+ syncType := waHistorySync.HistorySync_RECENT
+ reactionTimestamp := uint64(time.Date(2026, time.May, 16, 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),
+ FromMe: proto.Bool(false),
+ ID: proto.String("reaction-event-1"),
+ },
+ Message: &waE2E.Message{
+ ReactionMessage: &waE2E.ReactionMessage{
+ Key: &waCommon.MessageKey{
+ RemoteJID: proto.String(chatJID),
+ FromMe: proto.Bool(false),
+ ID: proto.String("msg-1"),
+ },
+ Text: proto.String("\U0001f44d"),
+ },
+ },
+ MessageTimestamp: &reactionTimestamp,
+ },
+ },
+ },
+ },
+ },
+ }
+
+ if err := processConversationMessages(ctx, data, repo, nil); err != nil {
+ t.Fatalf("process conversation messages: %v", err)
+ }
+
+ if repo.createReactionCalls != 1 {
+ t.Fatalf("expected history reaction event to be persisted once, got %d", repo.createReactionCalls)
+ }
+ if repo.lastReaction == nil {
+ t.Fatal("expected reaction event to be passed to repository")
+ }
+ if got := repo.lastReaction.Message.GetReactionMessage().GetText(); got != "\U0001f44d" {
+ t.Fatalf("expected thumbs-up reaction, got %q", got)
+ }
+ if got := repo.lastReaction.Message.GetReactionMessage().GetKey().GetID(); got != "msg-1" {
+ t.Fatalf("expected target message id msg-1, got %q", got)
+ }
+}
+
+type historyReactionRepoSpy struct {
+ domainChatStorage.IChatStorageRepository
+ createReactionCalls int
+ lastReaction *events.Message
+}
+
+func (r *historyReactionRepoSpy) CreateReaction(_ context.Context, evt *events.Message) error {
+ r.createReactionCalls++
+ r.lastReaction = evt
+ return nil
+}
+
+func (r *historyReactionRepoSpy) GetChatNameWithPushName(jid types.JID, _ string, _ string, pushName string) string {
+ if pushName != "" {
+ return pushName
+ }
+ return jid.String()
+}
diff --git a/src/usecase/chat.go b/src/usecase/chat.go
index 9f5d6922..afb2b9a9 100644
--- a/src/usecase/chat.go
+++ b/src/usecase/chat.go
@@ -179,6 +179,17 @@ func (service serviceChat) GetChatMessages(ctx context.Context, request domainCh
CreatedAt: message.CreatedAt.Format(time.RFC3339),
UpdatedAt: message.UpdatedAt.Format(time.RFC3339),
}
+ if len(message.Reactions) > 0 {
+ messageInfo.Reactions = make([]domainChat.ReactionInfo, 0, len(message.Reactions))
+ for _, reaction := range message.Reactions {
+ messageInfo.Reactions = append(messageInfo.Reactions, domainChat.ReactionInfo{
+ Emoji: reaction.Emoji,
+ SenderJID: reaction.ReactorJID,
+ IsFromMe: reaction.IsFromMe,
+ Timestamp: reaction.Timestamp.Format(time.RFC3339),
+ })
+ }
+ }
messageInfos = append(messageInfos, messageInfo)
}
diff --git a/src/usecase/chat_test.go b/src/usecase/chat_test.go
new file mode 100644
index 00000000..bf00727d
--- /dev/null
+++ b/src/usecase/chat_test.go
@@ -0,0 +1,99 @@
+package usecase
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ domainChat "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chat"
+ domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/whatsapp"
+ "go.mau.fi/whatsmeow/types/events"
+)
+
+func TestGetChatMessagesMapsReactions(t *testing.T) {
+ deviceID := "[email protected]"
+ chatJID := "[email protected]"
+ now := time.Date(2026, time.May, 16, 8, 0, 0, 0, time.UTC)
+ repo := &chatUsecaseRepoStub{
+ chat: &domainChatStorage.Chat{
+ DeviceID: deviceID,
+ JID: chatJID,
+ Name: "Alice",
+ LastMessageTime: now,
+ CreatedAt: now,
+ UpdatedAt: now,
+ },
+ messages: []*domainChatStorage.Message{
+ {
+ ID: "msg-1",
+ ChatJID: chatJID,
+ DeviceID: deviceID,
+ Sender: "[email protected]",
+ Content: "hello",
+ Timestamp: now,
+ CreatedAt: now,
+ UpdatedAt: now,
+ Reactions: []domainChatStorage.Reaction{
+ {
+ MessageID: "msg-1",
+ ChatJID: chatJID,
+ DeviceID: deviceID,
+ ReactorJID: "[email protected]",
+ Emoji: "\U0001f44d",
+ IsFromMe: false,
+ Timestamp: now.Add(time.Minute),
+ },
+ },
+ },
+ },
+ }
+ service := NewChatService(repo)
+ ctx := whatsapp.ContextWithDevice(context.Background(), whatsapp.NewDeviceInstance(deviceID, nil, nil))
+
+ response, err := service.GetChatMessages(ctx, domainChat.GetChatMessagesRequest{
+ ChatJID: chatJID,
+ Limit: 50,
+ })
+ if err != nil {
+ t.Fatalf("get chat messages: %v", err)
+ }
+ if len(response.Data) != 1 {
+ t.Fatalf("expected one message, got %d", len(response.Data))
+ }
+ reactions := response.Data[0].Reactions
+ if len(reactions) != 1 {
+ t.Fatalf("expected one reaction, got %d", len(reactions))
+ }
+ if reactions[0].Emoji != "\U0001f44d" {
+ t.Fatalf("expected reaction emoji to be mapped, got %q", reactions[0].Emoji)
+ }
+ if reactions[0].SenderJID != "[email protected]" {
+ t.Fatalf("expected reactor JID to be mapped, got %q", reactions[0].SenderJID)
+ }
+ if reactions[0].Timestamp != now.Add(time.Minute).Format(time.RFC3339) {
+ t.Fatalf("expected reaction timestamp to be mapped, got %q", reactions[0].Timestamp)
+ }
+}
+
+type chatUsecaseRepoStub struct {
+ domainChatStorage.IChatStorageRepository
+ chat *domainChatStorage.Chat
+ messages []*domainChatStorage.Message
+}
+
+func (r *chatUsecaseRepoStub) GetChatByDevice(_, _ string) (*domainChatStorage.Chat, error) {
+ return r.chat, nil
+}
+
+func (r *chatUsecaseRepoStub) GetMessages(*domainChatStorage.MessageFilter) ([]*domainChatStorage.Message, error) {
+ return r.messages, nil
+}
+
+func (r *chatUsecaseRepoStub) GetChatMessageCount(string) (int64, error) {
+ return int64(len(r.messages)), nil
+}
+
+func (r *chatUsecaseRepoStub) CreateReaction(context.Context, *events.Message) error {
+ return nil
+}