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.

17.6 KB
Raw Blame
package chatstorage

import (
	"context"
	"database/sql"
	"errors"
	"path/filepath"
	"testing"
	"time"

	domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
	"github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/whatsapp"
	"github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/sqlite"
	"go.mau.fi/whatsmeow/proto/waE2E"
	"go.mau.fi/whatsmeow/types"
	"go.mau.fi/whatsmeow/types/events"
	"google.golang.org/protobuf/proto"
)

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 TestCreateMessageFromMeKeepsPeerChatName(t *testing.T) {
	repo := newTestSQLiteRepository(t)
	accountJID := types.NewJID("15550101000", types.DefaultUserServer)
	peerJID := types.NewJID("15550102000", types.DefaultUserServer)
	timestamp := time.Date(2026, time.September, 2, 15, 30, 0, 0, time.UTC)

	if err := repo.StoreChat(&domainChatStorage.Chat{
		DeviceID:        accountJID.String(),
		JID:             peerJID.String(),
		Name:            peerJID.User,
		LastMessageTime: timestamp.Add(-time.Minute),
	}); err != nil {
		t.Fatalf("store peer chat: %v", err)
	}

	ctx := whatsapp.ContextWithDevice(
		context.Background(),
		whatsapp.NewDeviceInstance(accountJID.String(), nil, repo),
	)
	event := &events.Message{
		Info: types.MessageInfo{
			MessageSource: types.MessageSource{
				Chat:     peerJID,
				Sender:   accountJID,
				IsFromMe: true,
			},
			ID:        "outgoing-message-1",
			PushName:  "Alice Smith",
			Timestamp: timestamp,
		},
		Message: &waE2E.Message{Conversation: proto.String("Hello Bob")},
	}

	if err := repo.CreateMessage(ctx, event); err != nil {
		t.Fatalf("create outgoing message: %v", err)
	}

	chat, err := repo.GetChatByDevice(accountJID.String(), peerJID.String())
	if err != nil {
		t.Fatalf("get peer chat: %v", err)
	}
	if chat == nil {
		t.Fatal("expected peer chat")
	}
	if chat.Name != peerJID.User {
		t.Fatalf("outgoing message changed peer chat name to %q, want %q", chat.Name, peerJID.User)
	}
}

func TestSQLiteRepositoryGetsDeviceWebhookConfigByJID(t *testing.T) {
	repo := newTestSQLiteRepository(t)

	webhookURL := "https://device-webhook.example.com"
	if err := repo.SaveDeviceRecord(&domainChatStorage.DeviceRecord{
		DeviceID:    "session-a",
		DisplayName: "Session A",
		JID:         "[email protected]",
	}); err != nil {
		t.Fatalf("save device record: %v", err)
	}

	if err := repo.SetDeviceWebhookConfig("session-a", &domainChatStorage.DeviceWebhookConfig{
		WebhookURL:                &webhookURL,
		WebhookSecret:             "device-secret",
		WebhookEvents:             "message,message.ack",
		WebhookInsecureSkipVerify: true,
	}); err != nil {
		t.Fatalf("set device webhook config: %v", err)
	}

	record, err := repo.GetDeviceRecordByJID("[email protected]")
	if err != nil {
		t.Fatalf("get device record by jid: %v", err)
	}
	if record == nil {
		t.Fatal("expected device record")
	}
	if record.DeviceID != "session-a" {
		t.Fatalf("expected session-a, got %q", record.DeviceID)
	}
	if record.WebhookURL == nil || *record.WebhookURL != webhookURL {
		t.Fatalf("expected webhook URL %q, got %v", webhookURL, record.WebhookURL)
	}
	if record.WebhookSecret != "device-secret" {
		t.Fatalf("expected device secret, got %q", record.WebhookSecret)
	}
	if record.WebhookEvents != "message,message.ack" {
		t.Fatalf("expected webhook events, got %q", record.WebhookEvents)
	}
	if !record.WebhookInsecureSkipVerify {
		t.Fatal("expected insecure skip verify to be true")
	}
}

