GOWA - WhatsApp REST API with support for UI, Multi Account, Webhooks, and MCP, and Chatwoot. Built with Golang for efficient memory use.
Go botgogolanggolang-whatsappgolang-whatsapp-apirestrest-apiwhatsappwhatsapp-apiwhatsapp-api-gowhatsapp-multi-devicewhatsapp-web-multi-device
feat: refactor chatstorage & fix relogin and webhook
Aldino Kemal085f8fae9537
diff --git a/src/cmd/root.go b/src/cmd/root.goindex 4f3a5cca..5b216e85 100644--- a/src/cmd/root.go+++ b/src/cmd/root.go@@ -2,6 +2,7 @@ package cmdimport ("context"+ "database/sql""embed""fmt""os"@@ -11,6 +12,7 @@ import ("github.com/aldinokemal/go-whatsapp-web-multidevice/config"domainApp "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/app"domainChat "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chat"+ domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"domainGroup "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/group"domainMessage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/message"domainNewsletter "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/newsletter"@@ -39,7 +41,8 @@ var (whatsappDB *sqlstore.Container// Chat Storage- chatStorageRepo *chatstorage.Storage+ chatStorageDB *sql.DB+ chatStorageRepo domainChatStorage.IChatStorageRepository// UsecaseappUsecase domainApp.IAppUsecase@@ -184,6 +187,30 @@ func initFlags() {)}+func initChatStorage() (*sql.DB, error) {+ connStr := fmt.Sprintf("%s?_journal_mode=WAL", config.ChatStorageURI)+ if config.ChatStorageEnableForeignKeys {+ connStr += "&_foreign_keys=on"+ }++ db, err := sql.Open("sqlite3", connStr)+ if err != nil {+ return nil, err+ }++ // Configure connection pool+ db.SetMaxOpenConns(25)+ db.SetMaxIdleConns(5)++ // Test connection+ if err := db.Ping(); err != nil {+ db.Close()+ return nil, fmt.Errorf("failed to ping database: %w", err)+ }++ return db, nil+}+func initApp() {if config.AppDebug {config.WhatsappLogLevel = "DEBUG"@@ -198,17 +225,19 @@ func initApp() {ctx := context.Background()- chatStorageRepo, err = chatstorage.NewStorage(chatstorage.DefaultConfig())+ chatStorageDB, err = initChatStorage()if err != nil {- // Terminate the application if chat storage fails to initialize to avoid nil pointer panics later.logrus.Fatalf("failed to initialize chat storage: %v", err)}+ chatStorageRepo = chatstorage.NewStorageRepository(chatStorageDB)+ chatStorageRepo.InitializeSchema()+whatsappDB = whatsapp.InitWaDB(ctx)whatsapp.InitWaCLI(ctx, whatsappDB, chatStorageRepo)// Usecase- appUsecase = usecase.NewAppService(whatsappDB, chatStorageRepo)+ appUsecase = usecase.NewAppService(chatStorageRepo)chatUsecase = usecase.NewChatService(chatStorageRepo)sendUsecase = usecase.NewSendService(appUsecase, chatStorageRepo)userUsecase = usecase.NewUserService()diff --git a/src/config/settings.go b/src/config/settings.goindex fc7e67d4..0ee59443 100644--- a/src/config/settings.go+++ b/src/config/settings.go@@ -15,11 +15,10 @@ var (McpPort = "8080"McpHost = "localhost"- PathQrCode = "statics/qrcode"- PathSendItems = "statics/senditems"- PathMedia = "statics/media"- PathStorages = "storages"- PathChatStorage = "storages/chat.csv"+ PathQrCode = "statics/qrcode"+ PathSendItems = "statics/senditems"+ PathMedia = "statics/media"+ PathStorages = "storages"DBURI = "file:storages/whatsapp.db?_foreign_keys=on"@@ -35,4 +34,8 @@ var (WhatsappTypeUser = "@s.whatsapp.net"WhatsappTypeGroup = "@g.us"WhatsappAccountValidation = true++ ChatStorageURI = "file:storages/chatstorage.db"+ ChatStorageEnableForeignKeys = true+ ChatStorageEnableWAL = true)diff --git a/src/infrastructure/chatstorage/entity.go b/src/domains/chatstorage/chatstorage.gosimilarity index 98%rename from src/infrastructure/chatstorage/entity.gorename to src/domains/chatstorage/chatstorage.goindex dcd31844..08b481d6 100644--- a/src/infrastructure/chatstorage/entity.go+++ b/src/domains/chatstorage/chatstorage.go@@ -1,8 +1,6 @@package chatstorage-import (- "time"-)+import "time"// Chat represents a WhatsApp chat/conversationtype Chat struct {diff --git a/src/domains/chatstorage/interfaces.go b/src/domains/chatstorage/interfaces.gonew file mode 100644index 00000000..ba6534b9--- /dev/null+++ b/src/domains/chatstorage/interfaces.go@@ -0,0 +1,41 @@+package chatstorage++import (+ "context"+ "time"++ "go.mau.fi/whatsmeow/types"+ "go.mau.fi/whatsmeow/types/events"+)++type IChatStorageRepository interface {+ // Chat operations+ CreateMessage(ctx context.Context, evt *events.Message) error+ StoreChat(chat *Chat) error+ GetChat(jid string) (*Chat, error)+ GetChats(filter *ChatFilter) ([]*Chat, error)+ DeleteChat(jid string) error++ // Message operations+ StoreMessage(message *Message) error+ StoreMessagesBatch(messages []*Message) error+ GetMessageByID(id string) (*Message, error) // New method for efficient ID-only search+ GetMessages(filter *MessageFilter) ([]*Message, error)+ SearchMessages(chatJID, searchText string, limit int) ([]*Message, error) // Database-level search+ DeleteMessage(id, chatJID string) error+ StoreSentMessageWithContext(ctx context.Context, messageID string, senderJID string, recipientJID string, content string, timestamp time.Time) error++ // Statistics+ GetChatMessageCount(chatJID string) (int64, error)+ GetTotalMessageCount() (int64, error)+ GetTotalChatCount() (int64, error)+ GetChatNameWithPushName(jid types.JID, chatJID string, senderUser string, pushName string) string+ GetStorageStatistics() (chatCount int64, messageCount int64, err error)++ // Cleanup operations+ TruncateAllChats() error+ TruncateAllDataWithLogging(logPrefix string) error++ // Schema operations+ InitializeSchema() error+}diff --git a/src/domains/group/group.go b/src/domains/group/group.goindex 0c752877..687c8cda 100644--- a/src/domains/group/group.go+++ b/src/domains/group/group.go@@ -100,5 +100,5 @@ type GroupInfoRequest struct {}type GroupInfoResponse struct {- Data interface{} `json:"data"`+ Data any `json:"data"`}diff --git a/src/infrastructure/chatstorage/init.go b/src/infrastructure/chatstorage/init.godeleted file mode 100644index ca47fb2e..00000000--- a/src/infrastructure/chatstorage/init.go+++ /dev/null@@ -1,221 +0,0 @@-package chatstorage--import (- "database/sql"- "fmt"- "os"- "path/filepath"-- _ "github.com/mattn/go-sqlite3"-)--// Config holds configuration for chat storage-type Config struct {- DatabasePath string- EnableForeignKeys bool- EnableWAL bool-}--// DefaultConfig returns default configuration-func DefaultConfig() *Config {- return &Config{- DatabasePath: "storages/chatstorage.db",- EnableForeignKeys: true,- EnableWAL: true,- }-}--// Storage manages the chat storage system-type Storage struct {- db *sql.DB- repo Repository- config *Config-}--// NewStorage creates a new Storage instance-func NewStorage(config *Config) (*Storage, error) {- if config == nil {- config = DefaultConfig()- }-- // Create directory for database if it doesn't exist- dir := filepath.Dir(config.DatabasePath)- if err := os.MkdirAll(dir, 0755); err != nil {- return nil, fmt.Errorf("failed to create database directory: %w", err)- }-- // Build connection string- connStr := fmt.Sprintf("file:%s?_journal_mode=WAL", config.DatabasePath)- if config.EnableForeignKeys {- connStr += "&_foreign_keys=on"- }-- // Open database connection- db, err := sql.Open("sqlite3", connStr)- if err != nil {- return nil, fmt.Errorf("failed to open database: %w", err)- }-- // Configure connection pool- db.SetMaxOpenConns(25)- db.SetMaxIdleConns(5)-- // Test connection- if err := db.Ping(); err != nil {- db.Close()- return nil, fmt.Errorf("failed to ping database: %w", err)- }-- storage := &Storage{- db: db,- config: config,- repo: NewSQLiteRepository(db),- }-- // Initialize database schema- if err := storage.initializeSchema(); err != nil {- db.Close()- return nil, fmt.Errorf("failed to initialize schema: %w", err)- }-- return storage, nil-}--// Repository returns the repository instance-func (s *Storage) Repository() Repository {- return s.repo-}--// DB returns the raw database connection-func (s *Storage) DB() *sql.DB {- return s.db-}--// Close closes the database connection-func (s *Storage) Close() error {- if s.db == nil {- return nil- }-- // Close the database connection- if err := s.db.Close(); err != nil {- return fmt.Errorf("failed to close database connection: %w", err)- }-- return nil-}--// initializeSchema creates or migrates the database schema-func (s *Storage) initializeSchema() error {- // Get current schema version- version, err := s.getSchemaVersion()- if err != nil {- return err- }-- // Run migrations based on version- migrations := s.getMigrations()- for i := version; i < len(migrations); i++ {- if err := s.runMigration(migrations[i], i+1); err != nil {- return fmt.Errorf("failed to run migration %d: %w", i+1, err)- }- }-- return nil-}--// getSchemaVersion returns the current schema version-func (s *Storage) getSchemaVersion() (int, error) {- // Create schema_info table if it doesn't exist- _, err := s.db.Exec(`- CREATE TABLE IF NOT EXISTS schema_info (- version INTEGER PRIMARY KEY DEFAULT 0,- updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP- )- `)- if err != nil {- return 0, err- }-- // Get current version- var version int- err = s.db.QueryRow("SELECT COALESCE(MAX(version), 0) FROM schema_info").Scan(&version)- if err != nil {- return 0, err- }-- return version, nil-}--// runMigration executes a migration-func (s *Storage) runMigration(migration string, version int) error {- tx, err := s.db.Begin()- if err != nil {- return err- }- defer tx.Rollback()-- // Execute migration- if _, err := tx.Exec(migration); err != nil {- return err- }-- // Update schema version- if _, err := tx.Exec("INSERT OR REPLACE INTO schema_info (version) VALUES (?)", version); err != nil {- return err- }-- return tx.Commit()-}--// getMigrations returns all database migrations-func (s *Storage) getMigrations() []string {- return []string{- // Migration 1: Initial schema with only chats and messages tables- `- -- Create chats table- CREATE TABLE IF NOT EXISTS chats (- jid TEXT PRIMARY KEY,- name TEXT NOT NULL,- last_message_time TIMESTAMP NOT NULL,- ephemeral_expiration INTEGER DEFAULT 0,- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,- updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP- );-- -- Create messages table- CREATE TABLE IF NOT EXISTS messages (- id TEXT NOT NULL,- chat_jid TEXT NOT NULL,- sender TEXT NOT NULL,- content TEXT,- timestamp TIMESTAMP NOT NULL,- is_from_me BOOLEAN DEFAULT FALSE,- media_type TEXT,- filename TEXT,- url TEXT,- media_key BLOB,- file_sha256 BLOB,- file_enc_sha256 BLOB,- file_length INTEGER DEFAULT 0,- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,- updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,- PRIMARY KEY (id, chat_jid),- FOREIGN KEY (chat_jid) REFERENCES chats(jid) ON DELETE CASCADE- );-- -- Create indexes for performance- CREATE INDEX IF NOT EXISTS idx_messages_chat_jid ON messages(chat_jid);- CREATE INDEX IF NOT EXISTS idx_messages_timestamp ON messages(timestamp);- CREATE INDEX IF NOT EXISTS idx_messages_media_type ON messages(media_type);- CREATE INDEX IF NOT EXISTS idx_messages_sender ON messages(sender);- CREATE INDEX IF NOT EXISTS idx_chats_last_message ON chats(last_message_time);- CREATE INDEX IF NOT EXISTS idx_chats_name ON chats(name);- `,-- // Migration 2: Add index for message ID lookups (performance optimization)- `- CREATE INDEX IF NOT EXISTS idx_messages_id ON messages(id);- `,- }-}diff --git a/src/infrastructure/chatstorage/repository.go b/src/infrastructure/chatstorage/repository.godeleted file mode 100644index 002232a6..00000000--- a/src/infrastructure/chatstorage/repository.go+++ /dev/null@@ -1,614 +0,0 @@-package chatstorage--import (- "database/sql"- "fmt"- "strings"- "time"-)--// Repository defines the interface for chat storage operations-type Repository interface {- // Chat operations- StoreChat(chat *Chat) error- GetChat(jid string) (*Chat, error)- GetChats(filter *ChatFilter) ([]*Chat, error)- UpdateChatLastMessage(jid string, lastMessageTime time.Time) error- DeleteChat(jid string) error-- // Message operations- StoreMessage(message *Message) error- StoreMessagesBatch(messages []*Message) error- GetMessage(id, chatJID string) (*Message, error)- GetMessageByID(id string) (*Message, error) // New method for efficient ID-only search- GetMessages(filter *MessageFilter) ([]*Message, error)- SearchMessages(chatJID, searchText string, limit int) ([]*Message, error) // Database-level search- GetMediaInfo(id, chatJID string) (*MediaInfo, error)- UpdateMediaInfo(id, chatJID string, mediaInfo *MediaInfo) error- DeleteMessage(id, chatJID string) error- DeleteMessagesByChat(chatJID string) error-- // Statistics- GetChatMessageCount(chatJID string) (int64, error)- GetTotalMessageCount() (int64, error)- GetTotalChatCount() (int64, error)-- // Cleanup operations- TruncateAllMessages() error- TruncateAllChats() error- TruncateAllData() error-}--// SQLiteRepository implements Repository using SQLite-type SQLiteRepository struct {- db *sql.DB-}--// NewSQLiteRepository creates a new SQLite repository-func NewSQLiteRepository(db *sql.DB) *SQLiteRepository {- return &SQLiteRepository{db: db}-}--// StoreChat creates or updates a chat-func (r *SQLiteRepository) StoreChat(chat *Chat) error {- now := time.Now()- chat.UpdatedAt = now-- query := `- INSERT INTO chats (jid, name, last_message_time, ephemeral_expiration, created_at, updated_at)- VALUES (?, ?, ?, ?, ?, ?)- ON CONFLICT(jid) DO UPDATE SET- name = excluded.name,- last_message_time = excluded.last_message_time,- ephemeral_expiration = excluded.ephemeral_expiration,- updated_at = excluded.updated_at- `-- _, err := r.db.Exec(query, chat.JID, chat.Name, chat.LastMessageTime, chat.EphemeralExpiration, now, chat.UpdatedAt)- return err-}--// GetChat retrieves a chat by JID-func (r *SQLiteRepository) GetChat(jid string) (*Chat, error) {- chat := &Chat{}- query := `- SELECT jid, name, last_message_time, ephemeral_expiration, created_at, updated_at- FROM chats- WHERE jid = ?- `-- err := r.db.QueryRow(query, jid).Scan(- &chat.JID, &chat.Name, &chat.LastMessageTime, &chat.EphemeralExpiration,- &chat.CreatedAt, &chat.UpdatedAt,- )-- if err == sql.ErrNoRows {- return nil, nil- }-- return chat, err-}--// GetMessageByID retrieves a message by its ID from any chat-// This is more efficient than searching through all chats-func (r *SQLiteRepository) GetMessageByID(id string) (*Message, error) {- message := &Message{}- query := `- SELECT id, chat_jid, sender, content, timestamp, is_from_me,- media_type, filename, url, media_key, file_sha256,- file_enc_sha256, file_length, created_at, updated_at- FROM messages- WHERE id = ?- LIMIT 1- `-- err := r.db.QueryRow(query, id).Scan(- &message.ID, &message.ChatJID, &message.Sender, &message.Content,- &message.Timestamp, &message.IsFromMe, &message.MediaType, &message.Filename,- &message.URL, &message.MediaKey, &message.FileSHA256, &message.FileEncSHA256,- &message.FileLength, &message.CreatedAt, &message.UpdatedAt,- )-- if err == sql.ErrNoRows {- return nil, nil- }-- return message, err-}--// GetChats retrieves chats with filtering-func (r *SQLiteRepository) GetChats(filter *ChatFilter) ([]*Chat, error) {- var conditions []string- var args []interface{}-- query := `- SELECT c.jid, c.name, c.last_message_time, c.ephemeral_expiration, c.created_at, c.updated_at- FROM chats c- `-- if filter.SearchName != "" {- conditions = append(conditions, "c.name LIKE ?")- args = append(args, "%"+filter.SearchName+"%")- }-- if filter.HasMedia {- query += " INNER JOIN messages m ON c.jid = m.chat_jid"- conditions = append(conditions, "m.media_type != ''")- }-- if len(conditions) > 0 {- query += " WHERE " + strings.Join(conditions, " AND ")- }-- query += " ORDER BY c.last_message_time DESC"-- // Safely add LIMIT and OFFSET using parameterized values- if filter.Limit > 0 {- // Validate limit to prevent abuse- if filter.Limit > 1000 {- filter.Limit = 1000- }- query += " LIMIT ?"- args = append(args, filter.Limit)-- if filter.Offset > 0 {- query += " OFFSET ?"- args = append(args, filter.Offset)- }- }-- rows, err := r.db.Query(query, args...)- if err != nil {- return nil, err- }- defer rows.Close()-- var chats []*Chat- for rows.Next() {- chat := &Chat{}- err := rows.Scan(- &chat.JID, &chat.Name, &chat.LastMessageTime, &chat.EphemeralExpiration,- &chat.CreatedAt, &chat.UpdatedAt,- )- if err != nil {- return nil, err- }- chats = append(chats, chat)- }-- return chats, rows.Err()-}--// UpdateChatLastMessage updates the last message time for a chat-func (r *SQLiteRepository) UpdateChatLastMessage(jid string, lastMessageTime time.Time) error {- query := `- UPDATE chats- SET last_message_time = ?, updated_at = ?- WHERE jid = ?- `- _, err := r.db.Exec(query, lastMessageTime, time.Now(), jid)- return err-}--// DeleteChat deletes a chat and all its messages-func (r *SQLiteRepository) DeleteChat(jid string) error {- tx, err := r.db.Begin()- if err != nil {- return err- }- defer tx.Rollback()-- // Delete messages first (foreign key constraint)- _, err = tx.Exec("DELETE FROM messages WHERE chat_jid = ?", jid)- if err != nil {- return err- }-- // Delete chat- _, err = tx.Exec("DELETE FROM chats WHERE jid = ?", jid)- if err != nil {- return err- }-- return tx.Commit()-}--// StoreMessage creates or updates a message-func (r *SQLiteRepository) StoreMessage(message *Message) error {- now := time.Now()- message.CreatedAt = now- message.UpdatedAt = now-- // Skip empty messages- if message.Content == "" && message.MediaType == "" {- // This is not an error, just skip storing empty messages- return nil- }-- query := `- INSERT INTO messages (- id, chat_jid, sender, content, timestamp, is_from_me,- media_type, filename, url, media_key, file_sha256,- file_enc_sha256, file_length, created_at, updated_at- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)- ON CONFLICT(id, chat_jid) DO UPDATE SET- sender = excluded.sender,- content = excluded.content,- timestamp = excluded.timestamp,- is_from_me = excluded.is_from_me,- media_type = excluded.media_type,- filename = excluded.filename,- url = excluded.url,- media_key = excluded.media_key,- file_sha256 = excluded.file_sha256,- file_enc_sha256 = excluded.file_enc_sha256,- file_length = excluded.file_length,- updated_at = excluded.updated_at- `-- _, err := r.db.Exec(query,- message.ID, message.ChatJID, message.Sender, message.Content,- message.Timestamp, message.IsFromMe, message.MediaType, message.Filename,- message.URL, message.MediaKey, message.FileSHA256, message.FileEncSHA256,- message.FileLength, message.CreatedAt, message.UpdatedAt,- )-- return err-}--// StoreMessagesBatch creates or updates multiple messages in a single transaction-func (r *SQLiteRepository) StoreMessagesBatch(messages []*Message) error {- if len(messages) == 0 {- return nil- }-- tx, err := r.db.Begin()- if err != nil {- return fmt.Errorf("failed to begin transaction: %w", err)- }- defer tx.Rollback()-- // Prepare the statement once for better performance- stmt, err := tx.Prepare(`- INSERT INTO messages (- id, chat_jid, sender, content, timestamp, is_from_me,- media_type, filename, url, media_key, file_sha256,- file_enc_sha256, file_length, created_at, updated_at- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)- ON CONFLICT(id, chat_jid) DO UPDATE SET- sender = excluded.sender,- content = excluded.content,- timestamp = excluded.timestamp,- is_from_me = excluded.is_from_me,- media_type = excluded.media_type,- filename = excluded.filename,- url = excluded.url,- media_key = excluded.media_key,- file_sha256 = excluded.file_sha256,- file_enc_sha256 = excluded.file_enc_sha256,- file_length = excluded.file_length,- updated_at = excluded.updated_at- `)- if err != nil {- return fmt.Errorf("failed to prepare statement: %w", err)- }- defer stmt.Close()-- now := time.Now()- for _, message := range messages {- // Skip empty messages- if message.Content == "" && message.MediaType == "" {- continue- }-- message.CreatedAt = now- message.UpdatedAt = now-- _, err = stmt.Exec(- message.ID, message.ChatJID, message.Sender, message.Content,- message.Timestamp, message.IsFromMe, message.MediaType, message.Filename,- message.URL, message.MediaKey, message.FileSHA256, message.FileEncSHA256,- message.FileLength, message.CreatedAt, message.UpdatedAt,- )- if err != nil {- return fmt.Errorf("failed to store message %s: %w", message.ID, err)- }- }-- return tx.Commit()-}--// GetMessage retrieves a specific message-func (r *SQLiteRepository) GetMessage(id, chatJID string) (*Message, error) {- message := &Message{}- query := `- SELECT id, chat_jid, sender, content, timestamp, is_from_me,- media_type, filename, url, media_key, file_sha256,- file_enc_sha256, file_length, created_at, updated_at- FROM messages- WHERE id = ? AND chat_jid = ?- `-- err := r.db.QueryRow(query, id, chatJID).Scan(- &message.ID, &message.ChatJID, &message.Sender, &message.Content,- &message.Timestamp, &message.IsFromMe, &message.MediaType, &message.Filename,- &message.URL, &message.MediaKey, &message.FileSHA256, &message.FileEncSHA256,- &message.FileLength, &message.CreatedAt, &message.UpdatedAt,- )-- if err == sql.ErrNoRows {- return nil, nil- }-- return message, err-}--// GetMessages retrieves messages with filtering-func (r *SQLiteRepository) GetMessages(filter *MessageFilter) ([]*Message, error) {- var conditions []string- var args []interface{}-- conditions = append(conditions, "chat_jid = ?")- args = append(args, filter.ChatJID)-- if filter.StartTime != nil {- conditions = append(conditions, "timestamp >= ?")- args = append(args, *filter.StartTime)- }-- if filter.EndTime != nil {- conditions = append(conditions, "timestamp <= ?")- args = append(args, *filter.EndTime)- }-- if filter.MediaOnly {- conditions = append(conditions, "media_type != ''")- }-- if filter.IsFromMe != nil {- conditions = append(conditions, "is_from_me = ?")- args = append(args, *filter.IsFromMe)- }-- query := `- SELECT id, chat_jid, sender, content, timestamp, is_from_me,- media_type, filename, url, media_key, file_sha256,- file_enc_sha256, file_length, created_at, updated_at- FROM messages- WHERE ` + strings.Join(conditions, " AND ") + `- ORDER BY timestamp DESC- `-- // Safely add LIMIT and OFFSET using parameterized values- if filter.Limit > 0 {- // Validate limit to prevent abuse- if filter.Limit > 1000 {- filter.Limit = 1000- }- query += " LIMIT ?"- args = append(args, filter.Limit)-- if filter.Offset > 0 {- query += " OFFSET ?"- args = append(args, filter.Offset)- }- }-- rows, err := r.db.Query(query, args...)- if err != nil {- return nil, err- }- defer rows.Close()-- var messages []*Message- for rows.Next() {- message := &Message{}- err := rows.Scan(- &message.ID, &message.ChatJID, &message.Sender, &message.Content,- &message.Timestamp, &message.IsFromMe, &message.MediaType, &message.Filename,- &message.URL, &message.MediaKey, &message.FileSHA256, &message.FileEncSHA256,- &message.FileLength, &message.CreatedAt, &message.UpdatedAt,- )- if err != nil {- return nil, err- }- messages = append(messages, message)- }-- return messages, rows.Err()-}--// SearchMessages performs database-level search for messages containing specific text-func (r *SQLiteRepository) SearchMessages(chatJID, searchText string, limit int) ([]*Message, error) {- // Return empty results for empty search text- if strings.TrimSpace(searchText) == "" {- return []*Message{}, nil- }-- var conditions []string- var args []interface{}-- // Always filter by chat JID- conditions = append(conditions, "chat_jid = ?")- args = append(args, chatJID)-- // Add search condition using LIKE operator for case-insensitive search- conditions = append(conditions, "LOWER(content) LIKE ?")- args = append(args, "%"+strings.ToLower(searchText)+"%")-- query := `- SELECT id, chat_jid, sender, content, timestamp, is_from_me,- media_type, filename, url, media_key, file_sha256,- file_enc_sha256, file_length, created_at, updated_at- FROM messages- WHERE ` + strings.Join(conditions, " AND ") + `- ORDER BY timestamp DESC- `-- // Add limit with validation- if limit > 0 {- // Validate limit to prevent abuse- if limit > 1000 {- limit = 1000- }- query += " LIMIT ?"- args = append(args, limit)- }-- rows, err := r.db.Query(query, args...)- if err != nil {- return nil, fmt.Errorf("failed to search messages: %w", err)- }- defer rows.Close()-- var messages []*Message- for rows.Next() {- message := &Message{}- err := rows.Scan(- &message.ID, &message.ChatJID, &message.Sender, &message.Content,- &message.Timestamp, &message.IsFromMe, &message.MediaType, &message.Filename,- &message.URL, &message.MediaKey, &message.FileSHA256, &message.FileEncSHA256,- &message.FileLength, &message.CreatedAt, &message.UpdatedAt,- )- if err != nil {- return nil, fmt.Errorf("failed to scan message: %w", err)- }- messages = append(messages, message)- }-- if err := rows.Err(); err != nil {- return nil, fmt.Errorf("error iterating messages: %w", err)- }-- return messages, nil-}--// GetMediaInfo retrieves media information for a message-func (r *SQLiteRepository) GetMediaInfo(id, chatJID string) (*MediaInfo, error) {- info := &MediaInfo{- MessageID: id,- ChatJID: chatJID,- }-- query := `- SELECT media_type, filename, url, media_key, file_sha256,- file_enc_sha256, file_length- FROM messages- WHERE id = ? AND chat_jid = ?- `-- err := r.db.QueryRow(query, id, chatJID).Scan(- &info.MediaType, &info.Filename, &info.URL, &info.MediaKey,- &info.FileSHA256, &info.FileEncSHA256, &info.FileLength,- )-- if err == sql.ErrNoRows {- return nil, nil- }-- return info, err-}--// UpdateMediaInfo updates media information for a message-func (r *SQLiteRepository) UpdateMediaInfo(id, chatJID string, mediaInfo *MediaInfo) error {- query := `- UPDATE messages- SET url = ?, media_key = ?, file_sha256 = ?,- file_enc_sha256 = ?, file_length = ?, updated_at = ?- WHERE id = ? AND chat_jid = ?- `-- _, err := r.db.Exec(query,- mediaInfo.URL, mediaInfo.MediaKey, mediaInfo.FileSHA256,- mediaInfo.FileEncSHA256, mediaInfo.FileLength, time.Now(),- id, chatJID,- )-- return err-}--// DeleteMessage deletes a specific message-func (r *SQLiteRepository) DeleteMessage(id, chatJID string) error {- _, err := r.db.Exec("DELETE FROM messages WHERE id = ? AND chat_jid = ?", id, chatJID)- return err-}--// DeleteMessagesByChat deletes all messages for a chat-func (r *SQLiteRepository) DeleteMessagesByChat(chatJID string) error {- _, err := r.db.Exec("DELETE FROM messages WHERE chat_jid = ?", chatJID)- return err-}--// GetChatMessageCount returns the number of messages in a chat-func (r *SQLiteRepository) GetChatMessageCount(chatJID string) (int64, error) {- var count int64- err := r.db.QueryRow("SELECT COUNT(*) FROM messages WHERE chat_jid = ?", chatJID).Scan(&count)- return count, err-}--// GetTotalMessageCount returns the total number of messages-func (r *SQLiteRepository) GetTotalMessageCount() (int64, error) {- var count int64- err := r.db.QueryRow("SELECT COUNT(*) FROM messages").Scan(&count)- return count, err-}--// GetTotalChatCount returns the total number of chats-func (r *SQLiteRepository) GetTotalChatCount() (int64, error) {- var count int64- err := r.db.QueryRow("SELECT COUNT(*) FROM chats").Scan(&count)- return count, err-}--// TruncateAllMessages deletes all messages from the database-func (r *SQLiteRepository) TruncateAllMessages() error {- _, err := r.db.Exec("DELETE FROM messages")- return err-}--// TruncateAllChats deletes all chats from the database-// Note: Due to foreign key constraints, messages must be deleted first-func (r *SQLiteRepository) TruncateAllChats() error {- tx, err := r.db.Begin()- if err != nil {- return fmt.Errorf("failed to begin transaction: %w", err)- }- defer tx.Rollback()-- // Delete messages first (foreign key constraint)- _, err = tx.Exec("DELETE FROM messages")- if err != nil {- return fmt.Errorf("failed to delete messages: %w", err)- }-- // Delete chats- _, err = tx.Exec("DELETE FROM chats")- if err != nil {- return fmt.Errorf("failed to delete chats: %w", err)- }-- return tx.Commit()-}--// TruncateAllData deletes all chats and messages in the correct order-func (r *SQLiteRepository) TruncateAllData() error {- tx, err := r.db.Begin()- if err != nil {- return fmt.Errorf("failed to begin transaction: %w", err)- }- defer tx.Rollback()-- // Delete messages first (foreign key constraint)- _, err = tx.Exec("DELETE FROM messages")- if err != nil {- return fmt.Errorf("failed to delete messages: %w", err)- }-- // Delete chats- _, err = tx.Exec("DELETE FROM chats")- if err != nil {- return fmt.Errorf("failed to delete chats: %w", err)- }-- return tx.Commit()-}diff --git a/src/infrastructure/chatstorage/repository_test.go b/src/infrastructure/chatstorage/repository_test.godeleted file mode 100644index 0257b58b..00000000--- a/src/infrastructure/chatstorage/repository_test.go+++ /dev/null@@ -1,426 +0,0 @@-package chatstorage--import (- "database/sql"- "testing"- "time"-- _ "github.com/mattn/go-sqlite3"- "github.com/stretchr/testify/suite"-)--type ChatStorageTestSuite struct {- suite.Suite- storage *Storage- repo Repository- db *sql.DB-}--func (suite *ChatStorageTestSuite) SetupTest() {- // Create temporary database for testing- tempDB := ":memory:"-- db, err := sql.Open("sqlite3", tempDB)- suite.Require().NoError(err)-- // Create repository- repo := NewSQLiteRepository(db)-- // Create storage with in-memory config- config := &Config{- DatabasePath: tempDB,- EnableForeignKeys: true,- EnableWAL: false, // WAL mode doesn't work with :memory:- }-- storage := &Storage{- db: db,- config: config,- repo: repo,- }-- // Initialize schema manually for testing- suite.initTestSchema(db)-- suite.storage = storage- suite.repo = repo- suite.db = db-}--func (suite *ChatStorageTestSuite) TearDownTest() {- if suite.db != nil {- suite.db.Close()- }-}--func (suite *ChatStorageTestSuite) initTestSchema(db *sql.DB) {- // Create chats table- _, err := db.Exec(`- CREATE TABLE IF NOT EXISTS chats (- jid TEXT PRIMARY KEY,- name TEXT NOT NULL,- last_message_time TIMESTAMP NOT NULL,- ephemeral_expiration INTEGER DEFAULT 0,- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,- updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP- )- `)- suite.Require().NoError(err)-- // Create messages table- _, err = db.Exec(`- CREATE TABLE IF NOT EXISTS messages (- id TEXT NOT NULL,- chat_jid TEXT NOT NULL,- sender TEXT NOT NULL,- content TEXT,- timestamp TIMESTAMP NOT NULL,- is_from_me BOOLEAN DEFAULT FALSE,- media_type TEXT,- filename TEXT,- url TEXT,- media_key BLOB,- file_sha256 BLOB,- file_enc_sha256 BLOB,- file_length INTEGER DEFAULT 0,- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,- updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,- PRIMARY KEY (id, chat_jid),- FOREIGN KEY (chat_jid) REFERENCES chats(jid) ON DELETE CASCADE- )- `)- suite.Require().NoError(err)-}--func (suite *ChatStorageTestSuite) createTestData() {- // Create test chats- chat1 := &Chat{- JID: "[email protected]",- Name: "Test Contact 1",- LastMessageTime: time.Now(),- }- chat2 := &Chat{- JID: "[email protected]",- Name: "Test Contact 2",- LastMessageTime: time.Now(),- }- chat3 := &Chat{- JID: "[email protected]",- Name: "Test Group",- LastMessageTime: time.Now(),- }-- err := suite.repo.StoreChat(chat1)- suite.Require().NoError(err)- err = suite.repo.StoreChat(chat2)- suite.Require().NoError(err)- err = suite.repo.StoreChat(chat3)- suite.Require().NoError(err)-- // Create test messages- messages := []*Message{- {- ID: "msg1",- ChatJID: "[email protected]",- Sender: "1234567890",- Content: "Hello World",- Timestamp: time.Now(),- IsFromMe: false,- },- {- ID: "msg2",- ChatJID: "[email protected]",- Sender: "me",- Content: "Hi there!",- Timestamp: time.Now(),- IsFromMe: true,- },- {- ID: "msg3",- ChatJID: "[email protected]",- Sender: "0987654321",- Content: "How are you?",- Timestamp: time.Now(),- IsFromMe: false,- },- {- ID: "msg4",- ChatJID: "[email protected]",- Sender: "1234567890",- Content: "Group message",- Timestamp: time.Now(),- IsFromMe: false,- },- {- ID: "msg5",- ChatJID: "[email protected]",- Sender: "me",- Content: "My group reply",- Timestamp: time.Now(),- IsFromMe: true,- },- }-- err = suite.repo.StoreMessagesBatch(messages)- suite.Require().NoError(err)-}--func (suite *ChatStorageTestSuite) TestTruncateAllMessages() {- // Create test data- suite.createTestData()-- // Verify data exists- messageCount, err := suite.repo.GetTotalMessageCount()- suite.Require().NoError(err)- suite.Assert().Equal(int64(5), messageCount)-- // Truncate all messages- err = suite.repo.TruncateAllMessages()- suite.Require().NoError(err)-- // Verify messages are gone- messageCount, err = suite.repo.GetTotalMessageCount()- suite.Require().NoError(err)- suite.Assert().Equal(int64(0), messageCount)-- // Verify chats still exist- chats, err := suite.repo.GetChats(&ChatFilter{Limit: 100})- suite.Require().NoError(err)- suite.Assert().Equal(3, len(chats))-}--func (suite *ChatStorageTestSuite) TestTruncateAllChats() {- // Create test data- suite.createTestData()-- // Verify data exists- chats, err := suite.repo.GetChats(&ChatFilter{Limit: 100})- suite.Require().NoError(err)- suite.Assert().Equal(3, len(chats))-- // Truncate all chats (this should also delete messages due to foreign key constraint)- err = suite.repo.TruncateAllChats()- suite.Require().NoError(err)-- // Verify chats are gone- chats, err = suite.repo.GetChats(&ChatFilter{Limit: 100})- suite.Require().NoError(err)- suite.Assert().Equal(0, len(chats))-- // Verify messages are also gone- messageCount, err := suite.repo.GetTotalMessageCount()- suite.Require().NoError(err)- suite.Assert().Equal(int64(0), messageCount)-}--func (suite *ChatStorageTestSuite) TestTruncateAllData() {- // Create test data- suite.createTestData()-- // Verify data exists- messageCount, err := suite.repo.GetTotalMessageCount()- suite.Require().NoError(err)- suite.Assert().Equal(int64(5), messageCount)-- chats, err := suite.repo.GetChats(&ChatFilter{Limit: 100})- suite.Require().NoError(err)- suite.Assert().Equal(3, len(chats))-- // Truncate all data- err = suite.repo.TruncateAllData()- suite.Require().NoError(err)-- // Verify everything is gone- messageCount, err = suite.repo.GetTotalMessageCount()- suite.Require().NoError(err)- suite.Assert().Equal(int64(0), messageCount)-- chats, err = suite.repo.GetChats(&ChatFilter{Limit: 100})- suite.Require().NoError(err)- suite.Assert().Equal(0, len(chats))-}--func (suite *ChatStorageTestSuite) TestStorageGetStorageStatistics() {- // Create test data- suite.createTestData()-- // Get statistics- chatCount, messageCount, err := suite.storage.GetStorageStatistics()- suite.Require().NoError(err)-- suite.Assert().Equal(int64(3), chatCount)- suite.Assert().Equal(int64(5), messageCount)-}--func (suite *ChatStorageTestSuite) TestStorageTruncateAllDataWithLogging() {- // Create test data- suite.createTestData()-- // Verify data exists before truncation- chatCount, messageCount, err := suite.storage.GetStorageStatistics()- suite.Require().NoError(err)- suite.Assert().Equal(int64(3), chatCount)- suite.Assert().Equal(int64(5), messageCount)-- // Truncate with logging- err = suite.storage.TruncateAllDataWithLogging("TEST")- suite.Require().NoError(err)-- // Verify data is gone after truncation- chatCount, messageCount, err = suite.storage.GetStorageStatistics()- suite.Require().NoError(err)- suite.Assert().Equal(int64(0), chatCount)- suite.Assert().Equal(int64(0), messageCount)-}--func (suite *ChatStorageTestSuite) TestTruncateEmptyDatabase() {- // Test truncating when database is already empty- err := suite.repo.TruncateAllData()- suite.Require().NoError(err)-- // Verify counts are still zero- messageCount, err := suite.repo.GetTotalMessageCount()- suite.Require().NoError(err)- suite.Assert().Equal(int64(0), messageCount)-- chats, err := suite.repo.GetChats(&ChatFilter{Limit: 100})- suite.Require().NoError(err)- suite.Assert().Equal(0, len(chats))-}--func TestChatStorageTestSuite(t *testing.T) {- suite.Run(t, new(ChatStorageTestSuite))-}--// TestGetMessageByID tests the new optimized GetMessageByID method-func (suite *ChatStorageTestSuite) TestGetMessageByID() {- // Create test data- suite.createTestData()-- // Test finding existing message by ID only- msg, err := suite.repo.GetMessageByID("msg1")- suite.NoError(err)- suite.NotNil(msg)- suite.Equal("msg1", msg.ID)- suite.Equal("[email protected]", msg.ChatJID)- suite.Equal("Hello World", msg.Content)-- // Test finding non-existent message- msg, err = suite.repo.GetMessageByID("nonexistent")- suite.NoError(err)- suite.Nil(msg)-- // Test finding message from different chat- msg, err = suite.repo.GetMessageByID("msg3")- suite.NoError(err)- suite.NotNil(msg)- suite.Equal("msg3", msg.ID)- suite.Equal("[email protected]", msg.ChatJID)- suite.Equal("How are you?", msg.Content)-}--// TestSearchMessages tests the new database-level search functionality-func (suite *ChatStorageTestSuite) TestSearchMessages() {- // Create test data with varied content for search testing- suite.createTestData()-- // Add more messages with specific content for search testing- additionalMessages := []*Message{- {- ID: "msg6",- ChatJID: "[email protected]",- Sender: "1234567890",- Content: "This is a test message with HELLO in caps",- Timestamp: time.Now(),- IsFromMe: false,- },- {- ID: "msg7",- ChatJID: "[email protected]",- Sender: "me",- Content: "Another message without the target word",- Timestamp: time.Now(),- IsFromMe: true,- },- {- ID: "msg8",- ChatJID: "[email protected]",- Sender: "0987654321",- Content: "Hello from another chat",- Timestamp: time.Now(),- IsFromMe: false,- },- }-- err := suite.repo.StoreMessagesBatch(additionalMessages)- suite.Require().NoError(err)-- // Test case 1: Search for "hello" (case-insensitive) in first chat- results, err := suite.repo.SearchMessages("[email protected]", "hello", 10)- suite.NoError(err)- suite.Len(results, 2) // Should find "Hello World" and "HELLO in caps"-- // Verify results contain expected messages- foundContents := make(map[string]bool)- for _, msg := range results {- foundContents[msg.Content] = true- suite.Equal("[email protected]", msg.ChatJID) // All results should be from the specified chat- }- suite.True(foundContents["Hello World"])- suite.True(foundContents["This is a test message with HELLO in caps"])-- // Test case 2: Search for "hello" in second chat- results, err = suite.repo.SearchMessages("[email protected]", "hello", 10)- suite.NoError(err)- suite.Len(results, 1) // Should find "Hello from another chat"- suite.Equal("Hello from another chat", results[0].Content)-- // Test case 3: Search for non-existent text- results, err = suite.repo.SearchMessages("[email protected]", "nonexistent", 10)- suite.NoError(err)- suite.Len(results, 0)-- // Test case 4: Search in non-existent chat- results, err = suite.repo.SearchMessages("[email protected]", "hello", 10)- suite.NoError(err)- suite.Len(results, 0)-- // Test case 5: Search with limit- results, err = suite.repo.SearchMessages("[email protected]", "hello", 1)- suite.NoError(err)- suite.Len(results, 1) // Should respect the limit-- // Test case 6: Search with partial word match- results, err = suite.repo.SearchMessages("[email protected]", "test", 10)- suite.NoError(err)- suite.Len(results, 1) // Should find "This is a test message with HELLO in caps"- suite.Equal("This is a test message with HELLO in caps", results[0].Content)-- // Test case 7: Search with very high limit (should be capped)- results, err = suite.repo.SearchMessages("[email protected]", "hello", 2000)- suite.NoError(err)- suite.Len(results, 2) // Should find all matching messages regardless of high limit-}--// TestSearchMessagesStorage tests the storage layer search functionality-func (suite *ChatStorageTestSuite) TestSearchMessagesStorage() {- // Create test data- suite.createTestData()-- // Test the storage layer search method- results, err := suite.storage.SearchMessages("hello", "[email protected]", 10)- suite.NoError(err)- suite.Len(results, 1) // Should find "Hello World"- suite.Equal("Hello World", results[0].Content)-- // Test with empty search text- results, err = suite.storage.SearchMessages("", "[email protected]", 10)- suite.NoError(err)- suite.Len(results, 0) // Should return no results for empty search-- // Test with case variation- results, err = suite.storage.SearchMessages("HELLO", "[email protected]", 10)- suite.NoError(err)- suite.Len(results, 1) // Should find "Hello World" (case-insensitive)- suite.Equal("Hello World", results[0].Content)-}diff --git a/src/infrastructure/chatstorage/sqlite_repository.go b/src/infrastructure/chatstorage/sqlite_repository.gonew file mode 100644index 00000000..d3b03c70--- /dev/null+++ b/src/infrastructure/chatstorage/sqlite_repository.go@@ -0,0 +1,790 @@+package chatstorage++import (+ "context"+ "database/sql"+ "fmt"+ "strings"+ "time"++ domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"+ "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"+ "github.com/sirupsen/logrus"+ "go.mau.fi/whatsmeow/types"+ "go.mau.fi/whatsmeow/types/events"+)++// SQLiteRepository implements Repository using SQLite+type SQLiteRepository struct {+ db *sql.DB+}++// NewSQLiteRepository creates a new SQLite repository+func NewStorageRepository(db *sql.DB) domainChatStorage.IChatStorageRepository {+ return &SQLiteRepository{db: db}+}++// StoreChat creates or updates a chat+func (r *SQLiteRepository) StoreChat(chat *domainChatStorage.Chat) error {+ now := time.Now()+ chat.UpdatedAt = now++ query := `+ INSERT INTO chats (jid, name, last_message_time, ephemeral_expiration, created_at, updated_at)+ VALUES (?, ?, ?, ?, ?, ?)+ ON CONFLICT(jid) DO UPDATE SET+ name = excluded.name,+ last_message_time = excluded.last_message_time,+ ephemeral_expiration = excluded.ephemeral_expiration,+ updated_at = excluded.updated_at+ `++ _, err := r.db.Exec(query, chat.JID, chat.Name, chat.LastMessageTime, chat.EphemeralExpiration, now, chat.UpdatedAt)+ return err+}++// GetChat retrieves a chat by JID+func (r *SQLiteRepository) GetChat(jid string) (*domainChatStorage.Chat, error) {+ query := `+ SELECT jid, name, last_message_time, ephemeral_expiration, created_at, updated_at+ FROM chats+ WHERE jid = ?+ `++ chat, err := r.scanChat(r.db.QueryRow(query, jid))+ if err == sql.ErrNoRows {+ return nil, nil+ }++ return chat, err+}++// GetMessageByID retrieves a message by its ID from any chat+// This is more efficient than searching through all chats+func (r *SQLiteRepository) GetMessageByID(id string) (*domainChatStorage.Message, error) {+ query := `+ SELECT id, chat_jid, sender, content, timestamp, is_from_me,+ media_type, filename, url, media_key, file_sha256,+ file_enc_sha256, file_length, created_at, updated_at+ FROM messages+ WHERE id = ?+ LIMIT 1+ `++ message, err := r.scanMessage(r.db.QueryRow(query, id))+ if err == sql.ErrNoRows {+ return nil, nil+ }++ return message, err+}++// GetChats retrieves chats with filtering+func (r *SQLiteRepository) GetChats(filter *domainChatStorage.ChatFilter) ([]*domainChatStorage.Chat, error) {+ var conditions []string+ var args []any++ query := `+ SELECT c.jid, c.name, c.last_message_time, c.ephemeral_expiration, c.created_at, c.updated_at+ FROM chats c+ `++ if filter.SearchName != "" {+ conditions = append(conditions, "c.name LIKE ?")+ args = append(args, "%"+filter.SearchName+"%")+ }++ if filter.HasMedia {+ query += " INNER JOIN messages m ON c.jid = m.chat_jid"+ conditions = append(conditions, "m.media_type != ''")+ }++ if len(conditions) > 0 {+ query += " WHERE " + strings.Join(conditions, " AND ")+ }++ query += " ORDER BY c.last_message_time DESC"++ // Safely add LIMIT and OFFSET using parameterized values+ if filter.Limit > 0 {+ // Validate limit to prevent abuse+ if filter.Limit > 1000 {+ filter.Limit = 1000+ }+ query += " LIMIT ?"+ args = append(args, filter.Limit)++ if filter.Offset > 0 {+ query += " OFFSET ?"+ args = append(args, filter.Offset)+ }+ }++ rows, err := r.db.Query(query, args...)+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ var chats []*domainChatStorage.Chat+ for rows.Next() {+ chat, err := r.scanChat(rows)+ if err != nil {+ return nil, err+ }+ chats = append(chats, chat)+ }++ return chats, rows.Err()+}++// DeleteChat deletes a chat and all its messages+func (r *SQLiteRepository) DeleteChat(jid string) error {+ tx, err := r.db.Begin()+ if err != nil {+ return err+ }+ defer tx.Rollback()++ // Delete messages first (foreign key constraint)+ _, err = tx.Exec("DELETE FROM messages WHERE chat_jid = ?", jid)+ if err != nil {+ return err+ }++ // Delete chat+ _, err = tx.Exec("DELETE FROM chats WHERE jid = ?", jid)+ if err != nil {+ return err+ }++ return tx.Commit()+}++// StoreMessage creates or updates a message+func (r *SQLiteRepository) StoreMessage(message *domainChatStorage.Message) error {+ now := time.Now()+ message.CreatedAt = now+ message.UpdatedAt = now++ // Skip empty messages+ if message.Content == "" && message.MediaType == "" {+ // This is not an error, just skip storing empty messages+ return nil+ }++ query := `+ INSERT INTO messages (+ id, chat_jid, sender, content, timestamp, is_from_me,+ media_type, filename, url, media_key, file_sha256,+ file_enc_sha256, file_length, created_at, updated_at+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ ON CONFLICT(id, chat_jid) DO UPDATE SET+ sender = excluded.sender,+ content = excluded.content,+ timestamp = excluded.timestamp,+ is_from_me = excluded.is_from_me,+ media_type = excluded.media_type,+ filename = excluded.filename,+ url = excluded.url,+ media_key = excluded.media_key,+ file_sha256 = excluded.file_sha256,+ file_enc_sha256 = excluded.file_enc_sha256,+ file_length = excluded.file_length,+ updated_at = excluded.updated_at+ `++ _, err := r.db.Exec(query,+ message.ID, message.ChatJID, message.Sender, message.Content,+ message.Timestamp, message.IsFromMe, message.MediaType, message.Filename,+ message.URL, message.MediaKey, message.FileSHA256, message.FileEncSHA256,+ message.FileLength, message.CreatedAt, message.UpdatedAt,+ )++ return err+}++// StoreMessagesBatch creates or updates multiple messages in a single transaction+func (r *SQLiteRepository) StoreMessagesBatch(messages []*domainChatStorage.Message) error {+ if len(messages) == 0 {+ return nil+ }++ tx, err := r.db.Begin()+ if err != nil {+ return fmt.Errorf("failed to begin transaction: %w", err)+ }+ defer tx.Rollback()++ // Prepare the statement once for better performance+ stmt, err := tx.Prepare(`+ INSERT INTO messages (+ id, chat_jid, sender, content, timestamp, is_from_me,+ media_type, filename, url, media_key, file_sha256,+ file_enc_sha256, file_length, created_at, updated_at+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ ON CONFLICT(id, chat_jid) DO UPDATE SET+ sender = excluded.sender,+ content = excluded.content,+ timestamp = excluded.timestamp,+ is_from_me = excluded.is_from_me,+ media_type = excluded.media_type,+ filename = excluded.filename,+ url = excluded.url,+ media_key = excluded.media_key,+ file_sha256 = excluded.file_sha256,+ file_enc_sha256 = excluded.file_enc_sha256,+ file_length = excluded.file_length,+ updated_at = excluded.updated_at+ `)+ if err != nil {+ return fmt.Errorf("failed to prepare statement: %w", err)+ }+ defer stmt.Close()++ now := time.Now()+ for _, message := range messages {+ // Skip empty messages+ if message.Content == "" && message.MediaType == "" {+ continue+ }++ message.CreatedAt = now+ message.UpdatedAt = now++ _, err = stmt.Exec(+ message.ID, message.ChatJID, message.Sender, message.Content,+ message.Timestamp, message.IsFromMe, message.MediaType, message.Filename,+ message.URL, message.MediaKey, message.FileSHA256, message.FileEncSHA256,+ message.FileLength, message.CreatedAt, message.UpdatedAt,+ )+ if err != nil {+ return fmt.Errorf("failed to store message %s: %w", message.ID, err)+ }+ }++ return tx.Commit()+}++// GetMessages retrieves messages with filtering+func (r *SQLiteRepository) GetMessages(filter *domainChatStorage.MessageFilter) ([]*domainChatStorage.Message, error) {+ var conditions []string+ var args []any++ conditions = append(conditions, "chat_jid = ?")+ args = append(args, filter.ChatJID)++ if filter.StartTime != nil {+ conditions = append(conditions, "timestamp >= ?")+ args = append(args, *filter.StartTime)+ }++ if filter.EndTime != nil {+ conditions = append(conditions, "timestamp <= ?")+ args = append(args, *filter.EndTime)+ }++ if filter.MediaOnly {+ conditions = append(conditions, "media_type != ''")+ }++ if filter.IsFromMe != nil {+ conditions = append(conditions, "is_from_me = ?")+ args = append(args, *filter.IsFromMe)+ }++ query := `+ SELECT id, chat_jid, sender, content, timestamp, is_from_me,+ media_type, filename, url, media_key, file_sha256,+ file_enc_sha256, file_length, created_at, updated_at+ FROM messages+ WHERE ` + strings.Join(conditions, " AND ") + `+ ORDER BY timestamp DESC+ `++ // Safely add LIMIT and OFFSET using parameterized values+ if filter.Limit > 0 {+ // Validate limit to prevent abuse+ if filter.Limit > 1000 {+ filter.Limit = 1000+ }+ query += " LIMIT ?"+ args = append(args, filter.Limit)++ if filter.Offset > 0 {+ query += " OFFSET ?"+ args = append(args, filter.Offset)+ }+ }++ rows, err := r.db.Query(query, args...)+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ var messages []*domainChatStorage.Message+ for rows.Next() {+ message, err := r.scanMessage(rows)+ if err != nil {+ return nil, err+ }+ messages = append(messages, message)+ }++ return messages, rows.Err()+}++// SearchMessages performs database-level search for messages containing specific text+func (r *SQLiteRepository) SearchMessages(chatJID, searchText string, limit int) ([]*domainChatStorage.Message, error) {+ // Return empty results for empty search text+ if strings.TrimSpace(searchText) == "" {+ return []*domainChatStorage.Message{}, nil+ }++ var conditions []string+ var args []any++ // Always filter by chat JID+ conditions = append(conditions, "chat_jid = ?")+ args = append(args, chatJID)++ // Add search condition using LIKE operator for case-insensitive search+ conditions = append(conditions, "LOWER(content) LIKE ?")+ args = append(args, "%"+strings.ToLower(searchText)+"%")++ query := `+ SELECT id, chat_jid, sender, content, timestamp, is_from_me,+ media_type, filename, url, media_key, file_sha256,+ file_enc_sha256, file_length, created_at, updated_at+ FROM messages+ WHERE ` + strings.Join(conditions, " AND ") + `+ ORDER BY timestamp DESC+ `++ // Add limit with validation+ if limit > 0 {+ // Validate limit to prevent abuse+ if limit > 1000 {+ limit = 1000+ }+ query += " LIMIT ?"+ args = append(args, limit)+ }++ rows, err := r.db.Query(query, args...)+ if err != nil {+ return nil, fmt.Errorf("failed to search messages: %w", err)+ }+ defer rows.Close()++ var messages []*domainChatStorage.Message+ for rows.Next() {+ message, err := r.scanMessage(rows)+ if err != nil {+ return nil, fmt.Errorf("failed to scan message: %w", err)+ }+ messages = append(messages, message)+ }++ if err := rows.Err(); err != nil {+ return nil, fmt.Errorf("error iterating messages: %w", err)+ }++ return messages, nil+}++// DeleteMessage deletes a specific message+func (r *SQLiteRepository) DeleteMessage(id, chatJID string) error {+ _, err := r.db.Exec("DELETE FROM messages WHERE id = ? AND chat_jid = ?", id, chatJID)+ return err+}++// getCount is a private helper for count queries+func (r *SQLiteRepository) getCount(query string, args ...any) (int64, error) {+ var count int64+ err := r.db.QueryRow(query, args...).Scan(&count)+ return count, err+}++// scanMessage is a private helper for scanning message rows+func (r *SQLiteRepository) scanMessage(scanner interface{ Scan(...any) error }) (*domainChatStorage.Message, error) {+ message := &domainChatStorage.Message{}+ err := scanner.Scan(+ &message.ID, &message.ChatJID, &message.Sender, &message.Content,+ &message.Timestamp, &message.IsFromMe, &message.MediaType, &message.Filename,+ &message.URL, &message.MediaKey, &message.FileSHA256, &message.FileEncSHA256,+ &message.FileLength, &message.CreatedAt, &message.UpdatedAt,+ )+ return message, err+}++// scanChat is a private helper for scanning chat rows+func (r *SQLiteRepository) scanChat(scanner interface{ Scan(...any) error }) (*domainChatStorage.Chat, error) {+ chat := &domainChatStorage.Chat{}+ err := scanner.Scan(+ &chat.JID, &chat.Name, &chat.LastMessageTime, &chat.EphemeralExpiration,+ &chat.CreatedAt, &chat.UpdatedAt,+ )+ return chat, err+}++// GetChatMessageCount returns the number of messages in a chat+func (r *SQLiteRepository) GetChatMessageCount(chatJID string) (int64, error) {+ return r.getCount("SELECT COUNT(*) FROM messages WHERE chat_jid = ?", chatJID)+}++// GetTotalMessageCount returns the total number of messages+func (r *SQLiteRepository) GetTotalMessageCount() (int64, error) {+ return r.getCount("SELECT COUNT(*) FROM messages")+}++// GetTotalChatCount returns the total number of chats+func (r *SQLiteRepository) GetTotalChatCount() (int64, error) {+ return r.getCount("SELECT COUNT(*) FROM chats")+}++// TruncateAllChats deletes all chats from the database+// Note: Due to foreign key constraints, messages must be deleted first+func (r *SQLiteRepository) TruncateAllChats() error {+ tx, err := r.db.Begin()+ if err != nil {+ return fmt.Errorf("failed to begin transaction: %w", err)+ }+ defer tx.Rollback()++ // Delete messages first (foreign key constraint)+ _, err = tx.Exec("DELETE FROM messages")+ if err != nil {+ return fmt.Errorf("failed to delete messages: %w", err)+ }++ // Delete chats+ _, err = tx.Exec("DELETE FROM chats")+ if err != nil {+ return fmt.Errorf("failed to delete chats: %w", err)+ }++ return tx.Commit()+}++// GetChatNameWithPushName determines the appropriate name for a chat with pushname support+func (r *SQLiteRepository) GetChatNameWithPushName(jid types.JID, chatJID string, senderUser string, pushName string) string {+ // First, check if chat already exists with a name+ existingChat, err := r.GetChat(chatJID)+ if err == nil && existingChat != nil && existingChat.Name != "" {+ // If we have a pushname and the existing name is just a phone number/JID user, update it+ if pushName != "" && (existingChat.Name == jid.User || existingChat.Name == senderUser) {+ return pushName+ }+ return existingChat.Name+ }++ // Determine chat type and name+ var name string++ switch jid.Server {+ case "g.us":+ // This is a group chat+ // For now, use a generic name - this can be enhanced later with group info+ name = fmt.Sprintf("Group %s", jid.User)+ case "newsletter":+ // This is a newsletter/channel+ name = fmt.Sprintf("Newsletter %s", jid.User)+ default:+ // This is an individual contact+ // Priority: pushName > senderUser > JID user+ if pushName != "" && pushName != senderUser && pushName != jid.User {+ name = pushName+ } else if senderUser != "" {+ name = senderUser+ } else {+ name = jid.User+ }+ }++ return name+}++func (r *SQLiteRepository) CreateMessage(ctx context.Context, evt *events.Message) error {+ if evt == nil || evt.Message == nil {+ return nil+ }++ // Extract chat and sender information+ chatJID := evt.Info.Chat.String()+ // Store the full sender JID (user@server) to ensure consistency between received and sent messages+ sender := evt.Info.Sender.String()++ // Get appropriate chat name using pushname if available+ chatName := r.GetChatNameWithPushName(evt.Info.Chat, chatJID, evt.Info.Sender.User, evt.Info.PushName)++ // Extract ephemeral expiration+ ephemeralExpiration := utils.ExtractEphemeralExpiration(evt.Message)++ // Create or update chat+ chat := &domainChatStorage.Chat{+ JID: chatJID,+ Name: chatName,+ LastMessageTime: evt.Info.Timestamp,+ EphemeralExpiration: ephemeralExpiration,+ }++ // Store or update the chat+ if err := r.StoreChat(chat); err != nil {+ return fmt.Errorf("failed to store chat: %w", err)+ }++ // Extract message content and media info+ content := utils.ExtractMessageTextFromProto(evt.Message)+ mediaType, filename, url, mediaKey, fileSHA256, fileEncSHA256, fileLength := utils.ExtractMediaInfo(evt.Message)++ // Skip if there's no content and no media+ if content == "" && mediaType == "" {+ logrus.Debugf("Skipping message %s - no content or media", evt.Info.ID)+ return nil+ }++ // Create message object+ message := &domainChatStorage.Message{+ ID: evt.Info.ID,+ ChatJID: chatJID,+ Sender: sender,+ Content: content,+ Timestamp: evt.Info.Timestamp,+ IsFromMe: evt.Info.IsFromMe,+ MediaType: mediaType,+ Filename: filename,+ URL: url,+ MediaKey: mediaKey,+ FileSHA256: fileSHA256,+ FileEncSHA256: fileEncSHA256,+ FileLength: fileLength,+ }++ // Store the message+ return r.StoreMessage(message)+}++// GetStorageStatistics returns current storage statistics for logging purposes+func (r *SQLiteRepository) GetStorageStatistics() (chatCount int64, messageCount int64, err error) {+ // Count all chats using efficient query+ chatCount, err = r.GetTotalChatCount()+ if err != nil {+ return 0, 0, fmt.Errorf("failed to get chat count: %w", err)+ }++ // Count all messages+ messageCount, err = r.GetTotalMessageCount()+ if err != nil {+ return 0, 0, fmt.Errorf("failed to get message count: %w", err)+ }++ return chatCount, messageCount, nil+}++// TruncateAllDataWithLogging performs truncation with detailed logging+func (r *SQLiteRepository) TruncateAllDataWithLogging(logPrefix string) error {+ // Get statistics before truncation+ chatCount, messageCount, err := r.GetStorageStatistics()+ if err != nil {+ logrus.Warnf("[%s] Failed to get storage statistics before truncation: %v", logPrefix, err)+ } else {+ logrus.Infof("[%s] Storage before truncation: %d chats, %d messages", logPrefix, chatCount, messageCount)+ }++ // Perform truncation+ if err := r.TruncateAllChats(); err != nil {+ return fmt.Errorf("failed to truncate chatstorage data: %w", err)+ }++ // Verify truncation+ chatCountAfter, messageCountAfter, err := r.GetStorageStatistics()+ if err != nil {+ logrus.Warnf("[%s] Failed to get storage statistics after truncation: %v", logPrefix, err)+ } else {+ logrus.Infof("[%s] Storage after truncation: %d chats, %d messages", logPrefix, chatCountAfter, messageCountAfter)+ if chatCountAfter == 0 && messageCountAfter == 0 {+ logrus.Infof("[%s] ✅ Chatstorage truncation completed successfully", logPrefix)+ } else {+ logrus.Warnf("[%s] ⚠️ Truncation may not have completed fully", logPrefix)+ }+ }++ return nil+}++// StoreSentMessageWithContext stores a message that was sent by the user with context cancellation support+func (r *SQLiteRepository) StoreSentMessageWithContext(ctx context.Context, messageID string, senderJID string, recipientJID string, content string, timestamp time.Time) error {+ // Check if context is already cancelled before starting+ select {+ case <-ctx.Done():+ return ctx.Err()+ default:+ }++ // Ensure JID is properly formatted+ jid, err := types.ParseJID(recipientJID)+ if err != nil {+ return fmt.Errorf("invalid JID format: %w", err)+ }++ chatJID := jid.String()++ // Get chat name (no pushname available for sent messages)+ chatName := r.GetChatNameWithPushName(jid, chatJID, jid.User, "")++ // Check context again before database operations+ select {+ case <-ctx.Done():+ return ctx.Err()+ default:+ }++ // Store or update chat+ chat := &domainChatStorage.Chat{+ JID: chatJID,+ Name: chatName,+ LastMessageTime: timestamp,+ }++ if err := r.StoreChat(chat); err != nil {+ return fmt.Errorf("failed to store chat: %w", err)+ }++ // Check context one more time before storing message+ select {+ case <-ctx.Done():+ return ctx.Err()+ default:+ }++ // Store the sent message+ message := &domainChatStorage.Message{+ ID: messageID,+ ChatJID: chatJID,+ Sender: senderJID,+ Content: content,+ Timestamp: timestamp,+ IsFromMe: true,+ }++ return r.StoreMessage(message)+}++// _____________________________________________________________________________________________________________________++// initializeSchema creates or migrates the database schema+func (r *SQLiteRepository) InitializeSchema() error {+ // Get current schema version+ version, err := r.getSchemaVersion()+ if err != nil {+ return err+ }++ // Run migrations based on version+ migrations := r.getMigrations()+ for i := version; i < len(migrations); i++ {+ if err := r.runMigration(migrations[i], i+1); err != nil {+ return fmt.Errorf("failed to run migration %d: %w", i+1, err)+ }+ }++ return nil+}++// getSchemaVersion returns the current schema version+func (r *SQLiteRepository) getSchemaVersion() (int, error) {+ // Create schema_info table if it doesn't exist+ _, err := r.db.Exec(`+ CREATE TABLE IF NOT EXISTS schema_info (+ version INTEGER PRIMARY KEY DEFAULT 0,+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP+ )+ `)+ if err != nil {+ return 0, err+ }++ // Get current version+ var version int+ err = r.db.QueryRow("SELECT COALESCE(MAX(version), 0) FROM schema_info").Scan(&version)+ if err != nil {+ return 0, err+ }++ return version, nil+}++// runMigration executes a migration+func (r *SQLiteRepository) runMigration(migration string, version int) error {+ tx, err := r.db.Begin()+ if err != nil {+ return err+ }+ defer tx.Rollback()++ // Execute migration+ if _, err := tx.Exec(migration); err != nil {+ return err+ }++ // Update schema version+ if _, err := tx.Exec("INSERT OR REPLACE INTO schema_info (version) VALUES (?)", version); err != nil {+ return err+ }++ return tx.Commit()+}++// getMigrations returns all database migrations+func (r *SQLiteRepository) getMigrations() []string {+ return []string{+ // Migration 1: Initial schema with only chats and messages tables+ `+ -- Create chats table+ CREATE TABLE IF NOT EXISTS chats (+ jid TEXT PRIMARY KEY,+ name TEXT NOT NULL,+ last_message_time TIMESTAMP NOT NULL,+ ephemeral_expiration INTEGER DEFAULT 0,+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP+ );++ -- Create messages table+ CREATE TABLE IF NOT EXISTS messages (+ id TEXT NOT NULL,+ chat_jid TEXT NOT NULL,+ sender TEXT NOT NULL,+ content TEXT,+ timestamp TIMESTAMP NOT NULL,+ is_from_me BOOLEAN DEFAULT FALSE,+ media_type TEXT,+ filename TEXT,+ url TEXT,+ media_key BLOB,+ file_sha256 BLOB,+ file_enc_sha256 BLOB,+ file_length INTEGER DEFAULT 0,+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,+ PRIMARY KEY (id, chat_jid),+ FOREIGN KEY (chat_jid) REFERENCES chats(jid) ON DELETE CASCADE+ );++ -- Create indexes for performance+ CREATE INDEX IF NOT EXISTS idx_messages_chat_jid ON messages(chat_jid);+ CREATE INDEX IF NOT EXISTS idx_messages_timestamp ON messages(timestamp);+ CREATE INDEX IF NOT EXISTS idx_messages_media_type ON messages(media_type);+ CREATE INDEX IF NOT EXISTS idx_messages_sender ON messages(sender);+ CREATE INDEX IF NOT EXISTS idx_chats_last_message ON chats(last_message_time);+ CREATE INDEX IF NOT EXISTS idx_chats_name ON chats(name);+ `,++ // Migration 2: Add index for message ID lookups (performance optimization)+ `+ CREATE INDEX IF NOT EXISTS idx_messages_id ON messages(id);+ `,+ }+}diff --git a/src/infrastructure/chatstorage/whatsapp_integration.go b/src/infrastructure/chatstorage/whatsapp_integration.godeleted file mode 100644index f3b449ca..00000000--- a/src/infrastructure/chatstorage/whatsapp_integration.go+++ /dev/null@@ -1,407 +0,0 @@-package chatstorage--import (- "context"- "fmt"- "time"-- "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"- "github.com/sirupsen/logrus"- "go.mau.fi/whatsmeow"- "go.mau.fi/whatsmeow/types"- "go.mau.fi/whatsmeow/types/events"- waLog "go.mau.fi/whatsmeow/util/log"-)--// ChatStorage Logout Functionality-//-// This package provides comprehensive logout handling that truncates all chatstorage data-// when a user logs out. The truncation occurs in two scenarios:-//-// 1. REMOTE LOGOUT: When the user logs out from their WhatsApp phone/device-// - Triggered by the LoggedOut event from WhatsApp-// - Handled automatically by the event system-//-// 2. MANUAL LOGOUT: When the user calls the /app/logout API endpoint-// - Triggered by explicit API call-// - Initiated by user action through UI or REST API-//-// The truncation process:-// - Deletes all messages from the messages table-// - Deletes all chats from the chats table-// - Maintains referential integrity (messages deleted first due to foreign key constraints)-// - Provides detailed logging of the process-// - Continues with other cleanup operations even if chatstorage truncation fails-//-// Methods available:-// - TruncateAllData(): Basic truncation without logging-// - TruncateAllDataWithLogging(logPrefix): Truncation with detailed before/after statistics-// - GetStorageStatistics(): Get current chat and message counts-//-// Usage in logout process:-// The truncation is automatically integrated into the WhatsApp client logout handling-// and will be called whenever a logout occurs, ensuring no chat history persists-// after the user session ends.--// CreateMessage processes and stores a WhatsApp message event-func (s *Storage) CreateMessage(ctx context.Context, evt *events.Message) error {- if evt == nil || evt.Message == nil {- return nil- }-- // Extract chat and sender information- chatJID := evt.Info.Chat.String()- // Store the full sender JID (user@server) to ensure consistency between received and sent messages- sender := evt.Info.Sender.String()-- // Get appropriate chat name using pushname if available- chatName := s.GetChatNameWithPushName(evt.Info.Chat, chatJID, evt.Info.Sender.User, evt.Info.PushName)-- // Extract ephemeral expiration- ephemeralExpiration := utils.ExtractEphemeralExpiration(evt.Message)-- // Create or update chat- chat := &Chat{- JID: chatJID,- Name: chatName,- LastMessageTime: evt.Info.Timestamp,- EphemeralExpiration: ephemeralExpiration,- }-- // Store or update the chat- if err := s.repo.StoreChat(chat); err != nil {- return fmt.Errorf("failed to store chat: %w", err)- }-- // Extract message content and media info- content := utils.ExtractMessageTextFromProto(evt.Message)- mediaType, filename, url, mediaKey, fileSHA256, fileEncSHA256, fileLength := utils.ExtractMediaInfo(evt.Message)-- // Skip if there's no content and no media- if content == "" && mediaType == "" {- logrus.Debugf("Skipping message %s - no content or media", evt.Info.ID)- return nil- }-- // Create message object- message := &Message{- ID: evt.Info.ID,- ChatJID: chatJID,- Sender: sender,- Content: content,- Timestamp: evt.Info.Timestamp,- IsFromMe: evt.Info.IsFromMe,- MediaType: mediaType,- Filename: filename,- URL: url,- MediaKey: mediaKey,- FileSHA256: fileSHA256,- FileEncSHA256: fileEncSHA256,- FileLength: fileLength,- }-- // Store the message- return s.repo.StoreMessage(message)-}--// GetChatNameWithPushName determines the appropriate name for a chat with pushname support-func (s *Storage) GetChatNameWithPushName(jid types.JID, chatJID string, senderUser string, pushName string) string {- // First, check if chat already exists with a name- existingChat, err := s.repo.GetChat(chatJID)- if err == nil && existingChat != nil && existingChat.Name != "" {- // If we have a pushname and the existing name is just a phone number/JID user, update it- if pushName != "" && (existingChat.Name == jid.User || existingChat.Name == senderUser) {- return pushName- }- return existingChat.Name- }-- // Determine chat type and name- var name string-- switch jid.Server {- case "g.us":- // This is a group chat- // For now, use a generic name - this can be enhanced later with group info- name = fmt.Sprintf("Group %s", jid.User)- case "newsletter":- // This is a newsletter/channel- name = fmt.Sprintf("Newsletter %s", jid.User)- default:- // This is an individual contact- // Priority: pushName > senderUser > JID user- if pushName != "" && pushName != senderUser && pushName != jid.User {- name = pushName- } else if senderUser != "" {- name = senderUser- } else {- name = jid.User- }- }-- return name-}--// GetMessageHistory retrieves message history for a chat with pagination-func (s *Storage) GetMessageHistory(chatJID string, limit int, offset int) ([]*Message, error) {- filter := &MessageFilter{- ChatJID: chatJID,- Limit: limit,- Offset: offset,- }-- return s.repo.GetMessages(filter)-}--// GetRecentChats retrieves recent chats with their last message time-func (s *Storage) GetRecentChats(limit int) ([]*Chat, error) {- filter := &ChatFilter{- Limit: limit,- }-- return s.repo.GetChats(filter)-}--// SearchMessages searches for messages containing specific text using database-level filtering-func (s *Storage) SearchMessages(searchText string, chatJID string, limit int) ([]*Message, error) {- // Delegate to repository for efficient database-level search- return s.repo.SearchMessages(chatJID, searchText, limit)-}--// GetMediaMessages retrieves only media messages from a chat-func (s *Storage) GetMediaMessages(chatJID string, limit int) ([]*Message, error) {- filter := &MessageFilter{- ChatJID: chatJID,- Limit: limit,- MediaOnly: true,- }-- return s.repo.GetMessages(filter)-}--// DownloadMedia prepares media info for download-func (s *Storage) GetMediaDownloadInfo(messageID, chatJID string) (*MediaInfo, error) {- return s.repo.GetMediaInfo(messageID, chatJID)-}--// UpdateGroupInfo updates group chat information when available-func (s *Storage) UpdateGroupInfo(client *whatsmeow.Client, jid types.JID, logger waLog.Logger) error {- if jid.Server != "g.us" {- return nil // Not a group- }-- groupInfo, err := client.GetGroupInfo(jid)- if err != nil {- logger.Warnf("Failed to get group info for %s: %v", jid.String(), err)- return fmt.Errorf("failed to get group info: %w", err)- }-- // Update chat with group name- chat := &Chat{- JID: jid.String(),- Name: groupInfo.Name,- LastMessageTime: time.Now(),- }-- if err := s.repo.StoreChat(chat); err != nil {- logger.Errorf("Failed to store group chat %s: %v", jid.String(), err)- return fmt.Errorf("failed to store group chat: %w", err)- }-- logger.Infof("Updated group info for %s: %s", jid.String(), groupInfo.Name)- return nil-}--// StoreSentMessage stores a message that was sent by the user-func (s *Storage) StoreSentMessage(messageID string, senderJID string, recipientJID string, content string, timestamp time.Time) error {- // Ensure JID is properly formatted- jid, err := types.ParseJID(recipientJID)- if err != nil {- return fmt.Errorf("invalid JID format: %w", err)- }-- chatJID := jid.String()-- // Get chat name (no pushname available for sent messages)- chatName := s.GetChatNameWithPushName(jid, chatJID, jid.User, "")-- // Store or update chat- chat := &Chat{- JID: chatJID,- Name: chatName,- LastMessageTime: timestamp,- }-- if err := s.repo.StoreChat(chat); err != nil {- return fmt.Errorf("failed to store chat: %w", err)- }-- // Store the sent message- message := &Message{- ID: messageID,- ChatJID: chatJID,- Sender: senderJID,- Content: content,- Timestamp: timestamp,- IsFromMe: true,- }-- return s.repo.StoreMessage(message)-}--// StoreSentMessageWithContext stores a message that was sent by the user with context cancellation support-func (s *Storage) StoreSentMessageWithContext(ctx context.Context, messageID string, senderJID string, recipientJID string, content string, timestamp time.Time) error {- // Check if context is already cancelled before starting- select {- case <-ctx.Done():- return ctx.Err()- default:- }-- // Ensure JID is properly formatted- jid, err := types.ParseJID(recipientJID)- if err != nil {- return fmt.Errorf("invalid JID format: %w", err)- }-- chatJID := jid.String()-- // Get chat name (no pushname available for sent messages)- chatName := s.GetChatNameWithPushName(jid, chatJID, jid.User, "")-- // Check context again before database operations- select {- case <-ctx.Done():- return ctx.Err()- default:- }-- // Store or update chat- chat := &Chat{- JID: chatJID,- Name: chatName,- LastMessageTime: timestamp,- }-- if err := s.repo.StoreChat(chat); err != nil {- return fmt.Errorf("failed to store chat: %w", err)- }-- // Check context one more time before storing message- select {- case <-ctx.Done():- return ctx.Err()- default:- }-- // Store the sent message- message := &Message{- ID: messageID,- ChatJID: chatJID,- Sender: senderJID,- Content: content,- Timestamp: timestamp,- IsFromMe: true,- }-- return s.repo.StoreMessage(message)-}--// FindMessageByID retrieves a message by its ID for reply functionality-func (s *Storage) FindMessageByID(messageID string) (*Message, error) {- // Use the optimized GetMessageByID method- msg, err := s.repo.GetMessageByID(messageID)- if err != nil {- return nil, fmt.Errorf("failed to get message: %w", err)- }-- if msg == nil {- return nil, fmt.Errorf("message with ID %s not found", messageID)- }-- return msg, nil-}--// GetChat retrieves a chat by its JID-func (s *Storage) GetChat(jid string) (*Chat, error) {- return s.repo.GetChat(jid)-}--// StoreChat stores or updates a chat-func (s *Storage) StoreChat(chat *Chat) error {- return s.repo.StoreChat(chat)-}--// StoreMessage stores a message-func (s *Storage) StoreMessage(message *Message) error {- return s.repo.StoreMessage(message)-}--// StoreMessagesBatch stores multiple messages in a single transaction-func (s *Storage) StoreMessagesBatch(messages []*Message) error {- return s.repo.StoreMessagesBatch(messages)-}--// TruncateAllMessages deletes all messages from the chatstorage database-func (s *Storage) TruncateAllMessages() error {- return s.repo.TruncateAllMessages()-}--// TruncateAllChats deletes all chats from the chatstorage database-func (s *Storage) TruncateAllChats() error {- return s.repo.TruncateAllChats()-}--// TruncateAllData deletes all chats and messages from the chatstorage database-// This method should be called during user logout to clear all stored data-func (s *Storage) TruncateAllData() error {- return s.repo.TruncateAllData()-}--// GetStorageStatistics returns current storage statistics for logging purposes-func (s *Storage) GetStorageStatistics() (chatCount int64, messageCount int64, err error) {- // Count all chats using efficient query- chatCount, err = s.repo.GetTotalChatCount()- if err != nil {- return 0, 0, fmt.Errorf("failed to get chat count: %w", err)- }-- // Count all messages- messageCount, err = s.repo.GetTotalMessageCount()- if err != nil {- return 0, 0, fmt.Errorf("failed to get message count: %w", err)- }-- return chatCount, messageCount, nil-}--// TruncateAllDataWithLogging performs truncation with detailed logging-func (s *Storage) TruncateAllDataWithLogging(logPrefix string) error {- // Get statistics before truncation- chatCount, messageCount, err := s.GetStorageStatistics()- if err != nil {- logrus.Warnf("[%s] Failed to get storage statistics before truncation: %v", logPrefix, err)- } else {- logrus.Infof("[%s] Storage before truncation: %d chats, %d messages", logPrefix, chatCount, messageCount)- }-- // Perform truncation- if err := s.TruncateAllData(); err != nil {- return fmt.Errorf("failed to truncate chatstorage data: %w", err)- }-- // Verify truncation- chatCountAfter, messageCountAfter, err := s.GetStorageStatistics()- if err != nil {- logrus.Warnf("[%s] Failed to get storage statistics after truncation: %v", logPrefix, err)- } else {- logrus.Infof("[%s] Storage after truncation: %d chats, %d messages", logPrefix, chatCountAfter, messageCountAfter)- if chatCountAfter == 0 && messageCountAfter == 0 {- logrus.Infof("[%s] ✅ Chatstorage truncation completed successfully", logPrefix)- } else {- logrus.Warnf("[%s] ⚠️ Truncation may not have completed fully", logPrefix)- }- }-- return nil-}diff --git a/src/infrastructure/whatsapp/init.go b/src/infrastructure/whatsapp/init.goindex 5d4b381d..b3811b84 100644--- a/src/infrastructure/whatsapp/init.go+++ b/src/infrastructure/whatsapp/init.go@@ -11,7 +11,7 @@ import ("time""github.com/aldinokemal/go-whatsapp-web-multidevice/config"- "github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/chatstorage"+ domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"pkgError "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/error""github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils""github.com/aldinokemal/go-whatsapp-web-multidevice/ui/websocket"@@ -73,7 +73,7 @@ func initDatabase(ctx context.Context, dbLog waLog.Logger) (*sqlstore.Container,}// InitWaCLI initializes the WhatsApp client-func InitWaCLI(ctx context.Context, storeContainer *sqlstore.Container, chatStorageRepo *chatstorage.Storage) *whatsmeow.Client {+func InitWaCLI(ctx context.Context, storeContainer *sqlstore.Container, chatStorageRepo domainChatStorage.IChatStorageRepository) *whatsmeow.Client {device, err := storeContainer.GetFirstDevice(ctx)if err != nil {log.Errorf("Failed to get device: %v", err)@@ -94,7 +94,7 @@ func InitWaCLI(ctx context.Context, storeContainer *sqlstore.Container, chatStorcli = whatsmeow.NewClient(device, waLog.Stdout("Client", config.WhatsappLogLevel, true))cli.EnableAutoReconnect = truecli.AutoTrustIdentity = true- cli.AddEventHandler(func(rawEvt interface{}) {+ cli.AddEventHandler(func(rawEvt any) {handler(ctx, rawEvt, chatStorageRepo)})@@ -104,21 +104,22 @@ func InitWaCLI(ctx context.Context, storeContainer *sqlstore.Container, chatStor// 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) {+func UpdateGlobalClient(newCli *whatsmeow.Client, newDB *sqlstore.Container) {cli = newCli+ db = newDBlog.Infof("Global WhatsApp client updated successfully")}-// GetGlobalClient returns the current global client instance-func GetGlobalClient() *whatsmeow.Client {- return cli-}-// GetClient returns the current global client instance (alias for GetGlobalClient)func GetClient() *whatsmeow.Client {return cli}+// Get DB instance+func GetDB() *sqlstore.Container {+ return db+}+// GetConnectionStatus returns the current connection status of the global clientfunc GetConnectionStatus() (isConnected bool, isLoggedIn bool, deviceID string) {if cli == nil {@@ -197,7 +198,7 @@ func CleanupTemporaryFiles() error {}// ReinitializeWhatsAppComponents reinitializes database and client components-func ReinitializeWhatsAppComponents(ctx context.Context, chatStorageRepo *chatstorage.Storage) (*sqlstore.Container, *whatsmeow.Client, error) {+func ReinitializeWhatsAppComponents(ctx context.Context, chatStorageRepo domainChatStorage.IChatStorageRepository) (*sqlstore.Container, *whatsmeow.Client, error) {logrus.Info("[CLEANUP] Reinitializing database and client...")newDB := InitWaDB(ctx)@@ -213,7 +214,7 @@ func ReinitializeWhatsAppComponents(ctx context.Context, chatStorageRepo *chatst}// PerformCompleteCleanup performs all cleanup operations in the correct order-func PerformCompleteCleanup(ctx context.Context, logPrefix string, chatStorageRepo *chatstorage.Storage) (*sqlstore.Container, *whatsmeow.Client, error) {+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@@ -256,20 +257,20 @@ func PerformCompleteCleanup(ctx context.Context, logPrefix string, chatStorageRe// PerformCleanupAndUpdateGlobals is a convenience function that performs cleanup// and ensures global client synchronization-func PerformCleanupAndUpdateGlobals(ctx context.Context, logPrefix string, chatStorageRepo *chatstorage.Storage) (*sqlstore.Container, *whatsmeow.Client, error) {+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)+ UpdateGlobalClient(newCli, newDB)return newDB, newCli, nil}// handleRemoteLogout performs cleanup when user logs out from their phone-func handleRemoteLogout(ctx context.Context, chatStorageRepo *chatstorage.Storage) {+func handleRemoteLogout(ctx context.Context, chatStorageRepo domainChatStorage.IChatStorageRepository) {logrus.Info("[REMOTE_LOGOUT] User logged out from phone - starting cleanup...")logrus.Info("[REMOTE_LOGOUT] This will clear all WhatsApp session data and chat storage")@@ -294,7 +295,7 @@ func handleRemoteLogout(ctx context.Context, chatStorageRepo *chatstorage.Storag}// handler is the main event handler for WhatsApp events-func handler(ctx context.Context, rawEvt interface{}, chatStorageRepo *chatstorage.Storage) {+func handler(ctx context.Context, rawEvt any, chatStorageRepo domainChatStorage.IChatStorageRepository) {switch evt := rawEvt.(type) {case *events.DeleteForMe:handleDeleteForMe(ctx, evt, chatStorageRepo)@@ -323,11 +324,11 @@ func handler(ctx context.Context, rawEvt interface{}, chatStorageRepo *chatstora// Event handler functions-func handleDeleteForMe(ctx context.Context, evt *events.DeleteForMe, chatStorageRepo *chatstorage.Storage) {+func handleDeleteForMe(ctx context.Context, evt *events.DeleteForMe, chatStorageRepo domainChatStorage.IChatStorageRepository) {log.Infof("Deleted message %s for %s", evt.MessageID, evt.SenderJID.String())// Find the message to get its chat JID- message, err := chatStorageRepo.Repository().GetMessageByID(evt.MessageID)+ message, err := chatStorageRepo.GetMessageByID(evt.MessageID)if err != nil {log.Errorf("Failed to find message %s for deletion: %v", evt.MessageID, err)return@@ -339,7 +340,7 @@ func handleDeleteForMe(ctx context.Context, evt *events.DeleteForMe, chatStorage}// Delete the message from database- if err := chatStorageRepo.Repository().DeleteMessage(evt.MessageID, message.ChatJID); err != nil {+ if err := chatStorageRepo.DeleteMessage(evt.MessageID, message.ChatJID); err != nil {log.Errorf("Failed to delete message %s from database: %v", evt.MessageID, err)} else {log.Infof("Successfully deleted message %s from database", evt.MessageID)@@ -372,16 +373,9 @@ func handlePairSuccess(_ context.Context, evt *events.PairSuccess) {}}-func handleLoggedOut(ctx context.Context, chatStorageRepo *chatstorage.Storage) {+func handleLoggedOut(ctx context.Context, chatStorageRepo domainChatStorage.IChatStorageRepository) {logrus.Warn("[REMOTE_LOGOUT] Received LoggedOut event - user logged out from phone")- // Broadcast immediate notification about remote logout- websocket.Broadcast <- websocket.BroadcastMessage{- Code: "REMOTE_LOGOUT",- Message: "User logged out from phone - cleaning up session...",- Result: nil,- }-// Perform comprehensive cleanuphandleRemoteLogout(ctx, chatStorageRepo)@@ -411,7 +405,7 @@ func handleStreamReplaced(_ context.Context) {os.Exit(0)}-func handleMessage(ctx context.Context, evt *events.Message, chatStorageRepo *chatstorage.Storage) {+func handleMessage(ctx context.Context, evt *events.Message, chatStorageRepo domainChatStorage.IChatStorageRepository) {// Log message metadatametaParts := buildMessageMetaParts(evt)log.Infof("Received message %s from %s (%s): %+v",@@ -540,7 +534,7 @@ func handlePresence(_ context.Context, evt *events.Presence) {}}-func handleHistorySync(ctx context.Context, evt *events.HistorySync, chatStorageRepo *chatstorage.Storage) {+func handleHistorySync(ctx context.Context, evt *events.HistorySync, chatStorageRepo domainChatStorage.IChatStorageRepository) {id := atomic.AddInt32(&historySyncID, 1)fileName := fmt.Sprintf("%s/history-%d-%s-%d-%s.json",config.PathStorages,@@ -579,7 +573,7 @@ func handleAppState(_ context.Context, evt *events.AppState) {}// processHistorySync processes history sync data and stores messages in the database-func processHistorySync(ctx context.Context, data *waHistorySync.HistorySync, chatStorageRepo *chatstorage.Storage) error {+func processHistorySync(ctx context.Context, data *waHistorySync.HistorySync, chatStorageRepo domainChatStorage.IChatStorageRepository) error {if data == nil {return nil}@@ -602,7 +596,7 @@ func processHistorySync(ctx context.Context, data *waHistorySync.HistorySync, ch}// processConversationMessages processes and stores conversation messages from history sync-func processConversationMessages(_ context.Context, data *waHistorySync.HistorySync, chatStorageRepo *chatstorage.Storage) error {+func processConversationMessages(_ context.Context, data *waHistorySync.HistorySync, chatStorageRepo domainChatStorage.IChatStorageRepository) error {conversations := data.GetConversations()log.Infof("Processing %d conversations from history sync", len(conversations))@@ -632,7 +626,7 @@ func processConversationMessages(_ context.Context, data *waHistorySync.HistorySlog.Debugf("Processing %d messages for chat %s", len(messages), chatJID)// Collect messages for batch processing- var messageBatch []*chatstorage.Message+ var messageBatch []*domainChatStorage.Messagevar latestTimestamp time.Timefor _, histMsg := range messages {@@ -704,7 +698,7 @@ func processConversationMessages(_ context.Context, data *waHistorySync.HistoryS}// Create message object and add to batch- message := &chatstorage.Message{+ message := &domainChatStorage.Message{ID: messageID,ChatJID: chatJID,Sender: sender,@@ -725,7 +719,7 @@ func processConversationMessages(_ context.Context, data *waHistorySync.HistoryS// Store or update the chat with latest message timeif len(messageBatch) > 0 {- chat := &chatstorage.Chat{+ chat := &domainChatStorage.Chat{JID: chatJID,Name: chatName,LastMessageTime: latestTimestamp,@@ -751,7 +745,7 @@ func processConversationMessages(_ context.Context, data *waHistorySync.HistoryS}// processPushNames processes push names from history sync to update chat names-func processPushNames(_ context.Context, data *waHistorySync.HistorySync, chatStorageRepo *chatstorage.Storage) error {+func processPushNames(_ context.Context, data *waHistorySync.HistorySync, chatStorageRepo domainChatStorage.IChatStorageRepository) error {pushnames := data.GetPushnames()log.Infof("Processing %d push names from history sync", len(pushnames))diff --git a/src/infrastructure/whatsapp/webhook.go b/src/infrastructure/whatsapp/webhook.goindex 62262f46..8dc4f2c5 100644--- a/src/infrastructure/whatsapp/webhook.go+++ b/src/infrastructure/whatsapp/webhook.go@@ -13,7 +13,7 @@ import ("go.mau.fi/whatsmeow/types""github.com/aldinokemal/go-whatsapp-web-multidevice/config"- "github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/chatstorage"+ domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"pkgError "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/error""github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils""github.com/sirupsen/logrus"@@ -38,12 +38,12 @@ func forwardToWebhook(ctx context.Context, evt *events.Message) error {return nil}-func createPayload(ctx context.Context, evt *events.Message) (map[string]interface{}, error) {+func createPayload(ctx context.Context, evt *events.Message) (map[string]any, error) {message := utils.BuildEventMessage(evt)waReaction := utils.BuildEventReaction(evt)forwarded := utils.BuildForwarded(evt)- body := make(map[string]interface{})+ body := make(map[string]any)body["sender_id"] = evt.Info.Sender.Userbody["chat_id"] = evt.Info.Chat.User@@ -209,7 +209,7 @@ func createPayload(ctx context.Context, evt *events.Message) (map[string]interfareturn body, nil}-func submitWebhook(payload map[string]interface{}, url string) error {+func submitWebhook(payload map[string]any, url string) error {client := &http.Client{Timeout: 10 * time.Second}postBody, err := json.Marshal(payload)@@ -249,7 +249,7 @@ func submitWebhook(payload map[string]interface{}, url string) error {}// forwardDeleteToWebhook sends a delete event to webhook-func forwardDeleteToWebhook(ctx context.Context, evt *events.DeleteForMe, message *chatstorage.Message) error {+func forwardDeleteToWebhook(ctx context.Context, evt *events.DeleteForMe, message *domainChatStorage.Message) error {logrus.Info("Forwarding delete event to webhook:", config.WhatsappWebhook)payload, err := createDeletePayload(ctx, evt, message)if err != nil {@@ -267,18 +267,18 @@ func forwardDeleteToWebhook(ctx context.Context, evt *events.DeleteForMe, messag}// createDeletePayload creates a webhook payload for delete events-func createDeletePayload(ctx context.Context, evt *events.DeleteForMe, message *chatstorage.Message) (map[string]interface{}, error) {- body := make(map[string]interface{})+func createDeletePayload(_ context.Context, evt *events.DeleteForMe, message *domainChatStorage.Message) (map[string]any, error) {+ body := make(map[string]any)// Basic delete event informationbody["action"] = "message_deleted_for_me"body["deleted_message_id"] = evt.MessageIDbody["sender_id"] = evt.SenderJID.User- body["chat_id"] = message.ChatJIDbody["timestamp"] = time.Now().Format(time.RFC3339)// Include original message information if availableif message != nil {+ body["chat_id"] = message.ChatJIDbody["original_content"] = message.Contentbody["original_sender"] = message.Senderbody["original_timestamp"] = message.Timestamp.Format(time.RFC3339)diff --git a/src/pkg/utils/environment.go b/src/pkg/utils/environment.goindex 148bdcce..e2973b17 100644--- a/src/pkg/utils/environment.go+++ b/src/pkg/utils/environment.go@@ -28,7 +28,7 @@ func Env[T any](key string, defValue ...T) T {func MustHaveEnv(key string) string {env := viper.GetString(key)if env == "" {- logrus.Warn(context.Background(), map[string]interface{}{+ logrus.Warn(context.Background(), map[string]any{"field": key,}, "variable is not well set, reading from .env file")viper.SetConfigFile(".env")diff --git a/src/pkg/utils/general.go b/src/pkg/utils/general.goindex fea9ce14..9c7f3311 100644--- a/src/pkg/utils/general.go+++ b/src/pkg/utils/general.go@@ -440,7 +440,7 @@ func DownloadVideoFromURL(videoURL string) ([]byte, string, error) {}// FormatBusinessHourTime converts numeric time format (e.g., 600, 1200) to HH:MM format (e.g., "06:00", "12:00")-func FormatBusinessHourTime(timeValue interface{}) string {+func FormatBusinessHourTime(timeValue any) string {var timeInt intswitch v := timeValue.(type) {diff --git a/src/pkg/utils/response_test.go b/src/pkg/utils/response_test.goindex 1e61e2a3..d1d8e02c 100644--- a/src/pkg/utils/response_test.go+++ b/src/pkg/utils/response_test.go@@ -19,7 +19,7 @@ func (suite *ResponseTestSuite) TestResponseDataStruct() {Status: 200,Code: "SUCCESS",Message: "Operation completed successfully",- Results: map[string]interface{}{+ Results: map[string]any{"data": "test data","count": 10,},@@ -44,7 +44,7 @@ func (suite *ResponseTestSuite) TestResponseDataJSON() {assert.NoError(suite.T(), err)// Status field should be omitted from JSON (json:"-" tag)- var result map[string]interface{}+ var result map[string]anyerr = json.Unmarshal(jsonData, &result)assert.NoError(suite.T(), err)@@ -70,7 +70,7 @@ func (suite *ResponseTestSuite) TestResponseDataWithNilResults() {jsonData, err := json.Marshal(responseData)assert.NoError(suite.T(), err)- var result map[string]interface{}+ var result map[string]anyerr = json.Unmarshal(jsonData, &result)assert.NoError(suite.T(), err)@@ -94,7 +94,7 @@ func (suite *ResponseTestSuite) TestResponseDataWithEmptyResults() {jsonData, err := json.Marshal(responseData)assert.NoError(suite.T(), err)- var result map[string]interface{}+ var result map[string]anyerr = json.Unmarshal(jsonData, &result)assert.NoError(suite.T(), err)@@ -124,7 +124,7 @@ func (suite *ResponseTestSuite) TestResponseDataJSONUnmarshaling() {assert.NotNil(suite.T(), responseData.Results)// Check the Results content- results, ok := responseData.Results.(map[string]interface{})+ results, ok := responseData.Results.(map[string]any)assert.True(suite.T(), ok)assert.Equal(suite.T(), "detailed error message", results["error_details"])}diff --git a/src/usecase/app.go b/src/usecase/app.goindex 451e3198..95ded721 100644--- a/src/usecase/app.go+++ b/src/usecase/app.go@@ -9,7 +9,7 @@ import ("github.com/aldinokemal/go-whatsapp-web-multidevice/config"domainApp "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/app"- "github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/chatstorage"+ domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage""github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/whatsapp"pkgError "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/error""github.com/aldinokemal/go-whatsapp-web-multidevice/validations"@@ -19,17 +19,14 @@ import ("github.com/skip2/go-qrcode""go.mau.fi/libsignal/logger""go.mau.fi/whatsmeow"- "go.mau.fi/whatsmeow/store/sqlstore")type serviceApp struct {- db *sqlstore.Container- chatStorageRepo *chatstorage.Storage+ chatStorageRepo domainChatStorage.IChatStorageRepository}-func NewAppService(db *sqlstore.Container, chatStorageRepo *chatstorage.Storage) domainApp.IAppUsecase {+func NewAppService(chatStorageRepo domainChatStorage.IChatStorageRepository) domainApp.IAppUsecase {return &serviceApp{- db: db,chatStorageRepo: chatStorageRepo,}}@@ -42,7 +39,7 @@ func (service *serviceApp) Login(_ context.Context) (response domainApp.LoginRes// [DEBUG] Log database state before loginlogrus.Info("[DEBUG] Starting login process...")- devices, dbErr := service.db.GetAllDevices(context.Background())+ devices, dbErr := whatsapp.GetDB().GetAllDevices(context.Background())if dbErr != nil {logrus.Errorf("[DEBUG] Error getting devices before login: %v", dbErr)} else {@@ -122,7 +119,7 @@ func (service *serviceApp) Login(_ context.Context) (response domainApp.LoginResclient.IsConnected(), client.IsLoggedIn())// Ensure global client is synchronized with service client- whatsapp.UpdateGlobalClient(client)+ whatsapp.UpdateGlobalClient(client, whatsapp.GetDB())return response, nil}@@ -155,7 +152,7 @@ func (service *serviceApp) LoginWithCode(ctx context.Context, phoneNumber stringclient.IsConnected(), client.IsLoggedIn())// Ensure global client is synchronized with service client- whatsapp.UpdateGlobalClient(client)+ whatsapp.UpdateGlobalClient(client, whatsapp.GetDB())logrus.Infof("Successfully paired phone with code: %s", loginCode)return loginCode, nil@@ -164,7 +161,7 @@ func (service *serviceApp) LoginWithCode(ctx context.Context, phoneNumber stringfunc (service *serviceApp) Logout(ctx context.Context) (err error) {// [DEBUG] Log database state before logoutlogrus.Info("[DEBUG] Starting logout process...")- devices, dbErr := service.db.GetAllDevices(ctx)+ devices, dbErr := whatsapp.GetDB().GetAllDevices(ctx)if dbErr != nil {logrus.Errorf("[DEBUG] Error getting devices before logout: %v", dbErr)} else {@@ -185,7 +182,7 @@ func (service *serviceApp) Logout(ctx context.Context) (err error) {}// [DEBUG] Verify devices after logout- devices, dbErr = service.db.GetAllDevices(ctx)+ devices, dbErr = whatsapp.GetDB().GetAllDevices(ctx)if dbErr != nil {logrus.Errorf("[DEBUG] Error getting devices after logout: %v", dbErr)} else {@@ -193,14 +190,14 @@ func (service *serviceApp) Logout(ctx context.Context) (err error) {}// Perform complete cleanup with global client synchronization- newDB, _, err := whatsapp.PerformCleanupAndUpdateGlobals(ctx, "MANUAL_LOGOUT", service.chatStorageRepo)+ newDB, newCli, err := whatsapp.PerformCleanupAndUpdateGlobals(ctx, "MANUAL_LOGOUT", service.chatStorageRepo)if err != nil {logrus.Errorf("[DEBUG] Cleanup failed: %v", err)return err}// Update service references- service.db = newDB+ whatsapp.UpdateGlobalClient(newCli, newDB)logrus.Info("[DEBUG] Logout process completed successfully")return nil@@ -223,7 +220,7 @@ func (service *serviceApp) Reconnect(_ context.Context) (err error) {client.IsConnected(), client.IsLoggedIn())// Ensure global client is synchronized with service client- whatsapp.UpdateGlobalClient(client)+ whatsapp.UpdateGlobalClient(client, whatsapp.GetDB())logrus.Info("[DEBUG] Reconnect process completed successfully")return err@@ -234,7 +231,7 @@ func (service *serviceApp) FirstDevice(ctx context.Context) (response domainApp.return response, pkgError.ErrWaCLI}- devices, err := service.db.GetFirstDevice(ctx)+ devices, err := whatsapp.GetDB().GetFirstDevice(ctx)if err != nil {return response, err}@@ -254,7 +251,7 @@ func (service *serviceApp) FetchDevices(ctx context.Context) (response []domainAreturn response, pkgError.ErrWaCLI}- devices, err := service.db.GetAllDevices(ctx)+ devices, err := whatsapp.GetDB().GetAllDevices(ctx)if err != nil {return nil, err}diff --git a/src/usecase/chat.go b/src/usecase/chat.goindex 882b8278..abbf92f7 100644--- a/src/usecase/chat.go+++ b/src/usecase/chat.go@@ -6,7 +6,7 @@ import ("time"domainChat "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chat"- "github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/chatstorage"+ 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/utils""github.com/aldinokemal/go-whatsapp-web-multidevice/validations"@@ -15,10 +15,10 @@ import ()type serviceChat struct {- chatStorageRepo *chatstorage.Storage+ chatStorageRepo domainChatStorage.IChatStorageRepository}-func NewChatService(chatStorageRepo *chatstorage.Storage) domainChat.IChatUsecase {+func NewChatService(chatStorageRepo domainChatStorage.IChatStorageRepository) domainChat.IChatUsecase {return &serviceChat{chatStorageRepo: chatStorageRepo,}@@ -30,7 +30,7 @@ func (service serviceChat) ListChats(ctx context.Context, request domainChat.Lis}// Create filter from request- filter := &chatstorage.ChatFilter{+ filter := &domainChatStorage.ChatFilter{Limit: request.Limit,Offset: request.Offset,SearchName: request.Search,@@ -38,14 +38,14 @@ func (service serviceChat) ListChats(ctx context.Context, request domainChat.Lis}// Get chats from storage- chats, err := service.chatStorageRepo.Repository().GetChats(filter)+ chats, err := service.chatStorageRepo.GetChats(filter)if err != nil {logrus.WithError(err).Error("Failed to get chats from storage")return response, err}// Get total count for pagination- totalCount, err := service.chatStorageRepo.Repository().GetTotalChatCount()+ totalCount, err := service.chatStorageRepo.GetTotalChatCount()if err != nil {logrus.WithError(err).Error("Failed to get total chat count")// Continue with partial data@@ -91,7 +91,7 @@ func (service serviceChat) GetChatMessages(ctx context.Context, request domainCh}// Get chat info first- chat, err := service.chatStorageRepo.Repository().GetChat(request.ChatJID)+ chat, err := service.chatStorageRepo.GetChat(request.ChatJID)if err != nil {logrus.WithError(err).WithField("chat_jid", request.ChatJID).Error("Failed to get chat info")return response, err@@ -101,7 +101,7 @@ func (service serviceChat) GetChatMessages(ctx context.Context, request domainCh}// Create message filter from request- filter := &chatstorage.MessageFilter{+ filter := &domainChatStorage.MessageFilter{ChatJID: request.ChatJID,Limit: request.Limit,Offset: request.Offset,@@ -127,17 +127,17 @@ func (service serviceChat) GetChatMessages(ctx context.Context, request domainCh}// Get messages from storage- var messages []*chatstorage.Message+ var messages []*domainChatStorage.Messageif request.Search != "" {// Use search functionality if search query is provided- messages, err = service.chatStorageRepo.Repository().SearchMessages(request.ChatJID, request.Search, request.Limit)+ messages, err = service.chatStorageRepo.SearchMessages(request.ChatJID, request.Search, request.Limit)if err != nil {logrus.WithError(err).WithField("chat_jid", request.ChatJID).Error("Failed to search messages")return response, err}} else {// Use regular filter- messages, err = service.chatStorageRepo.Repository().GetMessages(filter)+ messages, err = service.chatStorageRepo.GetMessages(filter)if err != nil {logrus.WithError(err).WithField("chat_jid", request.ChatJID).Error("Failed to get messages")return response, err@@ -145,7 +145,7 @@ func (service serviceChat) GetChatMessages(ctx context.Context, request domainCh}// Get total message count for pagination- totalCount, err := service.chatStorageRepo.Repository().GetChatMessageCount(request.ChatJID)+ totalCount, err := service.chatStorageRepo.GetChatMessageCount(request.ChatJID)if err != nil {logrus.WithError(err).WithField("chat_jid", request.ChatJID).Error("Failed to get message count")// Continue with partial datadiff --git a/src/usecase/message.go b/src/usecase/message.goindex d4ad4a9d..83ff901b 100644--- a/src/usecase/message.go+++ b/src/usecase/message.go@@ -5,8 +5,8 @@ import ("fmt""time"+ domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"domainMessage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/message"- "github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/chatstorage""github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/whatsapp""github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils""github.com/aldinokemal/go-whatsapp-web-multidevice/validations"@@ -20,10 +20,10 @@ import ()type serviceMessage struct {- chatStorageRepo *chatstorage.Storage+ chatStorageRepo domainChatStorage.IChatStorageRepository}-func NewMessageService(chatStorageRepo *chatstorage.Storage) domainMessage.IMessageUsecase {+func NewMessageService(chatStorageRepo domainChatStorage.IChatStorageRepository) domainMessage.IMessageUsecase {return &serviceMessage{chatStorageRepo: chatStorageRepo,}@@ -43,7 +43,7 @@ func (service serviceMessage) MarkAsRead(ctx context.Context, request domainMessreturn response, err}- logrus.Info(map[string]interface{}{+ logrus.Info(map[string]any{"phone": request.Phone,"message_id": request.MessageID,"chat": dataWaRecipient.String(),diff --git a/src/usecase/send.go b/src/usecase/send.goindex f15aad93..21e00b45 100644--- a/src/usecase/send.go+++ b/src/usecase/send.go@@ -13,8 +13,8 @@ import ("github.com/aldinokemal/go-whatsapp-web-multidevice/config""github.com/aldinokemal/go-whatsapp-web-multidevice/domains/app"+ domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"domainSend "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/send"- "github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/chatstorage""github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/whatsapp"pkgError "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/error""github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"@@ -32,10 +32,10 @@ import (type serviceSend struct {appService app.IAppUsecase- chatStorageRepo *chatstorage.Storage+ chatStorageRepo domainChatStorage.IChatStorageRepository}-func NewSendService(appService app.IAppUsecase, chatStorageRepo *chatstorage.Storage) domainSend.ISendUsecase {+func NewSendService(appService app.IAppUsecase, chatStorageRepo domainChatStorage.IChatStorageRepository) domainSend.ISendUsecase {return &serviceSend{appService: appService,chatStorageRepo: chatStorageRepo,@@ -109,8 +109,10 @@ func (service serviceSend) SendText(ctx context.Context, request domainSend.Mess// Reply messageif request.ReplyMessageID != nil && *request.ReplyMessageID != "" {- message, err := service.chatStorageRepo.FindMessageByID(*request.ReplyMessageID)- if err == nil && message != nil { // Only set reply context if we found the message+ message, err := service.chatStorageRepo.GetMessageByID(*request.ReplyMessageID)+ if err != nil {+ logrus.Warnf("Error retrieving reply message ID %s: %v, continuing without reply context", *request.ReplyMessageID, err)+ } else if message != nil { // Only set reply context if we found the message// Ensure we use a full JID (user@server) for the Participant field// Use the sender JID from storage as-is. Modern storage should already provide// fully-qualified JIDs (e.g., [email protected] or [email protected]). Avoid mutatingdiff --git a/src/views/index.html b/src/views/index.htmlindex a7207757..9e3978ea 100644--- a/src/views/index.html+++ b/src/views/index.html@@ -316,12 +316,6 @@case 'LIST_DEVICES':this.connected_devices = message.resultbreak;- case 'REMOTE_LOGOUT':- // Handle remote logout from phone- showErrorInfo('⚠️ ' + message.message)- this.connected_devices = null- console.log('[REMOTE_LOGOUT] User logged out from phone:', message)- break;case 'LOGOUT_COMPLETE':// Handle successful cleanup after remote logoutshowSuccessInfo('✅ ' + message.message)