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.

chore: remove dead code and modernize interface{} to any

Aldino Kemal2e1798be7bc8
diff --git a/src/config/settings.go b/src/config/settings.go
index 0e450f75..e0355e2c 100644
--- a/src/config/settings.go
+++ b/src/config/settings.go
@@ -5,7 +5,7 @@ import (
)
var (
- AppVersion = "v8.4.0"
+ AppVersion = "v8.5.0"
AppPort = "3000"
AppHost = "0.0.0.0"
AppDebug = false
diff --git a/src/domains/send/video.go b/src/domains/send/video.go
index 116ca0d2..c1a188e9 100644
--- a/src/domains/send/video.go
+++ b/src/domains/send/video.go
@@ -4,10 +4,10 @@ import "mime/multipart"
type VideoRequest struct {
BaseRequest
- Caption string `json:"caption" form:"caption"`
- Video *multipart.FileHeader `json:"video" form:"video"`
- ViewOnce bool `json:"view_once" form:"view_once"`
+ Caption string `json:"caption" form:"caption"`
+ Video *multipart.FileHeader `json:"video" form:"video"`
+ ViewOnce bool `json:"view_once" form:"view_once"`
Compress bool `json:"compress"`
GifPlayback bool `json:"gif_playback" form:"gif_playback"`
- VideoURL *string `json:"video_url" form:"video_url"`
+ VideoURL *string `json:"video_url" form:"video_url"`
}
diff --git a/src/infrastructure/chatstorage/device_repository.go b/src/infrastructure/chatstorage/device_repository.go
deleted file mode 100644
index fcd1b9c5..00000000
--- a/src/infrastructure/chatstorage/device_repository.go
+++ /dev/null
@@ -1,181 +0,0 @@
-package chatstorage
-
-import (
- "context"
- "time"
-
- domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
- "go.mau.fi/whatsmeow/proto/waE2E"
- "go.mau.fi/whatsmeow/types"
- "go.mau.fi/whatsmeow/types/events"
-)
-
-// DeviceRepository wraps a base repository and injects device_id into all operations.
-// This keeps the existing interface while making sure each device is logically separated.
-type DeviceRepository struct {
- deviceID string
- base domainChatStorage.IChatStorageRepository
-}
-
-func NewDeviceRepository(deviceID string, base domainChatStorage.IChatStorageRepository) domainChatStorage.IChatStorageRepository {
- return &DeviceRepository{
- deviceID: deviceID,
- base: base,
- }
-}
-
-func (r *DeviceRepository) withDeviceChat(chat *domainChatStorage.Chat) *domainChatStorage.Chat {
- if chat == nil {
- return nil
- }
- if chat.DeviceID == "" {
- chat.DeviceID = r.deviceID
- }
- return chat
-}
-
-func (r *DeviceRepository) CreateMessage(ctx context.Context, evt *events.Message) error {
- // Base repository will attempt to derive device id from client; keep call unchanged for now.
- return r.base.CreateMessage(ctx, evt)
-}
-
-func (r *DeviceRepository) CreateIncomingCallRecord(ctx context.Context, evt *events.CallOffer, autoRejected bool) error {
- return r.base.CreateIncomingCallRecord(ctx, evt, autoRejected)
-}
-
-func (r *DeviceRepository) StoreChat(chat *domainChatStorage.Chat) error {
- return r.base.StoreChat(r.withDeviceChat(chat))
-}
-
-func (r *DeviceRepository) GetChat(jid string) (*domainChatStorage.Chat, error) {
- return r.base.GetChatByDevice(r.deviceID, jid)
-}
-
-func (r *DeviceRepository) GetChatByDevice(deviceID, jid string) (*domainChatStorage.Chat, error) {
- return r.base.GetChatByDevice(deviceID, jid)
-}
-
-func (r *DeviceRepository) GetChats(filter *domainChatStorage.ChatFilter) ([]*domainChatStorage.Chat, error) {
- if filter != nil && filter.DeviceID == "" {
- filter.DeviceID = r.deviceID
- }
- return r.base.GetChats(filter)
-}
-
-func (r *DeviceRepository) DeleteChat(jid string) error {
- return r.base.DeleteChatByDevice(r.deviceID, jid)
-}
-
-func (r *DeviceRepository) DeleteChatByDevice(deviceID, jid string) error {
- return r.base.DeleteChatByDevice(deviceID, jid)
-}
-
-func (r *DeviceRepository) StoreMessage(message *domainChatStorage.Message) error {
- return r.base.StoreMessage(message)
-}
-
-func (r *DeviceRepository) StoreMessagesBatch(messages []*domainChatStorage.Message) error {
- return r.base.StoreMessagesBatch(messages)
-}
-
-func (r *DeviceRepository) GetMessageByID(id string) (*domainChatStorage.Message, error) {
- return r.base.GetMessageByID(id)
-}
-
-func (r *DeviceRepository) GetMessages(filter *domainChatStorage.MessageFilter) ([]*domainChatStorage.Message, error) {
- if filter != nil && filter.DeviceID == "" {
- filter.DeviceID = r.deviceID
- }
- return r.base.GetMessages(filter)
-}
-
-func (r *DeviceRepository) SearchMessages(deviceID, chatJID, searchText string, limit int) ([]*domainChatStorage.Message, error) {
- targetDeviceID := deviceID
- if targetDeviceID == "" {
- targetDeviceID = r.deviceID
- }
- return r.base.SearchMessages(targetDeviceID, chatJID, searchText, limit)
-}
-
-func (r *DeviceRepository) DeleteMessage(id, chatJID string) error {
- return r.base.DeleteMessageByDevice(r.deviceID, id, chatJID)
-}
-
-func (r *DeviceRepository) DeleteMessageByDevice(deviceID, id, chatJID string) error {
- return r.base.DeleteMessageByDevice(deviceID, id, chatJID)
-}
-
-func (r *DeviceRepository) StoreSentMessageWithContext(ctx context.Context, messageID string, senderJID string, recipientJID string, content string, timestamp time.Time, msg *waE2E.Message) error {
- return r.base.StoreSentMessageWithContext(ctx, messageID, senderJID, recipientJID, content, timestamp, msg)
-}
-
-func (r *DeviceRepository) GetChatMessageCount(chatJID string) (int64, error) {
- return r.base.GetChatMessageCountByDevice(r.deviceID, chatJID)
-}
-
-func (r *DeviceRepository) GetChatMessageCountByDevice(deviceID, chatJID string) (int64, error) {
- return r.base.GetChatMessageCountByDevice(deviceID, chatJID)
-}
-
-func (r *DeviceRepository) GetTotalMessageCount() (int64, error) {
- return r.base.GetTotalMessageCount()
-}
-
-func (r *DeviceRepository) GetTotalChatCount() (int64, error) {
- return r.base.GetTotalChatCount()
-}
-
-func (r *DeviceRepository) GetFilteredChatCount(filter *domainChatStorage.ChatFilter) (int64, error) {
- if filter != nil && filter.DeviceID == "" {
- filter.DeviceID = r.deviceID
- }
- return r.base.GetFilteredChatCount(filter)
-}
-
-func (r *DeviceRepository) GetChatNameWithPushName(jid types.JID, chatJID string, senderUser string, pushName string) string {
- return r.base.GetChatNameWithPushNameByDevice(r.deviceID, jid, chatJID, senderUser, pushName)
-}
-
-func (r *DeviceRepository) GetChatNameWithPushNameByDevice(deviceID string, jid types.JID, chatJID string, senderUser string, pushName string) string {
- return r.base.GetChatNameWithPushNameByDevice(deviceID, jid, chatJID, senderUser, pushName)
-}
-
-func (r *DeviceRepository) GetStorageStatistics() (chatCount int64, messageCount int64, err error) {
- return r.base.GetStorageStatistics()
-}
-
-func (r *DeviceRepository) TruncateAllChats() error {
- return r.base.TruncateAllChats()
-}
-
-func (r *DeviceRepository) TruncateAllDataWithLogging(logPrefix string) error {
- return r.base.TruncateAllDataWithLogging(logPrefix)
-}
-
-func (r *DeviceRepository) InitializeSchema() error {
- return r.base.InitializeSchema()
-}
-
-func (r *DeviceRepository) DeleteDeviceData(deviceID string) error {
- target := deviceID
- if target == "" {
- target = r.deviceID
- }
- return r.base.DeleteDeviceData(target)
-}
-
-func (r *DeviceRepository) SaveDeviceRecord(record *domainChatStorage.DeviceRecord) error {
- return r.base.SaveDeviceRecord(record)
-}
-
-func (r *DeviceRepository) ListDeviceRecords() ([]*domainChatStorage.DeviceRecord, error) {
- return r.base.ListDeviceRecords()
-}
-
-func (r *DeviceRepository) GetDeviceRecord(deviceID string) (*domainChatStorage.DeviceRecord, error) {
- return r.base.GetDeviceRecord(deviceID)
-}
-
-func (r *DeviceRepository) DeleteDeviceRecord(deviceID string) error {
- return r.base.DeleteDeviceRecord(deviceID)
-}
diff --git a/src/infrastructure/chatwoot/client.go b/src/infrastructure/chatwoot/client.go
index 429912cd..bd768c7d 100644
--- a/src/infrastructure/chatwoot/client.go
+++ b/src/infrastructure/chatwoot/client.go
@@ -79,7 +79,7 @@ func init() {
ticker := time.NewTicker(sentMessageIDsTTL)
defer ticker.Stop()
for range ticker.C {
- sentMessageIDs.Range(func(key, value interface{}) bool {
+ sentMessageIDs.Range(func(key, value any) bool {
if time.Since(value.(time.Time)) > sentMessageIDsTTL {
sentMessageIDs.Delete(key)
}
@@ -105,53 +105,6 @@ func (c *Client) IsConfigured() bool {
return c.BaseURL != "" && c.APIToken != "" && c.AccountID != 0 && c.InboxID != 0
}
-// doRequest executes an HTTP request with common headers and error handling.
-// It marshals the payload to JSON (if provided), sets auth headers, executes the request,
-// and decodes the response into result (if provided).
-func (c *Client) doRequest(method, endpoint string, payload interface{}, result interface{}) ([]byte, error) {
- var body io.Reader
- if payload != nil {
- jsonPayload, err := json.Marshal(payload)
- if err != nil {
- return nil, fmt.Errorf("failed to marshal payload: %w", err)
- }
- body = bytes.NewBuffer(jsonPayload)
- }
-
- req, err := http.NewRequest(method, endpoint, body)
- if err != nil {
- return nil, err
- }
-
- if payload != nil {
- req.Header.Set("Content-Type", "application/json")
- }
- req.Header.Set("api_access_token", c.APIToken)
-
- resp, err := c.HTTPClient.Do(req)
- if err != nil {
- return nil, err
- }
- defer resp.Body.Close()
-
- bodyBytes, err := io.ReadAll(resp.Body)
- if err != nil {
- return nil, fmt.Errorf("failed to read response body: %w", err)
- }
-
- if resp.StatusCode < 200 || resp.StatusCode >= 300 {
- return bodyBytes, fmt.Errorf("request failed: status %d body %s", resp.StatusCode, string(bodyBytes))
- }
-
- if result != nil && len(bodyBytes) > 0 {
- if err := json.Unmarshal(bodyBytes, result); err != nil {
- return bodyBytes, fmt.Errorf("failed to decode response: %w", err)
- }
- }
-
- return bodyBytes, nil
-}
-
func (c *Client) FindContactByIdentifier(identifier string, isGroup bool) (*Contact, error) {
endpoint := fmt.Sprintf("%s/api/v1/accounts/%d/contacts/search", c.BaseURL, c.AccountID)
logrus.Debugf("Chatwoot: Finding contact by identifier endpoint=%s identifier=%s isGroup=%v", endpoint, identifier, isGroup)
@@ -227,7 +180,7 @@ func (c *Client) CreateContact(name, identifier string, isGroup bool) (*Contact,
Name: name,
PhoneNumber: phoneNumber,
Identifier: contactIdentifier,
- CustomAttributes: map[string]interface{}{
+ CustomAttributes: map[string]any{
"waha_whatsapp_jid": identifier,
},
}
@@ -310,7 +263,7 @@ func (c *Client) FindOrCreateContact(name, identifier string, isGroup bool) (*Co
func (c *Client) UpdateContactName(contactID int, name string) error {
endpoint := fmt.Sprintf("%s/api/v1/accounts/%d/contacts/%d", c.BaseURL, c.AccountID, contactID)
- payload := map[string]interface{}{
+ payload := map[string]any{
"name": name,
}
diff --git a/src/infrastructure/chatwoot/sync.go b/src/infrastructure/chatwoot/sync.go
index d78caae3..053693fb 100644
--- a/src/infrastructure/chatwoot/sync.go
+++ b/src/infrastructure/chatwoot/sync.go
@@ -10,7 +10,6 @@ import (
"sync"
"time"
- "github.com/aldinokemal/go-whatsapp-web-multidevice/config"
domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
"github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
"github.com/sirupsen/logrus"
@@ -399,39 +398,3 @@ func GetSyncService(
func GetDefaultSyncService() *SyncService {
return globalSyncService
}
-
-// TriggerAutoSync is called when a device connects to optionally start auto-sync
-func TriggerAutoSync(deviceID string, chatStorageRepo domainChatStorage.IChatStorageRepository, waClient *whatsmeow.Client) {
- if !config.ChatwootEnabled || !config.ChatwootImportMessages {
- return
- }
-
- client := GetDefaultClient()
- if !client.IsConfigured() {
- logrus.Warn("Chatwoot Sync: Auto-sync skipped - Chatwoot not configured")
- return
- }
-
- // Resolve the storage device ID (JID) from the WhatsApp client,
- // since chats are stored under the full JID, not the user-assigned alias.
- storageDeviceID := deviceID
- if waClient != nil && waClient.Store != nil && waClient.Store.ID != nil {
- if jid := waClient.Store.ID.ToNonAD().String(); jid != "" {
- storageDeviceID = jid
- }
- }
-
- syncService := GetSyncService(client, chatStorageRepo)
-
- go func() {
- opts := DefaultSyncOptions()
- opts.DaysLimit = config.ChatwootDaysLimitImportMessages
-
- logrus.Infof("Chatwoot Sync: Auto-sync triggered for device %s", storageDeviceID)
-
- _, err := syncService.SyncHistory(context.Background(), storageDeviceID, waClient, opts)
- if err != nil {
- logrus.Errorf("Chatwoot Sync: Auto-sync failed for device %s: %v", storageDeviceID, err)
- }
- }()
-}
diff --git a/src/infrastructure/chatwoot/sync_test.go b/src/infrastructure/chatwoot/sync_test.go
index 5af063e0..33d883bd 100644
--- a/src/infrastructure/chatwoot/sync_test.go
+++ b/src/infrastructure/chatwoot/sync_test.go
@@ -7,17 +7,17 @@ import (
func TestSyncProgress_SetRunning(t *testing.T) {
p := NewSyncProgress("test-device")
-
+
if p.Status != "idle" {
t.Errorf("expected initial status 'idle', got '%s'", p.Status)
}
-
+
p.SetRunning()
-
+
if p.Status != "running" {
t.Errorf("expected status 'running', got '%s'", p.Status)
}
-
+
if p.StartedAt == nil {
t.Error("expected StartedAt to be set")
}
@@ -27,11 +27,11 @@ func TestSyncProgress_SetCompleted(t *testing.T) {
p := NewSyncProgress("test-device")
p.SetRunning()
p.SetCompleted()
-
+
if p.Status != "completed" {
t.Errorf("expected status 'completed', got '%s'", p.Status)
}
-
+
if p.CompletedAt == nil {
t.Error("expected CompletedAt to be set")
}
@@ -40,14 +40,14 @@ func TestSyncProgress_SetCompleted(t *testing.T) {
func TestSyncProgress_SetFailed(t *testing.T) {
p := NewSyncProgress("test-device")
p.SetRunning()
-
+
testErr := &testError{msg: "test error"}
p.SetFailed(testErr)
-
+
if p.Status != "failed" {
t.Errorf("expected status 'failed', got '%s'", p.Status)
}
-
+
if p.Error != "test error" {
t.Errorf("expected error 'test error', got '%s'", p.Error)
}
@@ -55,30 +55,30 @@ func TestSyncProgress_SetFailed(t *testing.T) {
func TestSyncProgress_Counters(t *testing.T) {
p := NewSyncProgress("test-device")
-
+
p.SetTotals(10, 100)
if p.TotalChats != 10 || p.TotalMessages != 100 {
t.Errorf("expected totals (10, 100), got (%d, %d)", p.TotalChats, p.TotalMessages)
}
-
+
p.IncrementSyncedChats()
p.IncrementSyncedChats()
if p.SyncedChats != 2 {
t.Errorf("expected synced chats 2, got %d", p.SyncedChats)
}
-
+
p.IncrementSyncedMessages()
p.IncrementSyncedMessages()
p.IncrementSyncedMessages()
if p.SyncedMessages != 3 {
t.Errorf("expected synced messages 3, got %d", p.SyncedMessages)
}
-
+
p.IncrementFailedMessages()
if p.FailedMessages != 1 {
t.Errorf("expected failed messages 1, got %d", p.FailedMessages)
}
-
+
p.AddMessages(50)
if p.TotalMessages != 150 {
t.Errorf("expected total messages 150, got %d", p.TotalMessages)
@@ -91,9 +91,9 @@ func TestSyncProgress_Clone(t *testing.T) {
p.SetTotals(10, 100)
p.IncrementSyncedChats()
p.UpdateChat("test-chat")
-
+
cloned := p.Clone()
-
+
if cloned.DeviceID != p.DeviceID {
t.Error("clone DeviceID mismatch")
}
@@ -110,16 +110,16 @@ func TestSyncProgress_Clone(t *testing.T) {
func TestSyncProgress_IsRunning(t *testing.T) {
p := NewSyncProgress("test-device")
-
+
if p.IsRunning() {
t.Error("expected IsRunning false initially")
}
-
+
p.SetRunning()
if !p.IsRunning() {
t.Error("expected IsRunning true after SetRunning")
}
-
+
p.SetCompleted()
if p.IsRunning() {
t.Error("expected IsRunning false after SetCompleted")
@@ -128,27 +128,27 @@ func TestSyncProgress_IsRunning(t *testing.T) {
func TestDefaultSyncOptions(t *testing.T) {
opts := DefaultSyncOptions()
-
+
if opts.DaysLimit != 3 {
t.Errorf("expected DaysLimit 3, got %d", opts.DaysLimit)
}
-
+
if !opts.IncludeMedia {
t.Error("expected IncludeMedia true")
}
-
+
if !opts.IncludeGroups {
t.Error("expected IncludeGroups true")
}
-
+
if opts.MaxMessagesPerChat != 500 {
t.Errorf("expected MaxMessagesPerChat 500, got %d", opts.MaxMessagesPerChat)
}
-
+
if opts.BatchSize != 10 {
t.Errorf("expected BatchSize 10, got %d", opts.BatchSize)
}
-
+
if opts.DelayBetweenBatches != 500*time.Millisecond {
t.Errorf("expected DelayBetweenBatches 500ms, got %v", opts.DelayBetweenBatches)
}
@@ -170,7 +170,7 @@ func TestGetExtensionForMediaType(t *testing.T) {
{"image", "photo.png", ".png"},
{"document", "report.pdf", ".pdf"},
}
-
+
for _, tt := range tests {
result := getExtensionForMediaType(tt.mediaType, tt.filename)
if result != tt.expected {
diff --git a/src/infrastructure/chatwoot/sync_types.go b/src/infrastructure/chatwoot/sync_types.go
index 5285980b..4d346d2b 100644
--- a/src/infrastructure/chatwoot/sync_types.go
+++ b/src/infrastructure/chatwoot/sync_types.go
@@ -47,10 +47,10 @@ type SyncOptions struct {
// SyncRequest is the API request for triggering a sync
type SyncRequest struct {
- DeviceID string `json:"device_id,omitempty"`
- DaysLimit int `json:"days_limit,omitempty"`
- IncludeMedia bool `json:"include_media"`
- IncludeGroups bool `json:"include_groups"`
+ DeviceID string `json:"device_id,omitempty"`
+ DaysLimit int `json:"days_limit,omitempty"`
+ IncludeMedia bool `json:"include_media"`
+ IncludeGroups bool `json:"include_groups"`
}
// SyncResponse is the API response for sync operations
diff --git a/src/infrastructure/chatwoot/types.go b/src/infrastructure/chatwoot/types.go
index 7bb7c503..b37e2464 100644
--- a/src/infrastructure/chatwoot/types.go
+++ b/src/infrastructure/chatwoot/types.go
@@ -1,12 +1,12 @@
package chatwoot
type Contact struct {
- ID int `json:"id"`
- Name string `json:"name"`
- Email string `json:"email"`
- PhoneNumber string `json:"phone_number"`
- Identifier string `json:"identifier"`
- CustomAttributes map[string]interface{} `json:"custom_attributes"`
+ ID int `json:"id"`
+ Name string `json:"name"`
+ Email string `json:"email"`
+ PhoneNumber string `json:"phone_number"`
+ Identifier string `json:"identifier"`
+ CustomAttributes map[string]any `json:"custom_attributes"`
}
type Conversation struct {
@@ -25,11 +25,11 @@ type Message struct {
}
type CreateContactRequest struct {
- InboxID int `json:"inbox_id"`
- Name string `json:"name"`
- PhoneNumber string `json:"phone_number,omitempty"`
- Identifier string `json:"identifier,omitempty"`
- CustomAttributes map[string]interface{} `json:"custom_attributes"`
+ InboxID int `json:"inbox_id"`
+ Name string `json:"name"`
+ PhoneNumber string `json:"phone_number,omitempty"`
+ Identifier string `json:"identifier,omitempty"`
+ CustomAttributes map[string]any `json:"custom_attributes"`
}
type CreateConversationRequest struct {
diff --git a/src/infrastructure/whatsapp/chatwoot_forward_test.go b/src/infrastructure/whatsapp/chatwoot_forward_test.go
index cf17372f..fcf8e091 100644
--- a/src/infrastructure/whatsapp/chatwoot_forward_test.go
+++ b/src/infrastructure/whatsapp/chatwoot_forward_test.go
@@ -105,14 +105,14 @@ func TestIsEventWhitelistedForChatwoot(t *testing.T) {
func TestBuildReactionChatwootContent(t *testing.T) {
tests := []struct {
name string
- payload map[string]interface{}
+ payload map[string]any
isGroup bool
fromName string
expected string
}{
{
name: "group reaction with sender name and target id",
- payload: map[string]interface{}{
+ payload: map[string]any{
"reaction": "πŸ‘",
"reacted_message_id": "wamid-123",
},
@@ -122,7 +122,7 @@ func TestBuildReactionChatwootContent(t *testing.T) {
},
{
name: "direct reaction falls back to phone",
- payload: map[string]interface{}{
+ payload: map[string]any{
"reaction": "πŸ”₯",
"reacted_message_id": "wamid-456",
"from": "[email protected]",
@@ -133,7 +133,7 @@ func TestBuildReactionChatwootContent(t *testing.T) {
},
{
name: "reaction removal",
- payload: map[string]interface{}{
+ payload: map[string]any{
"reaction": "",
"reacted_message_id": "wamid-789",
},
@@ -143,7 +143,7 @@ func TestBuildReactionChatwootContent(t *testing.T) {
},
{
name: "group reaction falls back to sender jid when pushname missing",
- payload: map[string]interface{}{
+ payload: map[string]any{
"reaction": "πŸ˜‚",
"reacted_message_id": "wamid-999",
"from": "[email protected]",
@@ -154,7 +154,7 @@ func TestBuildReactionChatwootContent(t *testing.T) {
},
{
name: "missing target id still produces readable text",
- payload: map[string]interface{}{
+ payload: map[string]any{
"reaction": "❀️",
},
isGroup: true,
diff --git a/src/infrastructure/whatsapp/cleanup.go b/src/infrastructure/whatsapp/cleanup.go
deleted file mode 100644
index e2f06913..00000000
--- a/src/infrastructure/whatsapp/cleanup.go
+++ /dev/null
@@ -1,267 +0,0 @@
-package whatsapp
-
-import (
- "context"
- "fmt"
- "os"
- "path/filepath"
- "strings"
-
- "github.com/aldinokemal/go-whatsapp-web-multidevice/config"
- domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
- "github.com/sirupsen/logrus"
- "go.mau.fi/whatsmeow"
- "go.mau.fi/whatsmeow/store/sqlstore"
-)
-
-// CleanupDatabase removes the database file (SQLite) or deletes all devices (PostgreSQL) to prevent foreign key constraint issues
-func CleanupDatabase() error {
- // Check if using PostgreSQL - for PostgreSQL we can use RLock since we're not closing connections
- if strings.HasPrefix(config.DBURI, "postgres:") {
- globalStateMu.RLock()
- currentDB := db
- currentKeysDB := keysDB
- globalStateMu.RUnlock()
-
- logrus.Info("[CLEANUP] PostgreSQL detected - deleting all devices from database")
-
- // Check if database is initialized
- if currentDB == nil {
- logrus.Warn("[CLEANUP] Database is nil, skipping device deletion")
- return nil
- }
-
- ctx := context.Background()
-
- // Get all devices
- devices, err := currentDB.GetAllDevices(ctx)
- if err != nil {
- logrus.Errorf("[CLEANUP] Error getting devices: %v", err)
- return fmt.Errorf("failed to get devices: %v", err)
- }
-
- logrus.Infof("[CLEANUP] Found %d devices to delete", len(devices))
-
- // Delete each device (this will cascade delete related records like identity keys, sessions, etc.)
- for _, device := range devices {
- logrus.Infof("[CLEANUP] Deleting device: %s", device.ID)
- if err := currentDB.DeleteDevice(ctx, device); err != nil {
- logrus.Errorf("[CLEANUP] Error deleting device %s: %v", device.ID, err)
- return fmt.Errorf("failed to delete device %s: %v", device.ID, err)
- }
- }
-
- // Also clean up keysDB if it exists and is separate
- if currentKeysDB != nil && currentKeysDB != currentDB {
- keysDevices, err := currentKeysDB.GetAllDevices(ctx)
- if err != nil {
- logrus.Errorf("[CLEANUP] Error getting devices from keysDB: %v", err)
- return fmt.Errorf("failed to get devices from keysDB: %v", err)
- }
-
- logrus.Infof("[CLEANUP] Found %d devices in keysDB to delete", len(keysDevices))
-
- for _, device := range keysDevices {
- logrus.Infof("[CLEANUP] Deleting device from keysDB: %s", device.ID)
- if err := currentKeysDB.DeleteDevice(ctx, device); err != nil {
- logrus.Errorf("[CLEANUP] Error deleting device %s from keysDB: %v", device.ID, err)
- return fmt.Errorf("failed to delete device %s from keysDB: %v", device.ID, err)
- }
- }
- }
-
- logrus.Info("[CLEANUP] All devices deleted successfully from PostgreSQL")
- return nil
- }
-
- // SQLite: Hold write lock for entire cleanup to prevent race conditions
- // Other goroutines must not access db/keysDB while we're closing and removing files
- globalStateMu.Lock()
- defer globalStateMu.Unlock()
-
- logrus.Info("[CLEANUP] SQLite detected - closing database connections before file removal")
-
- // Store references and clear globals immediately to prevent use-after-close
- currentDB := db
- currentKeysDB := keysDB
- db = nil
- keysDB = nil
- cli = nil // Also clear client since it depends on db
-
- // Close the main database connection
- if currentDB != nil {
- logrus.Info("[CLEANUP] Closing main database connection")
- if err := currentDB.Close(); err != nil {
- logrus.Errorf("[CLEANUP] Error closing main database: %v", err)
- return fmt.Errorf("failed to close main database: %v", err)
- }
- logrus.Info("[CLEANUP] Main database connection closed successfully")
- }
-
- // Close keysDB if it exists and is separate from main db
- if currentKeysDB != nil && currentKeysDB != currentDB {
- logrus.Info("[CLEANUP] Closing keysDB database connection")
- if err := currentKeysDB.Close(); err != nil {
- logrus.Errorf("[CLEANUP] Error closing keysDB: %v", err)
- return fmt.Errorf("failed to close keysDB: %v", err)
- }
- logrus.Info("[CLEANUP] KeysDB connection closed successfully")
-
- // Remove keysDB file if it's also SQLite
- if config.DBKeysURI != "" && strings.HasPrefix(config.DBKeysURI, "file:") {
- keysDBPath := strings.TrimPrefix(config.DBKeysURI, "file:")
- if strings.Contains(keysDBPath, "?") {
- keysDBPath = strings.Split(keysDBPath, "?")[0]
- }
-
- logrus.Infof("[CLEANUP] Removing keysDB file: %s", keysDBPath)
- if err := os.Remove(keysDBPath); err != nil {
- if !os.IsNotExist(err) {
- logrus.Errorf("[CLEANUP] Error removing keysDB file: %v", err)
- return fmt.Errorf("failed to remove keysDB file: %v", err)
- } else {
- logrus.Info("[CLEANUP] KeysDB file already removed")
- }
- } else {
- logrus.Info("[CLEANUP] KeysDB file removed successfully")
- }
- // Remove WAL and SHM sidecar files
- os.Remove(keysDBPath + "-wal")
- os.Remove(keysDBPath + "-shm")
- }
- }
-
- // Now remove the main database file
- dbPath := strings.TrimPrefix(config.DBURI, "file:")
- if strings.Contains(dbPath, "?") {
- dbPath = strings.Split(dbPath, "?")[0]
- }
-
- logrus.Infof("[CLEANUP] Removing main database file: %s", dbPath)
- if err := os.Remove(dbPath); err != nil {
- if !os.IsNotExist(err) {
- logrus.Errorf("[CLEANUP] Error removing database file: %v", err)
- return err
- } else {
- logrus.Info("[CLEANUP] Database file already removed")
- }
- } else {
- logrus.Info("[CLEANUP] Database file removed successfully")
- }
- // Remove WAL and SHM sidecar files
- os.Remove(dbPath + "-wal")
- os.Remove(dbPath + "-shm")
- return nil
-}
-
-// CleanupTemporaryFiles removes history files, QR images, and send items
-func CleanupTemporaryFiles() error {
- // Clean up history files
- if files, err := filepath.Glob(fmt.Sprintf("./%s/history-*", config.PathStorages)); err == nil {
- for _, f := range files {
- if err := os.Remove(f); err != nil {
- logrus.Errorf("[CLEANUP] Error removing history file %s: %v", f, err)
- return err
- }
- }
- logrus.Info("[CLEANUP] History files cleaned up")
- }
-
- // Clean up QR images
- if qrImages, err := filepath.Glob(fmt.Sprintf("./%s/scan-*", config.PathQrCode)); err == nil {
- for _, f := range qrImages {
- if err := os.Remove(f); err != nil {
- logrus.Errorf("[CLEANUP] Error removing QR image %s: %v", f, err)
- return err
- }
- }
- logrus.Info("[CLEANUP] QR images cleaned up")
- }
-
- // Clean up send items
- if qrItems, err := filepath.Glob(fmt.Sprintf("./%s/*", config.PathSendItems)); err == nil {
- for _, f := range qrItems {
- if !strings.Contains(f, ".gitignore") {
- if err := os.Remove(f); err != nil {
- logrus.Errorf("[CLEANUP] Error removing send item %s: %v", f, err)
- return err
- }
- }
- }
- logrus.Info("[CLEANUP] Send items cleaned up")
- }
-
- return nil
-}
-
-// ReinitializeWhatsAppComponents reinitializes database and client components
-func ReinitializeWhatsAppComponents(ctx context.Context, chatStorageRepo domainChatStorage.IChatStorageRepository) (*sqlstore.Container, *whatsmeow.Client, error) {
- logrus.Info("[CLEANUP] Reinitializing database and client...")
-
- newDB := InitWaDB(ctx, config.DBURI)
- var newKeysDB *sqlstore.Container
- if config.DBKeysURI != "" {
- newKeysDB = InitWaDB(ctx, config.DBKeysURI)
- }
- newCli := InitWaCLI(ctx, newDB, newKeysDB, chatStorageRepo)
-
- logrus.Info("[CLEANUP] Database and client reinitialized successfully")
-
- return newDB, newCli, nil
-}
-
-// PerformCompleteCleanup performs all cleanup operations in the correct order
-func PerformCompleteCleanup(ctx context.Context, logPrefix string, chatStorageRepo domainChatStorage.IChatStorageRepository) (*sqlstore.Container, *whatsmeow.Client, error) {
- logrus.Infof("[%s] Starting complete cleanup process...", logPrefix)
-
- // Disconnect current client if it exists
- if current := GetClient(); current != nil {
- current.Disconnect()
- logrus.Infof("[%s] Client disconnected", logPrefix)
- }
-
- // Truncate all chatstorage data before other cleanup
- if chatStorageRepo != nil {
- logrus.Infof("[%s] Truncating chatstorage data...", logPrefix)
- if err := chatStorageRepo.TruncateAllDataWithLogging(logPrefix); err != nil {
- logrus.Errorf("[%s] Failed to truncate chatstorage data: %v", logPrefix, err)
- // Continue with cleanup even if chatstorage truncation fails
- }
- }
-
- // Clean up database
- if err := CleanupDatabase(); err != nil {
- return nil, nil, fmt.Errorf("database cleanup failed: %v", err)
- }
-
- // Reinitialize components
- newDB, newCli, err := ReinitializeWhatsAppComponents(ctx, chatStorageRepo)
- if err != nil {
- return nil, nil, fmt.Errorf("reinitialization failed: %v", err)
- }
-
- // Clean up temporary files
- if err := CleanupTemporaryFiles(); err != nil {
- logrus.Errorf("[%s] Temporary file cleanup failed (non-critical): %v", logPrefix, err)
- // Don't return error for file cleanup as it's non-critical
- }
-
- logrus.Infof("[%s] Complete cleanup process finished successfully", logPrefix)
- logrus.Infof("[%s] Application is ready for next login without restart", logPrefix)
-
- return newDB, newCli, nil
-}
-
-// PerformCleanupAndUpdateGlobals is a convenience function that performs cleanup
-// and ensures global client synchronization
-func PerformCleanupAndUpdateGlobals(ctx context.Context, logPrefix string, chatStorageRepo domainChatStorage.IChatStorageRepository) (*sqlstore.Container, *whatsmeow.Client, error) {
- newDB, newCli, err := PerformCompleteCleanup(ctx, logPrefix, chatStorageRepo)
- if err != nil {
- return nil, nil, err
- }
-
- // Ensure global client is properly synchronized
- UpdateGlobalClient(newCli, newDB)
-
- return newDB, newCli, nil
-}
diff --git a/src/infrastructure/whatsapp/client_lifecycle.go b/src/infrastructure/whatsapp/client_lifecycle.go
index 2b71d497..fab1e842 100644
--- a/src/infrastructure/whatsapp/client_lifecycle.go
+++ b/src/infrastructure/whatsapp/client_lifecycle.go
@@ -6,17 +6,6 @@ import (
"go.mau.fi/whatsmeow/store/sqlstore"
)
-// UpdateGlobalClient updates the global cli variable with a new client instance
-// This is needed when reinitializing the client after logout to ensure all
-// infrastructure code uses the new client instance
-func UpdateGlobalClient(newCli *whatsmeow.Client, newDB *sqlstore.Container) {
- globalStateMu.Lock()
- cli = newCli
- db = newDB
- globalStateMu.Unlock()
- log.Infof("Global WhatsApp client updated successfully")
-}
-
// GetClient returns the current global client instance (alias for GetGlobalClient)
func GetClient() *whatsmeow.Client {
globalStateMu.RLock()
@@ -24,13 +13,6 @@ func GetClient() *whatsmeow.Client {
return cli
}
-// Get DB instance
-func GetDB() *sqlstore.Container {
- globalStateMu.RLock()
- defer globalStateMu.RUnlock()
- return db
-}
-
func getStoreContainers() (*sqlstore.Container, *sqlstore.Container) {
globalStateMu.RLock()
defer globalStateMu.RUnlock()
diff --git a/src/infrastructure/whatsapp/database.go b/src/infrastructure/whatsapp/database.go
index 33b094ac..0adfb21d 100644
--- a/src/infrastructure/whatsapp/database.go
+++ b/src/infrastructure/whatsapp/database.go
@@ -38,22 +38,3 @@ func initDatabase(ctx context.Context, dbLog waLog.Logger, DBURI string) (*sqlst
return nil, fmt.Errorf("unknown database type: %s. Currently only sqlite3(file:) and postgres are supported", DBURI)
}
-
-// GetConnectionStatus returns the current connection status of the global client
-func GetConnectionStatus() (isConnected bool, isLoggedIn bool, deviceID string) {
- globalStateMu.RLock()
- currentClient := cli
- globalStateMu.RUnlock()
- if currentClient == nil {
- return false, false, ""
- }
-
- isConnected = currentClient.IsConnected()
- isLoggedIn = currentClient.IsLoggedIn()
-
- if currentClient.Store != nil && currentClient.Store.ID != nil {
- deviceID = currentClient.Store.ID.String()
- }
-
- return isConnected, isLoggedIn, deviceID
-}
diff --git a/src/infrastructure/whatsapp/device_manager.go b/src/infrastructure/whatsapp/device_manager.go
index 822e02f8..0e33fbe4 100644
--- a/src/infrastructure/whatsapp/device_manager.go
+++ b/src/infrastructure/whatsapp/device_manager.go
@@ -491,7 +491,7 @@ func (m *DeviceManager) EnsureClient(ctx context.Context, deviceID string) (*Dev
inst.SetChatStorage(repo)
}
- client.AddEventHandler(func(rawEvt interface{}) {
+ client.AddEventHandler(func(rawEvt any) {
handler(ctx, inst, rawEvt)
})
diff --git a/src/infrastructure/whatsapp/event_message.go b/src/infrastructure/whatsapp/event_message.go
index c52fd3e9..105c8226 100644
--- a/src/infrastructure/whatsapp/event_message.go
+++ b/src/infrastructure/whatsapp/event_message.go
@@ -383,7 +383,7 @@ func buildWebhookContactPayload(contact *waE2E.ContactMessage) webhookContactPay
return webhookContactPayload{
DisplayName: contact.GetDisplayName(),
VCard: vcard,
- PhoneNumber: extractPhoneFromVCard(vcard),
+ PhoneNumber: utils.ExtractPhoneFromVCard(vcard),
}
}
diff --git a/src/infrastructure/whatsapp/init.go b/src/infrastructure/whatsapp/init.go
index 60794e85..47cb073c 100644
--- a/src/infrastructure/whatsapp/init.go
+++ b/src/infrastructure/whatsapp/init.go
@@ -110,7 +110,7 @@ func InitWaCLI(ctx context.Context, storeContainer, keysStoreContainer *sqlstore
deviceRepo := newDeviceChatStorage(instanceID, chatStorageRepo)
instance := NewDeviceInstance(instanceID, client, deviceRepo)
- client.AddEventHandler(func(rawEvt interface{}) {
+ client.AddEventHandler(func(rawEvt any) {
handler(ctx, instance, rawEvt)
})
diff --git a/src/infrastructure/whatsapp/logger.go b/src/infrastructure/whatsapp/logger.go
index 1f888d46..db90c630 100644
--- a/src/infrastructure/whatsapp/logger.go
+++ b/src/infrastructure/whatsapp/logger.go
@@ -26,7 +26,7 @@ func newFilteredLogger(base waLog.Logger) waLog.Logger {
return &filteredLogger{base: base}
}
-func (l *filteredLogger) Errorf(msg string, args ...interface{}) {
+func (l *filteredLogger) Errorf(msg string, args ...any) {
formatted := fmt.Sprintf(msg, args...)
if isWebsocketEOFError(formatted) {
l.base.Debugf("WebSocket closed after idle; auto-reconnecting within ~1s without interrupting message handling. Investigate only if reconnection keeps failing: %s", formatted)
@@ -36,15 +36,15 @@ func (l *filteredLogger) Errorf(msg string, args ...interface{}) {
l.base.Errorf(msg, args...)
}
-func (l *filteredLogger) Warnf(msg string, args ...interface{}) {
+func (l *filteredLogger) Warnf(msg string, args ...any) {
l.base.Warnf(msg, args...)
}
-func (l *filteredLogger) Infof(msg string, args ...interface{}) {
+func (l *filteredLogger) Infof(msg string, args ...any) {
l.base.Infof(msg, args...)
}
-func (l *filteredLogger) Debugf(msg string, args ...interface{}) {
+func (l *filteredLogger) Debugf(msg string, args ...any) {
l.base.Debugf(msg, args...)
}
diff --git a/src/infrastructure/whatsapp/webhook_forward.go b/src/infrastructure/whatsapp/webhook_forward.go
index be1c6953..418ab53e 100644
--- a/src/infrastructure/whatsapp/webhook_forward.go
+++ b/src/infrastructure/whatsapp/webhook_forward.go
@@ -140,7 +140,7 @@ type chatwootContactInfo struct {
// extractChatwootContactInfo extracts contact identifier and name from message payload.
// For groups, uses the group JID as identifier and tries to fetch group name.
// For private chats, uses the sender's phone number.
-func extractChatwootContactInfo(ctx context.Context, data map[string]interface{}) (*chatwootContactInfo, error) {
+func extractChatwootContactInfo(ctx context.Context, data map[string]any) (*chatwootContactInfo, error) {
from, _ := data["from"].(string)
fromName, _ := data["from_name"].(string)
chatID, _ := data["chat_id"].(string)
@@ -181,7 +181,7 @@ func extractChatwootContactInfo(ctx context.Context, data map[string]interface{}
// buildChatwootMessageContent extracts message body and attachments from the payload.
// For group messages, prepends the sender name to the content.
-func buildChatwootMessageContent(data map[string]interface{}, isGroup bool, fromName string) (content string, attachments []string) {
+func buildChatwootMessageContent(data map[string]any, isGroup bool, fromName string) (content string, attachments []string) {
if body, ok := data["body"].(string); ok && body != "" {
content = body
}
@@ -239,7 +239,7 @@ func isEventWhitelistedForChatwoot(eventName string) bool {
return eventName == "message.reaction" && isEventWhitelisted("message")
}
-func buildReactionChatwootContent(data map[string]interface{}, isGroup bool, fromName string) string {
+func buildReactionChatwootContent(data map[string]any, isGroup bool, fromName string) string {
reaction, _ := data["reaction"].(string)
reactedMessageID, _ := data["reacted_message_id"].(string)
@@ -263,24 +263,17 @@ func buildReactionChatwootContent(data map[string]interface{}, isGroup bool, fro
return fmt.Sprintf("%s reacted %s", actor, reaction)
}
-func chatwootMessageTypeFromPayload(data map[string]interface{}) string {
+func chatwootMessageTypeFromPayload(data map[string]any) string {
if isFromMe, ok := data["is_from_me"].(bool); ok && isFromMe {
return "outgoing"
}
return "incoming"
}
-func extractStructuredMessageContent(data map[string]interface{}) string {
+func extractStructuredMessageContent(data map[string]any) string {
if contact, ok := data["contact"]; ok && contact != nil {
if name, phone, ok := extractContactDetails(contact); ok {
- switch {
- case name != "" && phone != "":
- return fmt.Sprintf("Contact: %s (%s)", name, phone)
- case name != "":
- return "Contact: " + name
- case phone != "":
- return "Contact: " + phone
- }
+ return utils.FormatContactSummary(name, phone, false)
}
return "Contact shared"
}
@@ -297,19 +290,12 @@ func extractStructuredMessageContent(data map[string]interface{}) string {
}
}
return structuredContactsArraySummary(normalized)
- case []interface{}:
+ case []any:
if len(contacts) == 0 {
return "Contacts shared"
}
if name, phone, ok := extractContactDetails(contacts[0]); ok {
- switch {
- case name != "" && phone != "":
- return fmt.Sprintf("Contacts: %s (%s)", name, phone)
- case name != "":
- return "Contacts: " + name
- case phone != "":
- return "Contacts: " + phone
- }
+ return utils.FormatContactSummary(name, phone, true)
}
return "Contacts shared"
default:
@@ -365,7 +351,7 @@ func extractStructuredMessageContent(data map[string]interface{}) string {
return ""
}
-func extractContactDetails(contact interface{}) (name string, phone string, ok bool) {
+func extractContactDetails(contact any) (name string, phone string, ok bool) {
switch c := contact.(type) {
case webhookContactPayload:
return c.DisplayName, c.PhoneNumber, true
@@ -385,7 +371,7 @@ func extractContactDetails(contact interface{}) (name string, phone string, ok b
}
if phone == "" {
if v, ok := c["vcard"].(string); ok {
- phone = extractPhoneFromVCard(v)
+ phone = utils.ExtractPhoneFromVCard(v)
}
}
return name, phone, name != "" || phone != ""
@@ -394,7 +380,7 @@ func extractContactDetails(contact interface{}) (name string, phone string, ok b
GetVcard() string
}:
name = c.GetDisplayName()
- phone = extractPhoneFromVCard(c.GetVcard())
+ phone = utils.ExtractPhoneFromVCard(c.GetVcard())
return name, phone, true
default:
return "", "", false
@@ -405,30 +391,8 @@ func structuredContactsArraySummary(contacts []webhookContactPayload) string {
if len(contacts) == 0 {
return "Contacts shared"
}
-
first := contacts[0]
- switch {
- case first.DisplayName != "" && first.PhoneNumber != "":
- return fmt.Sprintf("Contacts: %s (%s)", first.DisplayName, first.PhoneNumber)
- case first.DisplayName != "":
- return "Contacts: " + first.DisplayName
- case first.PhoneNumber != "":
- return "Contacts: " + first.PhoneNumber
- default:
- return "Contacts shared"
- }
-}
-
-func extractPhoneFromVCard(vcard string) string {
- for _, line := range strings.Split(vcard, "\n") {
- line = strings.TrimSpace(line)
- if strings.HasPrefix(strings.ToUpper(line), "TEL") {
- if idx := strings.LastIndex(line, ":"); idx >= 0 {
- return strings.TrimSpace(line[idx+1:])
- }
- }
- }
- return ""
+ return utils.FormatContactSummary(first.DisplayName, first.PhoneNumber, true)
}
// syncMessageToChatwoot creates or finds contact/conversation and sends the message.
@@ -474,7 +438,7 @@ func forwardToChatwoot(ctx context.Context, payload map[string]any, eventName st
return
}
- data, ok := payload["payload"].(map[string]interface{})
+ data, ok := payload["payload"].(map[string]any)
if !ok {
logrus.Error("Chatwoot: Invalid payload format (missing 'payload' object)")
return
diff --git a/src/pkg/error/app_error.go b/src/pkg/error/app_error.go
index 5d4c26dd..97d89cb1 100644
--- a/src/pkg/error/app_error.go
+++ b/src/pkg/error/app_error.go
@@ -19,33 +19,8 @@ func (e LoginError) StatusCode() int {
return http.StatusBadRequest
}
-type ReconnectError string
-
-func throwReconnectError(text string) GenericError {
- return AuthError(text)
-}
-
-// Error for complying the error interface
-func (e ReconnectError) Error() string {
- return string(e)
-}
-
-// ErrCode will return the error code based on the error data type
-func (e ReconnectError) ErrCode() string {
- return "RECONNECT_ERROR"
-}
-
-// StatusCode will return the HTTP status code based on the error data type
-func (e ReconnectError) StatusCode() int {
- return http.StatusBadRequest
-}
-
type AuthError string
-func throwAuthError(text string) GenericError {
- return AuthError(text)
-}
-
func (err AuthError) Error() string {
return string(err)
}
@@ -62,10 +37,6 @@ func (err AuthError) StatusCode() int {
type qrChannelError string
-func throwQrChannelError(text string) GenericError {
- return qrChannelError(text)
-}
-
func (err qrChannelError) Error() string {
return string(err)
}
@@ -82,10 +53,6 @@ func (err qrChannelError) StatusCode() int {
type sessionSavedError string
-func throwSessionSavedError(text string) GenericError {
- return sessionSavedError(text)
-}
-
func (err sessionSavedError) Error() string {
return string(err)
}
@@ -102,9 +69,9 @@ func (err sessionSavedError) StatusCode() int {
var (
ErrAlreadyLoggedIn = LoginError("you are already logged in.")
- ErrNotConnected = throwAuthError("you are not connect to services server, please reconnect")
- ErrNotLoggedIn = throwAuthError("you are not logged in")
- ErrReconnect = throwReconnectError("reconnect error")
- ErrQrChannel = throwQrChannelError("QR channel error")
- ErrSessionSaved = throwSessionSavedError("your session have been saved, please wait to connect 2 second and refresh again")
+ ErrNotConnected = AuthError("you are not connect to services server, please reconnect")
+ ErrNotLoggedIn = AuthError("you are not logged in")
+ ErrReconnect = AuthError("reconnect error")
+ ErrQrChannel = qrChannelError("QR channel error")
+ ErrSessionSaved = sessionSavedError("your session have been saved, please wait to connect 2 second and refresh again")
)
diff --git a/src/pkg/error/generic_error.go b/src/pkg/error/generic_error.go
index 0573d83b..46658400 100644
--- a/src/pkg/error/generic_error.go
+++ b/src/pkg/error/generic_error.go
@@ -42,28 +42,3 @@ func (e ContextError) ErrCode() string {
func (e ContextError) StatusCode() int {
return http.StatusRequestTimeout
}
-
-// TimeoutError represents a request timeout error
-type TimeoutError string
-
-func (e TimeoutError) Error() string {
- return string(e)
-}
-
-func (e TimeoutError) ErrCode() string {
- return "REQUEST_TIMEOUT"
-}
-
-func (e TimeoutError) StatusCode() int {
- return http.StatusGatewayTimeout // 504
-}
-
-// RequestTimeout creates a timeout error with a custom message
-func RequestTimeout(text string) GenericError {
- return TimeoutError(text)
-}
-
-var (
- ErrInternalServerError = InternalServerError("internal server error")
- ErrRequestTimeout = TimeoutError("request timed out waiting for WhatsApp server response")
-)
diff --git a/src/pkg/utils/environment.go b/src/pkg/utils/environment.go
index 601ba89a..03fb8dc1 100644
--- a/src/pkg/utils/environment.go
+++ b/src/pkg/utils/environment.go
@@ -1,86 +1,10 @@
package utils
-import (
- "context"
- "fmt"
- "strconv"
- "time"
+import "github.com/spf13/viper"
- "github.com/sirupsen/logrus"
- "github.com/spf13/viper"
-)
-
-// IsLocal will return true if the APP_ENV is not listed in those three condition
-func IsLocal() bool {
- envLevel := MustHaveEnv("APP_ENV")
- return envLevel != "production" && envLevel != "staging" && envLevel != "integration"
-}
-
-func Env[T any](key string, defValue ...T) T {
- if env := viper.Get(key); env != nil {
- // Ensure type safety for retrieved environment variables
- if value, ok := env.(T); ok {
- return value
- }
- }
-
- if len(defValue) > 0 {
- return defValue[0]
- }
-
- var zero T
- return zero
-}
-
-// MustHaveEnv ensure the ENV is exists, otherwise will crashing the app
-func MustHaveEnv(key string) string {
- env := viper.GetString(key)
- if env == "" {
- logrus.Warn(context.Background(), map[string]any{
- "field": key,
- }, "variable is not well set, reading from .env file")
- viper.SetConfigFile(".env")
- viper.SetConfigType("env")
- err := viper.ReadInConfig()
- if err != nil {
- logrus.Fatal(err, "can't read .env file")
- }
- env = viper.GetString(key)
- }
- if env == "" {
- logrus.Fatal(fmt.Sprintf("%s is not well set", key))
- }
- return env
-}
-
-// MustHaveEnvBool ensure the ENV exists and returns a bool, otherwise it will crash the app
-func MustHaveEnvBool(key string) bool {
- env := MustHaveEnv(key)
- return env == "true"
-}
-
-// MustHaveEnvInt ensure the ENV is exists and return int value
-func MustHaveEnvInt(key string) int {
- env := MustHaveEnv(key)
- number, err := strconv.ParseInt(env, 10, 64)
- if err != nil {
- logrus.Fatal(fmt.Sprintf("%s is not well set", key))
- }
- return int(number)
-}
-
-// MustHaveEnvMinuteDuration ensure the ENV is exists and return a minute duration
-func MustHaveEnvMinuteDuration(key string) time.Duration {
- env := MustHaveEnv(key)
- number, err := strconv.ParseInt(env, 10, 64)
- if err != nil {
- logrus.Fatal(fmt.Sprintf("%s is not well set", key))
- }
-
- return time.Duration(number) * time.Minute
-}
-
-func LoadConfig(path string, name ...string) (err error) {
+// LoadConfig reads configuration from a .env-style file in the given path.
+// If a custom name is supplied, it is used as the config name; otherwise ".env" is used.
+func LoadConfig(path string, name ...string) error {
viper.AddConfigPath(path)
if len(name) > 0 && name[0] != "" {
viper.SetConfigName(name[0])
@@ -91,9 +15,5 @@ func LoadConfig(path string, name ...string) (err error) {
viper.SetConfigType("env")
viper.AutomaticEnv()
- err = viper.ReadInConfig()
- if err != nil {
- return
- }
- return nil
+ return viper.ReadInConfig()
}
diff --git a/src/pkg/utils/environment_test.go b/src/pkg/utils/environment_test.go
index 1648bc97..7f5c62fa 100644
--- a/src/pkg/utils/environment_test.go
+++ b/src/pkg/utils/environment_test.go
@@ -3,193 +3,40 @@ package utils_test
import (
"os"
"testing"
- "time"
"github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
"github.com/spf13/viper"
"github.com/stretchr/testify/assert"
- "github.com/stretchr/testify/suite"
)
-type EnvironmentTestSuite struct {
- suite.Suite
-}
-
-func (suite *EnvironmentTestSuite) SetupTest() {
- // Clear any existing viper configs
- viper.Reset()
- // Set up automatic environment variable reading
- viper.AutomaticEnv()
-}
-
-func (suite *EnvironmentTestSuite) TearDownTest() {
- viper.Reset()
-}
-
-func (suite *EnvironmentTestSuite) TestIsLocal() {
- tests := []struct {
- name string
- envValue string
- expected bool
- }{
- {"Production environment", "production", false},
- {"Staging environment", "staging", false},
- {"Integration environment", "integration", false},
- {"Development environment", "development", true},
- {"Local environment", "local", true},
- }
-
- for _, tt := range tests {
- suite.T().Run(tt.name, func(t *testing.T) {
- // Set the environment value
- if tt.envValue != "" {
- viper.Set("APP_ENV", tt.envValue)
- } else {
- viper.Set("APP_ENV", nil) // Explicitly clear the value
- }
-
- result := utils.IsLocal()
- assert.Equal(t, tt.expected, result)
- })
- }
-}
-
-func (suite *EnvironmentTestSuite) TestEnv() {
- // Test with existing value
- viper.Set("TEST_KEY", "test_value")
- result := utils.Env[string]("TEST_KEY")
- assert.Equal(suite.T(), "test_value", result)
-
- // Test with default value
- result = utils.Env("NON_EXISTENT_KEY", "default_value")
- assert.Equal(suite.T(), "default_value", result)
-
- // Test with integer
- viper.Set("TEST_INT", 42)
- intResult := utils.Env[int]("TEST_INT")
- assert.Equal(suite.T(), 42, intResult)
-
- // Test with default integer
- intResult = utils.Env("NON_EXISTENT_INT", 100)
- assert.Equal(suite.T(), 100, intResult)
-
- // Test with boolean
- viper.Set("TEST_BOOL", true)
- boolResult := utils.Env[bool]("TEST_BOOL")
- assert.Equal(suite.T(), true, boolResult)
-
- // Test missing key without default returns zero value
- var zeroInt int
- zeroVal := utils.Env[int]("MISSING_INT")
- assert.Equal(suite.T(), zeroInt, zeroVal)
-
- // Test type mismatch returns provided default value
- viper.Set("STRING_VALUE", "abc")
- defaultInt := utils.Env[int]("STRING_VALUE", 10)
- assert.Equal(suite.T(), 10, defaultInt)
-}
-
-func (suite *EnvironmentTestSuite) TestMustHaveEnv() {
- // Test with value present
- viper.Set("REQUIRED_ENV", "required_value")
- result := utils.MustHaveEnv("REQUIRED_ENV")
- assert.Equal(suite.T(), "required_value", result)
+func TestLoadConfig(t *testing.T) {
+ t.Run("default name", func(t *testing.T) {
+ viper.Reset()
+ tempDir := t.TempDir()
+ require := assert.New(t)
- // Create a temporary .env file for testing
- tempEnvContent := []byte("ENV_FROM_FILE=env_file_value\n")
- err := os.WriteFile(".env", tempEnvContent, 0644)
- assert.NoError(suite.T(), err)
- defer os.Remove(".env")
+ require.NoError(os.WriteFile(tempDir+"/.env", []byte("TEST_CONFIG=config_value\n"), 0644))
- // Test reading from .env file
- result = utils.MustHaveEnv("ENV_FROM_FILE")
- assert.Equal(suite.T(), "env_file_value", result)
+ err := utils.LoadConfig(tempDir)
+ require.NoError(err)
+ require.Equal("config_value", viper.GetString("TEST_CONFIG"))
+ })
- // We can't easily test the fatal log scenario in a unit test
- // as it would terminate the program
-}
-
-func (suite *EnvironmentTestSuite) TestMustHaveEnvBool() {
- // Test true value
- viper.Set("BOOL_TRUE", "true")
- result := utils.MustHaveEnvBool("BOOL_TRUE")
- assert.True(suite.T(), result)
-
- // Test false value
- viper.Set("BOOL_FALSE", "false")
- result = utils.MustHaveEnvBool("BOOL_FALSE")
- assert.False(suite.T(), result)
-}
-
-func (suite *EnvironmentTestSuite) TestMustHaveEnvInt() {
- // Test valid integer
- viper.Set("INT_VALUE", "42")
- result := utils.MustHaveEnvInt("INT_VALUE")
- assert.Equal(suite.T(), 42, result)
-
- // Test zero
- viper.Set("ZERO_INT", "0")
- result = utils.MustHaveEnvInt("ZERO_INT")
- assert.Equal(suite.T(), 0, result)
-
- // Test negative number
- viper.Set("NEG_INT", "-10")
- result = utils.MustHaveEnvInt("NEG_INT")
- assert.Equal(suite.T(), -10, result)
-
- // We can't easily test the fatal log scenario with invalid int
- // as it would terminate the program
-}
+ t.Run("custom name", func(t *testing.T) {
+ viper.Reset()
+ tempDir := t.TempDir()
+ require := assert.New(t)
-func (suite *EnvironmentTestSuite) TestMustHaveEnvMinuteDuration() {
- // Test valid duration
- viper.Set("DURATION_MIN", "5")
- result := utils.MustHaveEnvMinuteDuration("DURATION_MIN")
- assert.Equal(suite.T(), 5*time.Minute, result)
+ require.NoError(os.WriteFile(tempDir+"/custom.env", []byte("CUSTOM_CONFIG=custom_value\n"), 0644))
- // Test zero duration
- viper.Set("ZERO_DURATION", "0")
- result = utils.MustHaveEnvMinuteDuration("ZERO_DURATION")
- assert.Equal(suite.T(), 0*time.Minute, result)
-
- // We can't easily test the fatal log scenario with invalid duration
- // as it would terminate the program
-}
-
-func (suite *EnvironmentTestSuite) TestLoadConfig() {
- // Create a temporary config file for testing
- tempDir, err := os.MkdirTemp("", "config_test")
- assert.NoError(suite.T(), err)
- defer os.RemoveAll(tempDir)
-
- // Create test config file
- configContent := []byte("TEST_CONFIG=config_value\n")
- configPath := tempDir + "/.env"
- err = os.WriteFile(configPath, configContent, 0644)
- assert.NoError(suite.T(), err)
-
- // Test loading config with default name
- err = utils.LoadConfig(tempDir)
- assert.NoError(suite.T(), err)
- assert.Equal(suite.T(), "config_value", viper.GetString("TEST_CONFIG"))
-
- // Test loading config with custom name
- customConfigContent := []byte("CUSTOM_CONFIG=custom_value\n")
- customConfigPath := tempDir + "/custom.env"
- err = os.WriteFile(customConfigPath, customConfigContent, 0644)
- assert.NoError(suite.T(), err)
-
- viper.Reset()
- err = utils.LoadConfig(tempDir, "custom")
- assert.NoError(suite.T(), err)
- assert.Equal(suite.T(), "custom_value", viper.GetString("CUSTOM_CONFIG"))
-
- // Test error case - non-existent directory
- viper.Reset()
- err = utils.LoadConfig("/non/existent/directory")
- assert.Error(suite.T(), err)
-}
+ err := utils.LoadConfig(tempDir, "custom")
+ require.NoError(err)
+ require.Equal("custom_value", viper.GetString("CUSTOM_CONFIG"))
+ })
-func TestEnvironmentTestSuite(t *testing.T) {
- suite.Run(t, new(EnvironmentTestSuite))
+ t.Run("non-existent directory returns error", func(t *testing.T) {
+ viper.Reset()
+ err := utils.LoadConfig("/non/existent/directory")
+ assert.Error(t, err)
+ })
}
diff --git a/src/pkg/utils/phone.go b/src/pkg/utils/phone.go
index 7c07ce64..93032ffd 100644
--- a/src/pkg/utils/phone.go
+++ b/src/pkg/utils/phone.go
@@ -17,11 +17,6 @@ func NormalizePhoneE164(phone string) string {
return phone
}
-// StripPhonePrefix removes + prefix from phone number.
-func StripPhonePrefix(phone string) string {
- return strings.TrimPrefix(strings.TrimSpace(phone), "+")
-}
-
// ExtractPhoneFromJID extracts phone number from JID by stripping the domain part.
// For example, "[email protected]" becomes "1234567890".
func ExtractPhoneFromJID(jid string) string {
diff --git a/src/pkg/utils/whatsapp.go b/src/pkg/utils/whatsapp.go
index c1e8e4d5..fb8c60ac 100644
--- a/src/pkg/utils/whatsapp.go
+++ b/src/pkg/utils/whatsapp.go
@@ -56,7 +56,9 @@ func resolveKnownDocumentExtension(mimeType string) (string, bool) {
return ext, ok
}
-func extractPhoneFromVCard(vcard string) string {
+// ExtractPhoneFromVCard returns the first phone number found in a vCard's TEL field.
+// Splits on "\n" β€” TrimSpace handles the trailing "\r" from CRLF-terminated vCards.
+func ExtractPhoneFromVCard(vcard string) string {
for _, line := range strings.Split(vcard, "\n") {
line = strings.TrimSpace(line)
if strings.HasPrefix(strings.ToUpper(line), "TEL") {
@@ -68,16 +70,30 @@ func extractPhoneFromVCard(vcard string) string {
return ""
}
+// FormatContactSummary builds a one-liner for a shared contact card.
+// Pass plural=true for ContactsArrayMessage to use the "Contacts" prefix.
+func FormatContactSummary(name, phone string, plural bool) string {
+ prefix := "Contact"
+ if plural {
+ prefix = "Contacts"
+ }
+ switch {
+ case name != "" && phone != "":
+ return fmt.Sprintf("%s: %s (%s)", prefix, name, phone)
+ case name != "":
+ return prefix + ": " + name
+ case phone != "":
+ return prefix + ": " + phone
+ default:
+ return prefix + " shared"
+ }
+}
+
// KnownDocumentMIMEByExtension returns a known MIME type for a given Office document extension.
func KnownDocumentMIMEByExtension(ext string) (string, bool) {
return resolveKnownDocumentMIME(ext)
}
-// KnownDocumentExtensionByMIME returns a known Office document extension for a given MIME type.
-func KnownDocumentExtensionByMIME(mimeType string) (string, bool) {
- return resolveKnownDocumentExtension(mimeType)
-}
-
func determineMediaExtension(originalFilename, mimeType string) string {
if originalFilename != "" {
if ext := filepath.Ext(originalFilename); ext != "" {
@@ -152,37 +168,14 @@ func ExtractMessageTextFromProto(msg *waE2E.Message) string {
// Check for shared contact card
if contact := msg.GetContactMessage(); contact != nil {
- name := contact.GetDisplayName()
- phone := extractPhoneFromVCard(contact.GetVcard())
- switch {
- case name != "" && phone != "":
- return fmt.Sprintf("Contact: %s (%s)", name, phone)
- case name != "":
- return "Contact: " + name
- case phone != "":
- return "Contact: " + phone
- default:
- return "Contact shared"
- }
+ return FormatContactSummary(contact.GetDisplayName(), ExtractPhoneFromVCard(contact.GetVcard()), false)
}
// Check for shared multiple contact cards
if contactsArray := msg.GetContactsArrayMessage(); contactsArray != nil {
- contacts := contactsArray.GetContacts()
- if len(contacts) > 0 {
+ if contacts := contactsArray.GetContacts(); len(contacts) > 0 && contacts[0] != nil {
first := contacts[0]
- if first != nil {
- name := first.GetDisplayName()
- phone := extractPhoneFromVCard(first.GetVcard())
- switch {
- case name != "" && phone != "":
- return fmt.Sprintf("Contacts: %s (%s)", name, phone)
- case name != "":
- return "Contacts: " + name
- case phone != "":
- return "Contacts: " + phone
- }
- }
+ return FormatContactSummary(first.GetDisplayName(), ExtractPhoneFromVCard(first.GetVcard()), true)
}
return "Contacts shared"
}
@@ -210,93 +203,6 @@ func ExtractMediaCaption(msg *waE2E.Message) string {
return ""
}
-// ExtractMessageTextFromEvent extracts text content from a WhatsApp event message with emojis
-func ExtractMessageTextFromEvent(evt *events.Message) string {
- messageText := evt.Message.GetConversation()
- if extendedText := evt.Message.GetExtendedTextMessage(); extendedText != nil {
- messageText = extendedText.GetText()
- } else if protocolMessage := evt.Message.GetProtocolMessage(); protocolMessage != nil {
- if editedMessage := protocolMessage.GetEditedMessage(); editedMessage != nil {
- if extendedText := editedMessage.GetExtendedTextMessage(); extendedText != nil {
- messageText = extendedText.GetText()
- }
- }
- } else if imageMessage := evt.Message.GetImageMessage(); imageMessage != nil {
- messageText = imageMessage.GetCaption()
- if messageText == "" {
- messageText = "πŸ–ΌοΈ Image"
- }
- } else if documentMessage := evt.Message.GetDocumentMessage(); documentMessage != nil {
- messageText = documentMessage.GetCaption()
- if messageText == "" {
- fileName := strings.TrimSpace(documentMessage.GetFileName())
- if fileName != "" {
- messageText = "πŸ“„ " + fileName
- } else {
- messageText = "πŸ“„ Document"
- }
- }
- } else if videoMessage := evt.Message.GetVideoMessage(); videoMessage != nil {
- messageText = videoMessage.GetCaption()
- if messageText == "" {
- messageText = "πŸŽ₯ Video"
- }
- } else if liveLocationMessage := evt.Message.GetLiveLocationMessage(); liveLocationMessage != nil {
- messageText = liveLocationMessage.GetCaption()
- if messageText == "" {
- messageText = "πŸ“ Live Location"
- }
- } else if locationMessage := evt.Message.GetLocationMessage(); locationMessage != nil {
- messageText = locationMessage.GetName()
- if messageText == "" {
- messageText = "πŸ“ Location"
- }
- } else if contactMessage := evt.Message.GetContactMessage(); contactMessage != nil {
- messageText = contactMessage.GetDisplayName()
- if messageText == "" {
- messageText = "πŸ‘€ Contact"
- }
- } else if listMessage := evt.Message.GetListMessage(); listMessage != nil {
- messageText = listMessage.GetTitle()
- if messageText == "" {
- messageText = "πŸ“ List"
- }
- } else if orderMessage := evt.Message.GetOrderMessage(); orderMessage != nil {
- messageText = orderMessage.GetOrderTitle()
- if messageText == "" {
- messageText = "πŸ›οΈ Order"
- }
- } else if paymentMessage := evt.Message.GetPaymentInviteMessage(); paymentMessage != nil {
- messageText = paymentMessage.GetServiceType().String()
- if messageText == "" {
- messageText = "πŸ’³ Payment"
- }
- } else if audioMessage := evt.Message.GetAudioMessage(); audioMessage != nil {
- messageText = "🎧 Audio"
- if audioMessage.GetPTT() {
- messageText = "🎀 Voice Message"
- }
- } else if pollMessageV3 := evt.Message.GetPollCreationMessageV3(); pollMessageV3 != nil {
- messageText = pollMessageV3.GetName()
- if messageText == "" {
- messageText = "πŸ“Š Poll"
- }
- } else if pollMessageV4 := evt.Message.GetPollCreationMessageV4(); pollMessageV4 != nil {
- if pollMessage := pollMessageV4.GetMessage(); pollMessage != nil {
- messageText = pollMessage.GetConversation()
- }
- if messageText == "" {
- messageText = "πŸ“Š Poll"
- }
- } else if pollMessageV5 := evt.Message.GetPollCreationMessageV5(); pollMessageV5 != nil {
- messageText = pollMessageV5.GetName()
- if messageText == "" {
- messageText = "πŸ“Š Poll"
- }
- }
- return messageText
-}
-
// ExtractMediaInfo extracts media information from a WhatsApp message
func ExtractMediaInfo(msg *waE2E.Message) (mediaType string, filename string, url string, mediaKey []byte, fileSHA256 []byte, fileEncSHA256 []byte, fileLength uint64) {
if msg == nil {
@@ -739,11 +645,6 @@ type EvtMessage struct {
QuotedMessage string `json:"quoted_message"`
}
-type EvtReaction struct {
- Message string `json:"message"`
- ID string `json:"id"`
-}
-
// GetMessageDigestOrSignature generates HMAC signature for message
func GetMessageDigestOrSignature(msg, key []byte) (string, error) {
mac := hmac.New(sha256.New, key)
@@ -815,15 +716,6 @@ func BuildEventMessage(evt *events.Message) (message EvtMessage) {
return message
}
-func BuildEventReaction(evt *events.Message) (waReaction EvtReaction) {
- msg := UnwrapMessage(evt.Message)
- if reactionMessage := msg.GetReactionMessage(); reactionMessage != nil {
- waReaction.Message = reactionMessage.GetText()
- waReaction.ID = reactionMessage.GetKey().GetID()
- }
- return waReaction
-}
-
func BuildForwarded(evt *events.Message) bool {
msg := UnwrapMessage(evt.Message)
if ci := ExtractContextInfo(msg); ci != nil {
diff --git a/src/pkg/utils/whatsapp_test.go b/src/pkg/utils/whatsapp_test.go
index 9ece804e..77c66eee 100644
--- a/src/pkg/utils/whatsapp_test.go
+++ b/src/pkg/utils/whatsapp_test.go
@@ -62,11 +62,66 @@ func TestDetermineMediaExtension(t *testing.T) {
}
func TestExtractPhoneFromVCard(t *testing.T) {
- vcard := "BEGIN:VCARD\nVERSION:3.0\nN:;Alice;;;\nFN:Alice\nTEL;type=Mobile:+62 812 3456 7890\nEND:VCARD"
+ tests := []struct {
+ name string
+ vcard string
+ want string
+ }{
+ {
+ name: "LFEndings",
+ vcard: "BEGIN:VCARD\nVERSION:3.0\nFN:Alice\nTEL;type=Mobile:+62 812 3456 7890\nEND:VCARD",
+ want: "+62 812 3456 7890",
+ },
+ {
+ name: "CRLFEndings",
+ vcard: "BEGIN:VCARD\r\nVERSION:3.0\r\nFN:Bob\r\nTEL:+1 555 0100\r\nEND:VCARD",
+ want: "+1 555 0100",
+ },
+ {
+ name: "NoTelLine",
+ vcard: "BEGIN:VCARD\nVERSION:3.0\nFN:Carol\nEND:VCARD",
+ want: "",
+ },
+ {
+ name: "Empty",
+ vcard: "",
+ want: "",
+ },
+ }
- got := extractPhoneFromVCard(vcard)
- if got != "+62 812 3456 7890" {
- t.Fatalf("extractPhoneFromVCard() = %q, want %q", got, "+62 812 3456 7890")
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got := ExtractPhoneFromVCard(tt.vcard)
+ if got != tt.want {
+ t.Fatalf("ExtractPhoneFromVCard() = %q, want %q", got, tt.want)
+ }
+ })
+ }
+}
+
+func TestFormatContactSummary(t *testing.T) {
+ tests := []struct {
+ name string
+ dName string
+ phone string
+ plural bool
+ want string
+ }{
+ {name: "SingleNameAndPhone", dName: "Alice", phone: "+62 812", plural: false, want: "Contact: Alice (+62 812)"},
+ {name: "SingleNameOnly", dName: "Alice", phone: "", plural: false, want: "Contact: Alice"},
+ {name: "SinglePhoneOnly", dName: "", phone: "+62 812", plural: false, want: "Contact: +62 812"},
+ {name: "SingleEmpty", dName: "", phone: "", plural: false, want: "Contact shared"},
+ {name: "PluralNameAndPhone", dName: "Alice", phone: "+62 812", plural: true, want: "Contacts: Alice (+62 812)"},
+ {name: "PluralEmpty", dName: "", phone: "", plural: true, want: "Contacts shared"},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got := FormatContactSummary(tt.dName, tt.phone, tt.plural)
+ if got != tt.want {
+ t.Fatalf("FormatContactSummary() = %q, want %q", got, tt.want)
+ }
+ })
}
}
@@ -86,3 +141,54 @@ func TestExtractMessageTextFromProtoContactMessage(t *testing.T) {
t.Fatalf("ExtractMessageTextFromProto() = %q, want %q", got, want)
}
}
+
+func TestExtractMessageTextFromProtoContactsArrayMessage(t *testing.T) {
+ bob := "Bob"
+ bobVcard := "BEGIN:VCARD\nVERSION:3.0\nFN:Bob\nTEL:+1 555 0100\nEND:VCARD"
+ carol := "Carol"
+ carolVcard := "BEGIN:VCARD\nVERSION:3.0\nFN:Carol\nTEL:+1 555 0200\nEND:VCARD"
+
+ tests := []struct {
+ name string
+ msg *waE2E.Message
+ want string
+ }{
+ {
+ name: "FirstContactWithNameAndPhone",
+ msg: &waE2E.Message{
+ ContactsArrayMessage: &waE2E.ContactsArrayMessage{
+ Contacts: []*waE2E.ContactMessage{
+ {DisplayName: &bob, Vcard: &bobVcard},
+ {DisplayName: &carol, Vcard: &carolVcard},
+ },
+ },
+ },
+ want: "Contacts: Bob (+1 555 0100)",
+ },
+ {
+ name: "EmptyContactsArray",
+ msg: &waE2E.Message{
+ ContactsArrayMessage: &waE2E.ContactsArrayMessage{Contacts: nil},
+ },
+ want: "Contacts shared",
+ },
+ {
+ name: "FirstContactEmpty",
+ msg: &waE2E.Message{
+ ContactsArrayMessage: &waE2E.ContactsArrayMessage{
+ Contacts: []*waE2E.ContactMessage{{}},
+ },
+ },
+ want: "Contacts shared",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got := ExtractMessageTextFromProto(tt.msg)
+ if got != tt.want {
+ t.Fatalf("ExtractMessageTextFromProto() = %q, want %q", got, tt.want)
+ }
+ })
+ }
+}
diff --git a/src/ui/mcp/send.go b/src/ui/mcp/send.go
index 3f2fcab7..bcd9fbf1 100644
--- a/src/ui/mcp/send.go
+++ b/src/ui/mcp/send.go
@@ -83,7 +83,7 @@ func (s *SendHandler) handleSendText(ctx context.Context, request mcp.CallToolRe
// Parse mentions array (ghost mentions)
var mentions []string
- if mentionsRaw, ok := request.GetArguments()["mentions"].([]interface{}); ok {
+ if mentionsRaw, ok := request.GetArguments()["mentions"].([]any); ok {
for _, m := range mentionsRaw {
if mentionStr, ok := m.(string); ok {
mentions = append(mentions, mentionStr)
diff --git a/src/ui/rest/chatwoot.go b/src/ui/rest/chatwoot.go
index 4ca42705..35cbda7c 100644
--- a/src/ui/rest/chatwoot.go
+++ b/src/ui/rest/chatwoot.go
@@ -269,7 +269,7 @@ func (h *ChatwootHandler) SyncHistory(c *fiber.Ctx) error {
Status: fiber.StatusConflict,
Code: "SYNC_ALREADY_RUNNING",
Message: "A sync is already in progress for this device",
- Results: map[string]interface{}{
+ Results: map[string]any{
"progress": progress,
},
})
@@ -297,7 +297,7 @@ func (h *ChatwootHandler) SyncHistory(c *fiber.Ctx) error {
Status: 200,
Code: "SYNC_STARTED",
Message: "History sync initiated in background",
- Results: map[string]interface{}{
+ Results: map[string]any{
"device_id": resolvedID,
"days_limit": opts.DaysLimit,
"include_media": opts.IncludeMedia,
@@ -331,7 +331,7 @@ func (h *ChatwootHandler) SyncStatus(c *fiber.Ctx) error {
Status: 200,
Code: "SUCCESS",
Message: "No sync has been initiated yet",
- Results: map[string]interface{}{
+ Results: map[string]any{
"device_id": resolvedID,
"status": "idle",
},
@@ -344,7 +344,7 @@ func (h *ChatwootHandler) SyncStatus(c *fiber.Ctx) error {
Status: 200,
Code: "SUCCESS",
Message: "No sync progress found for this device",
- Results: map[string]interface{}{
+ Results: map[string]any{
"device_id": resolvedID,
"status": "idle",
},
diff --git a/src/usecase/message.go b/src/usecase/message.go
index cabbc854..26e908bc 100644
--- a/src/usecase/message.go
+++ b/src/usecase/message.go
@@ -306,7 +306,7 @@ func (service serviceMessage) DownloadMedia(ctx context.Context, request domainM
}
// Create a downloadable message interface based on media type
- var downloadableMsg interface{}
+ var downloadableMsg any
switch message.MediaType {
case "image":
diff --git a/src/validations/chat_validation.go b/src/validations/chat_validation.go
index e097c437..b2a4133b 100644
--- a/src/validations/chat_validation.go
+++ b/src/validations/chat_validation.go
@@ -78,7 +78,7 @@ func ValidateSetDisappearingTimer(ctx context.Context, request *domainChat.SetDi
return nil
}
-func validateTimerValue(value interface{}) error {
+func validateTimerValue(value any) error {
timer, ok := value.(uint32)
if !ok {
return pkgError.ValidationError("timer_seconds must be a valid number")
diff --git a/src/validations/send_validation_test_sticker.go b/src/validations/send_validation_sticker_test.go
similarity index 94%
rename from src/validations/send_validation_test_sticker.go
rename to src/validations/send_validation_sticker_test.go
index 077fdbbb..5598f9e4 100644
--- a/src/validations/send_validation_test_sticker.go
+++ b/src/validations/send_validation_sticker_test.go
@@ -52,7 +52,7 @@ func TestValidateSendSticker(t *testing.T) {
Sticker: sticker,
},
},
- err: pkgError.ValidationError("Phone: cannot be blank."),
+ err: pkgError.ValidationError("phone: cannot be blank."),
},
{
name: "should error without sticker and sticker_url",
@@ -132,7 +132,7 @@ func TestValidateSendSticker(t *testing.T) {
request: domainSend.StickerRequest{
BaseRequest: domainSend.BaseRequest{
Phone: "+6289123456",
- Duration: func() *int { d := 3600; return &d }(),
+ Duration: func() *int { d := 86400; return &d }(),
},
Sticker: sticker,
},
@@ -150,7 +150,7 @@ func TestValidateSendSticker(t *testing.T) {
Sticker: sticker,
},
},
- err: pkgError.ValidationError("duration must be between 0 and 4294967295 seconds (0 means no expiry)"),
+ err: pkgError.ValidationError("duration must be one of: 0 (no expiry), 86400 (24h), 604800 (7d), 7776000 (90d)"),
},
}