func TestSQLiteRepositorySetDeviceWebhookConfigReturnsErrNoRowsForMissingDevice(t *testing.T) {
	repo := newTestSQLiteRepository(t)

	webhookURL := "https://device-webhook.example.com"
	err := repo.SetDeviceWebhookConfig("missing-device", &domainChatStorage.DeviceWebhookConfig{
		WebhookURL: &webhookURL,
	})
	if !errors.Is(err, sql.ErrNoRows) {
		t.Fatalf("expected sql.ErrNoRows for missing device, got %v", err)
	}
}

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 TestStoreSentMessageWithContextRequiresDeviceInContext(t *testing.T) {
	repo := newTestSQLiteRepository(t)
	deviceID := "[email protected]"
	chatJID := "[email protected]"
	now := time.Date(2026, time.May, 22, 10, 0, 0, 0, time.UTC)

	err := repo.StoreSentMessageWithContext(
		context.Background(),
		"msg-sent-1",
		deviceID,
		chatJID,
		"hello from api",
		now,
		nil,
	)
	if err == nil {
		t.Fatal("expected error when storing sent message without device context")
	}
	if !errors.Is(err, domainChatStorage.ErrMissingDeviceContext) {
		t.Fatalf("expected missing device context error, got %v", err)
	}
}

func TestSQLiteRepositoryStoresMessageDirectPath(t *testing.T) {
	repo := newTestSQLiteRepository(t)
	deviceID := "[email protected]"
	chatJID := "[email protected]"
	now := time.Date(2026, time.June, 19, 8, 0, 0, 0, time.UTC)
	directPath := "/v/t62.7118-24/media.enc?ccb=11-4"

	if err := repo.StoreChat(&domainChatStorage.Chat{
		DeviceID:        deviceID,
		JID:             chatJID,
		Name:            chatJID,
		LastMessageTime: now,
	}); err != nil {
		t.Fatalf("store chat: %v", err)
	}
	if err := repo.StoreMessage(&domainChatStorage.Message{
		ID:            "msg-media-1",
		ChatJID:       chatJID,
		DeviceID:      deviceID,
		Sender:        "[email protected]",
		Timestamp:     now,
		MediaType:     "image",
		URL:           "https://mmg.whatsapp.net/v/t62.7118-24/media.enc?ccb=11-4",
		DirectPath:    directPath,
		MediaKey:      []byte("media-key"),
		FileSHA256:    []byte("file-sha"),
		FileEncSHA256: []byte("file-enc-sha"),
		FileLength:    1234,
	}); err != nil {
		t.Fatalf("store message: %v", err)
	}

	got, err := repo.GetMessageByID("msg-media-1")
	if err != nil {
		t.Fatalf("get message by id: %v", err)
	}
	if got == nil {
		t.Fatal("expected stored message")
	}
	if got.DirectPath != directPath {
		t.Fatalf("DirectPath = %q, want %q", got.DirectPath, directPath)
	}
}

func TestSQLiteRepositoryStoresBatchMessageDirectPath(t *testing.T) {
	repo := newTestSQLiteRepository(t)
	deviceID := "[email protected]"
	chatJID := "[email protected]"
	now := time.Date(2026, time.June, 19, 8, 0, 0, 0, time.UTC)
	directPath := "/v/t62.7118-24/batch-media.enc?ccb=11-4"

	if err := repo.StoreChat(&domainChatStorage.Chat{
		DeviceID:        deviceID,
		JID:             chatJID,
		Name:            chatJID,
		LastMessageTime: now,
	}); err != nil {
		t.Fatalf("store chat: %v", err)
	}
	if err := repo.StoreMessagesBatch([]*domainChatStorage.Message{{
		ID:            "msg-media-batch-1",
		ChatJID:       chatJID,
		DeviceID:      deviceID,
		Sender:        "[email protected]",
		Timestamp:     now,
		MediaType:     "video",
		URL:           "https://mmg.whatsapp.net/v/t62.7118-24/batch-media.enc?ccb=11-4",
		DirectPath:    directPath,
		MediaKey:      []byte("media-key"),
		FileSHA256:    []byte("file-sha"),
		FileEncSHA256: []byte("file-enc-sha"),
		FileLength:    5678,
	}}); err != nil {
		t.Fatalf("store messages batch: %v", err)
	}

	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))
	}
	if messages[0].DirectPath != directPath {
		t.Fatalf("DirectPath = %q, want %q", messages[0].DirectPath, directPath)
	}
}

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
}

