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
Bug/large groups (#348)
Almog Baku813fde0425d4
diff --git a/src/.env.example b/src/.env.exampleindex d0dafa88..fe4a984d 100644--- a/src/.env.example+++ b/src/.env.example@@ -6,6 +6,7 @@ APP_BASIC_AUTH=user1:pass1,user2:pass2# Database SettingsDB_URI="file:storages/whatsapp.db?_foreign_keys=on"+DB_KEYS_URI="file::memory:?cache=shared&_foreign_keys=on"# WhatsApp SettingsWHATSAPP_AUTO_REPLY="Auto reply message"diff --git a/src/cmd/root.go b/src/cmd/root.goindex 5b216e85..a113aea5 100644--- a/src/cmd/root.go+++ b/src/cmd/root.go@@ -5,6 +5,7 @@ import ("database/sql""embed""fmt"+ "go.mau.fi/whatsmeow/store/sqlstore""os""strings""time"@@ -22,14 +23,12 @@ import ("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/usecase"+ _ "github.com/lib/pq"+ _ "github.com/mattn/go-sqlite3""github.com/sirupsen/logrus""github.com/spf13/cobra""github.com/spf13/viper""go.mau.fi/whatsmeow"- "go.mau.fi/whatsmeow/store/sqlstore"-- _ "github.com/lib/pq"- _ "github.com/mattn/go-sqlite3")var (@@ -38,7 +37,6 @@ var (whatsappCli *whatsmeow.Client- whatsappDB *sqlstore.Container// Chat StoragechatStorageDB *sql.DB@@ -98,6 +96,9 @@ func initEnvConfig() {if envDBURI := viper.GetString("db_uri"); envDBURI != "" {config.DBURI = envDBURI}+ if envDBKEYSURI := viper.GetString("db_keys_uri"); envDBKEYSURI != "" {+ config.DBKeysURI = envDBKEYSURI+ }// WhatsApp settingsif envAutoReply := viper.GetString("whatsapp_auto_reply"); envAutoReply != "" {@@ -153,6 +154,12 @@ func initFlags() {config.DBURI,`the database uri to store the connection data database uri (by default, we'll use sqlite3 under storages/whatsapp.db). database uri --db-uri <string> | example: --db-uri="file:storages/whatsapp.db?_foreign_keys=on or postgres://user:password@localhost:5432/whatsapp"`,)+ rootCmd.PersistentFlags().StringVarP(+ &config.DBKeysURI,+ "db-keys-uri", "",+ config.DBKeysURI,+ `the database uri to store the keys database uri (by default, we'll use the same database uri). database uri --db-keys-uri <string> | example: --db-keys-uri="file::memory:?cache=shared&_foreign_keys=on"`,+ )// WhatsApp flagsrootCmd.PersistentFlags().StringVarP(@@ -227,14 +234,20 @@ func initApp() {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)+ whatsappDB := whatsapp.InitWaDB(ctx, config.DBURI)+ var keysDB *sqlstore.Container+ if config.DBKeysURI != "" {+ keysDB = whatsapp.InitWaDB(ctx, config.DBKeysURI)+ }++ whatsapp.InitWaCLI(ctx, whatsappDB, keysDB, chatStorageRepo)// UsecaseappUsecase = usecase.NewAppService(chatStorageRepo)diff --git a/src/config/settings.go b/src/config/settings.goindex f18ab0d6..74edcb6f 100644--- a/src/config/settings.go+++ b/src/config/settings.go@@ -21,6 +21,7 @@ var (PathStorages = "storages"DBURI = "file:storages/whatsapp.db?_foreign_keys=on"+ DBKeysURI = ""WhatsappAutoReplyMessage stringWhatsappAutoMarkRead = false // Auto-mark incoming messages as readdiff --git a/src/infrastructure/whatsapp/init.go b/src/infrastructure/whatsapp/init.goindex 9fcae782..04ac7245 100644--- a/src/infrastructure/whatsapp/init.go+++ b/src/infrastructure/whatsapp/init.go@@ -4,6 +4,7 @@ import ("context""encoding/json""fmt"+ "go.mau.fi/whatsmeow/proto/waHistorySync""os""path/filepath""strings"@@ -19,7 +20,6 @@ import ("go.mau.fi/whatsmeow""go.mau.fi/whatsmeow/appstate""go.mau.fi/whatsmeow/proto/waE2E"- "go.mau.fi/whatsmeow/proto/waHistorySync""go.mau.fi/whatsmeow/store""go.mau.fi/whatsmeow/store/sqlstore""go.mau.fi/whatsmeow/types"@@ -39,41 +39,68 @@ type ExtractedMedia struct {var (cli *whatsmeow.Clientdb *sqlstore.Container // Add global database reference for cleanup+ keysDB *sqlstore.Containerlog waLog.LoggerhistorySyncID int32startupTime = time.Now().Unix())// InitWaDB initializes the WhatsApp database connection-func InitWaDB(ctx context.Context) *sqlstore.Container {+func InitWaDB(ctx context.Context, DBURI string) *sqlstore.Container {log = waLog.Stdout("Main", config.WhatsappLogLevel, true)dbLog := waLog.Stdout("Database", config.WhatsappLogLevel, true)- storeContainer, err := initDatabase(ctx, dbLog)+ storeContainer, err := initDatabase(ctx, dbLog, DBURI)if err != nil {log.Errorf("Database initialization error: %v", err)panic(pkgError.InternalServerError(fmt.Sprintf("Database initialization error: %v", err)))}- // Set global database reference for remote logout cleanup- db = storeContainer-return storeContainer}// initDatabase creates and returns a database store container based on the configured URI-func initDatabase(ctx context.Context, dbLog waLog.Logger) (*sqlstore.Container, error) {- if strings.HasPrefix(config.DBURI, "file:") {- return sqlstore.New(ctx, "sqlite3", config.DBURI, dbLog)- } else if strings.HasPrefix(config.DBURI, "postgres:") {- return sqlstore.New(ctx, "postgres", config.DBURI, dbLog)+func initDatabase(ctx context.Context, dbLog waLog.Logger, DBURI string) (*sqlstore.Container, error) {+ if strings.HasPrefix(DBURI, "file:") {+ return sqlstore.New(ctx, "sqlite3", DBURI, dbLog)+ } else if strings.HasPrefix(DBURI, "postgres:") {+ return sqlstore.New(ctx, "postgres", DBURI, dbLog)+ }++ return nil, fmt.Errorf("unknown database type: %s. Currently only sqlite3(file:) and postgres are supported", DBURI)+}++func syncKeysDevice(ctx context.Context, db, keysDB *sqlstore.Container) {+ if keysDB == nil {+ return}- return nil, fmt.Errorf("unknown database type: %s. Currently only sqlite3(file:) and postgres are supported", config.DBURI)+ dev, err := db.GetFirstDevice(ctx)+ if err != nil {+ log.Errorf("Failed to get all devices: %v", err)+ } else {+ found := false+ if devs, err := keysDB.GetAllDevices(ctx); err != nil {+ log.Errorf("Failed to get all devices: %v", err)+ } else {+ for _, d := range devs {+ if d.ID == dev.ID {+ found = true+ break+ } else {+ keysDB.DeleteDevice(ctx, d)+ }+ }++ if !found {+ keysDB.PutDevice(ctx, dev)+ }+ }+ }}// InitWaCLI initializes the WhatsApp client-func InitWaCLI(ctx context.Context, storeContainer *sqlstore.Container, chatStorageRepo domainChatStorage.IChatStorageRepository) *whatsmeow.Client {+func InitWaCLI(ctx context.Context, storeContainer, keysStoreContainer *sqlstore.Container, chatStorageRepo domainChatStorage.IChatStorageRepository) *whatsmeow.Client {device, err := storeContainer.GetFirstDevice(ctx)if err != nil {log.Errorf("Failed to get device: %v", err)@@ -90,11 +117,29 @@ func InitWaCLI(ctx context.Context, storeContainer *sqlstore.Container, chatStorstore.DeviceProps.PlatformType = &config.AppPlatformstore.DeviceProps.Os = &osName+ // Set global database reference for remote logout cleanup+ db = storeContainer+ keysDB = keysStoreContainer++ // Configure a separated database for accelerating encryption caching+ if keysDB != nil && device.ID != nil {+ innerStore := sqlstore.NewSQLStore(keysStoreContainer, *device.ID)++ syncKeysDevice(ctx, db, keysDB)+ device.Identities = innerStore+ device.Sessions = innerStore+ device.PreKeys = innerStore+ device.SenderKeys = innerStore+ device.MsgSecrets = innerStore+ device.PrivacyTokens = innerStore+ }+// Create and configure the clientcli = whatsmeow.NewClient(device, waLog.Stdout("Client", config.WhatsappLogLevel, true))cli.EnableAutoReconnect = truecli.AutoTrustIdentity = true- cli.AddEventHandler(func(rawEvt any) {++ cli.AddEventHandler(func(rawEvt interface{}) {handler(ctx, rawEvt, chatStorageRepo)})@@ -201,8 +246,11 @@ func CleanupTemporaryFiles() error {func ReinitializeWhatsAppComponents(ctx context.Context, chatStorageRepo domainChatStorage.IChatStorageRepository) (*sqlstore.Container, *whatsmeow.Client, error) {logrus.Info("[CLEANUP] Reinitializing database and client...")- newDB := InitWaDB(ctx)- newCli := InitWaCLI(ctx, newDB, chatStorageRepo)+ newDB := InitWaDB(ctx, config.DBURI)+ if config.DBKeysURI != "" {+ keysDB = InitWaDB(ctx, config.DBKeysURI)+ }+ newCli := InitWaCLI(ctx, newDB, keysDB, chatStorageRepo)// Update global referencesdb = newDB@@ -366,11 +414,12 @@ func handleAppStateSyncComplete(_ context.Context, evt *events.AppStateSyncCompl}}-func handlePairSuccess(_ context.Context, evt *events.PairSuccess) {+func handlePairSuccess(ctx context.Context, evt *events.PairSuccess) {websocket.Broadcast <- websocket.BroadcastMessage{Code: "LOGIN_SUCCESS",Message: fmt.Sprintf("Successfully pair with %s", evt.ID.String()),}+ syncKeysDevice(ctx, db, keysDB)}func handleLoggedOut(ctx context.Context, chatStorageRepo domainChatStorage.IChatStorageRepository) {