// TestSQLiteRepositoryGetOldestMessageByDevice pins the on-demand history sync
// anchor lookup: it must return the earliest message by timestamp for the
// given chat/device, ignoring newer messages and other devices' messages, and
// return (nil, nil) for a chat with nothing stored yet.
func TestSQLiteRepositoryGetOldestMessageByDevice(t *testing.T) {
	repo := newTestSQLiteRepository(t)
	deviceID := "[email protected]"
	otherDeviceID := "[email protected]"
	chatJID := "[email protected]"
	base := time.Date(2026, time.June, 19, 8, 0, 0, 0, time.UTC)

	if err := repo.StoreChat(&domainChatStorage.Chat{
		DeviceID:        deviceID,
		JID:             chatJID,
		Name:            chatJID,
		LastMessageTime: base,
	}); err != nil {
		t.Fatalf("store chat: %v", err)
	}

	got, err := repo.GetOldestMessageByDevice(deviceID, chatJID)
	if err != nil {
		t.Fatalf("get oldest message (empty chat): %v", err)
	}
	if got != nil {
		t.Fatalf("expected nil for chat with no stored messages, got %+v", got)
	}

	messages := []*domainChatStorage.Message{
		{ID: "msg-newest", ChatJID: chatJID, DeviceID: deviceID, Sender: "[email protected]", Content: "newest", Timestamp: base.Add(2 * time.Hour)},
		{ID: "msg-oldest", ChatJID: chatJID, DeviceID: deviceID, Sender: "[email protected]", Content: "oldest", Timestamp: base},
		{ID: "msg-middle", ChatJID: chatJID, DeviceID: deviceID, Sender: "[email protected]", Content: "middle", Timestamp: base.Add(1 * time.Hour)},
		// Older timestamp but a different device — must not be selected.
		{ID: "msg-other-device", ChatJID: chatJID, DeviceID: otherDeviceID, Sender: "[email protected]", Content: "other device", Timestamp: base.Add(-1 * time.Hour)},
	}
	if err := repo.StoreMessagesBatch(messages); err != nil {
		t.Fatalf("store messages batch: %v", err)
	}

	got, err = repo.GetOldestMessageByDevice(deviceID, chatJID)
	if err != nil {
		t.Fatalf("get oldest message: %v", err)
	}
	if got == nil {
		t.Fatal("expected the oldest stored message, got nil")
	}
	if got.ID != "msg-oldest" {
		t.Fatalf("oldest message ID = %q, want %q", got.ID, "msg-oldest")
	}
}

// TestSQLiteRepositoryGetOldestMessageByDeviceSkipsSyntheticCallRows pins the
// history-sync anchor fix: a synthetic call row (media_type "call", id
// "call:<callID>") stored by CreateIncomingCallRecord is not a real WhatsApp
// message the phone can recognize as a history-sync anchor, so it must never
// be selected over an older-but-real message.
func TestSQLiteRepositoryGetOldestMessageByDeviceSkipsSyntheticCallRows(t *testing.T) {
	repo := newTestSQLiteRepository(t)
	deviceID := "[email protected]"
	chatJID := "[email protected]"
	base := time.Date(2026, time.June, 19, 8, 0, 0, 0, time.UTC)

	if err := repo.StoreChat(&domainChatStorage.Chat{
		DeviceID:        deviceID,
		JID:             chatJID,
		Name:            chatJID,
		LastMessageTime: base,
	}); err != nil {
		t.Fatalf("store chat: %v", err)
	}

	// Synthetic call row, older than the real message.
	if err := repo.StoreMessage(&domainChatStorage.Message{
		ID:        "call:call-1",
		ChatJID:   chatJID,
		DeviceID:  deviceID,
		Sender:    "[email protected]",
		Content:   "Incoming call",
		Timestamp: base.Add(-1 * time.Hour),
		MediaType: "call",
	}); err != nil {
		t.Fatalf("store synthetic call row: %v", err)
	}

	if err := repo.StoreMessage(&domainChatStorage.Message{
		ID:        "msg-real",
		ChatJID:   chatJID,
		DeviceID:  deviceID,
		Sender:    "[email protected]",
		Content:   "real message",
		Timestamp: base,
	}); err != nil {
		t.Fatalf("store real message: %v", err)
	}

	got, err := repo.GetOldestMessageByDevice(deviceID, chatJID)
	if err != nil {
		t.Fatalf("get oldest message: %v", err)
	}
	if got == nil {
		t.Fatal("expected the real message, got nil")
	}
	if got.ID != "msg-real" {
		t.Fatalf("oldest message ID = %q, want %q (synthetic call row must be excluded)", got.ID, "msg-real")
	}
}

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
}