Skip to content

GOWA - WhatsApp REST API with support for UI, Multi Account, Webhooks, and MCP, and Chatwoot. Built with Golang for efficient memory use.

feat: chatwoot integration

Aldino Kemal44a128c78a76
diff --git a/readme.md b/readme.md
index d5bb659a..ac62de89 100644
--- a/readme.md
+++ b/readme.md
@@ -194,6 +194,11 @@ To use environment variables:
| `WHATSAPP_WEBHOOK_INSECURE_SKIP_VERIFY` | Skip TLS verification for webhooks (insecure) | `false` | `WHATSAPP_WEBHOOK_INSECURE_SKIP_VERIFY=true` |
| `WHATSAPP_WEBHOOK_EVENTS` | Whitelist of events to forward (comma-separated, empty = all) | - | `WHATSAPP_WEBHOOK_EVENTS=message,message.ack` |
| `WHATSAPP_ACCOUNT_VALIDATION` | Enable account validation | `true` | `WHATSAPP_ACCOUNT_VALIDATION=false` |
+| `CHATWOOT_ENABLED` | Enable Chatwoot integration | `false` | `CHATWOOT_ENABLED=true` |
+| `CHATWOOT_URL` | Chatwoot instance URL | - | `CHATWOOT_URL=https://app.chatwoot.com` |
+| `CHATWOOT_API_TOKEN` | Chatwoot API access token | - | `CHATWOOT_API_TOKEN=your-api-token` |
+| `CHATWOOT_ACCOUNT_ID` | Chatwoot account ID | - | `CHATWOOT_ACCOUNT_ID=12345` |
+| `CHATWOOT_INBOX_ID` | Chatwoot inbox ID | - | `CHATWOOT_INBOX_ID=67890` |
Note: Command-line flags will override any values set in environment variables or `.env` file.
diff --git a/src/.env.example b/src/.env.example
index 6bc07791..70b9b435 100644
--- a/src/.env.example
+++ b/src/.env.example
@@ -19,4 +19,12 @@ WHATSAPP_WEBHOOK=https://webhook.site/07b69616-5943-4c7f-a8be-db4819df699e,https
WHATSAPP_WEBHOOK_SECRET=super-secret-key
WHATSAPP_WEBHOOK_INSECURE_SKIP_VERIFY=false
WHATSAPP_WEBHOOK_EVENTS=message,message.reaction,message.revoked,message.edited,message.ack,message.deleted,group.participants
-WHATSAPP_ACCOUNT_VALIDATION=true
\ No newline at end of file
+WHATSAPP_ACCOUNT_VALIDATION=true
+WHATSAPP_CHAT_STORAGE=true
+
+# Chatwoot Integration
+CHATWOOT_ENABLED=false
+CHATWOOT_URL=https://app.chatwoot.com
+CHATWOOT_API_TOKEN=xxxxxxxx
+CHATWOOT_ACCOUNT_ID=111111
+CHATWOOT_INBOX_ID=000000
diff --git a/src/cmd/rest.go b/src/cmd/rest.go
index b7bcc958..6bb003e3 100644
--- a/src/cmd/rest.go
+++ b/src/cmd/rest.go
@@ -109,6 +109,11 @@ func restServer(_ *cobra.Command, _ []string) {
rest.InitRestGroup(r, groupUsecase)
rest.InitRestNewsletter(r, newsletterUsecase)
websocket.RegisterRoutes(r, appUsecase)
+
+ if config.ChatwootEnabled {
+ chatwootHandler := rest.NewChatwootHandler(appUsecase, sendUsecase)
+ r.Post("/chatwoot/webhook", chatwootHandler.HandleWebhook)
+ }
}
// Device management routes (no device_id required)
diff --git a/src/cmd/root.go b/src/cmd/root.go
index 47845a2e..23be9efb 100644
--- a/src/cmd/root.go
+++ b/src/cmd/root.go
@@ -140,6 +140,23 @@ func initEnvConfig() {
if viper.IsSet("whatsapp_account_validation") {
config.WhatsappAccountValidation = viper.GetBool("whatsapp_account_validation")
}
+
+ // Chatwoot settings
+ if viper.IsSet("chatwoot_enabled") {
+ config.ChatwootEnabled = viper.GetBool("chatwoot_enabled")
+ }
+ if envChatwootURL := viper.GetString("chatwoot_url"); envChatwootURL != "" {
+ config.ChatwootURL = envChatwootURL
+ }
+ if envChatwootAPIToken := viper.GetString("chatwoot_api_token"); envChatwootAPIToken != "" {
+ config.ChatwootAPIToken = envChatwootAPIToken
+ }
+ if viper.IsSet("chatwoot_account_id") {
+ config.ChatwootAccountID = viper.GetInt("chatwoot_account_id")
+ }
+ if viper.IsSet("chatwoot_inbox_id") {
+ config.ChatwootInboxID = viper.GetInt("chatwoot_inbox_id")
+ }
}
func initFlags() {
@@ -252,6 +269,14 @@ func initFlags() {
config.WhatsappAccountValidation,
`enable or disable account validation --account-validation <true/false> | example: --account-validation=true`,
)
+
+ // Chatwoot flags
+ rootCmd.PersistentFlags().BoolVarP(
+ &config.ChatwootEnabled,
+ "chatwoot-enabled", "",
+ config.ChatwootEnabled,
+ `enable Chatwoot integration --chatwoot-enabled <true/false> | example: --chatwoot-enabled=true`,
+ )
}
func initChatStorage() (*sql.DB, error) {
diff --git a/src/config/settings.go b/src/config/settings.go
index 5c8ff683..d17d1579 100644
--- a/src/config/settings.go
+++ b/src/config/settings.go
@@ -5,7 +5,7 @@ import (
)
var (
- AppVersion = "v8.1.2"
+ AppVersion = "v8.2.0"
AppPort = "3000"
AppHost = "0.0.0.0"
AppDebug = false
@@ -45,4 +45,10 @@ var (
ChatStorageURI = "file:storages/chatstorage.db"
ChatStorageEnableForeignKeys = true
ChatStorageEnableWAL = true
+
+ ChatwootEnabled = false
+ ChatwootURL = ""
+ ChatwootAPIToken = ""
+ ChatwootAccountID = 0
+ ChatwootInboxID = 0
)
diff --git a/src/domains/send/file.go b/src/domains/send/file.go
index 347fb106..af01ffca 100644
--- a/src/domains/send/file.go
+++ b/src/domains/send/file.go
@@ -5,5 +5,6 @@ import "mime/multipart"
type FileRequest struct {
BaseRequest
File *multipart.FileHeader `json:"file" form:"file"`
+ FileURL *string `json:"file_url" form:"file_url"`
Caption string `json:"caption" form:"caption"`
}
diff --git a/src/infrastructure/chatwoot/client.go b/src/infrastructure/chatwoot/client.go
new file mode 100644
index 00000000..f576763e
--- /dev/null
+++ b/src/infrastructure/chatwoot/client.go
@@ -0,0 +1,503 @@
+package chatwoot
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "io"
+ "mime"
+ "mime/multipart"
+ "net/http"
+ "net/textproto"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/config"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
+ "github.com/sirupsen/logrus"
+)
+
+type Client struct {
+ BaseURL string
+ APIToken string
+ AccountID int
+ InboxID int
+ HTTPClient *http.Client
+}
+
+var (
+ defaultClient *Client
+ defaultClientOnce sync.Once
+)
+
+// GetDefaultClient returns a shared Chatwoot client instance.
+// Uses lazy initialization with sync.Once for thread safety.
+func GetDefaultClient() *Client {
+ defaultClientOnce.Do(func() {
+ defaultClient = NewClient()
+ })
+ return defaultClient
+}
+
+func NewClient() *Client {
+ return &Client{
+ BaseURL: strings.TrimRight(config.ChatwootURL, "/"),
+ APIToken: config.ChatwootAPIToken,
+ AccountID: config.ChatwootAccountID,
+ InboxID: config.ChatwootInboxID,
+ HTTPClient: &http.Client{
+ Timeout: 30 * time.Second,
+ },
+ }
+}
+
+func (c *Client) IsConfigured() bool {
+ return c.BaseURL != "" && c.APIToken != "" && c.AccountID != 0 && c.InboxID != 0
+}
+
+// doRequest executes an HTTP request with common headers and error handling.
+// It marshals the payload to JSON (if provided), sets auth headers, executes the request,
+// and decodes the response into result (if provided).
+func (c *Client) doRequest(method, endpoint string, payload interface{}, result interface{}) ([]byte, error) {
+ var body io.Reader
+ if payload != nil {
+ jsonPayload, err := json.Marshal(payload)
+ if err != nil {
+ return nil, fmt.Errorf("failed to marshal payload: %w", err)
+ }
+ body = bytes.NewBuffer(jsonPayload)
+ }
+
+ req, err := http.NewRequest(method, endpoint, body)
+ if err != nil {
+ return nil, err
+ }
+
+ if payload != nil {
+ req.Header.Set("Content-Type", "application/json")
+ }
+ req.Header.Set("api_access_token", c.APIToken)
+
+ resp, err := c.HTTPClient.Do(req)
+ if err != nil {
+ return nil, err
+ }
+ defer resp.Body.Close()
+
+ bodyBytes, err := io.ReadAll(resp.Body)
+ if err != nil {
+ return nil, fmt.Errorf("failed to read response body: %w", err)
+ }
+
+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {
+ return bodyBytes, fmt.Errorf("request failed: status %d body %s", resp.StatusCode, string(bodyBytes))
+ }
+
+ if result != nil && len(bodyBytes) > 0 {
+ if err := json.Unmarshal(bodyBytes, result); err != nil {
+ return bodyBytes, fmt.Errorf("failed to decode response: %w", err)
+ }
+ }
+
+ return bodyBytes, nil
+}
+
+func (c *Client) FindContactByIdentifier(identifier string, isGroup bool) (*Contact, error) {
+ endpoint := fmt.Sprintf("%s/api/v1/accounts/%d/contacts/search", c.BaseURL, c.AccountID)
+ req, err := http.NewRequest("GET", endpoint, nil)
+ if err != nil {
+ return nil, err
+ }
+
+ // For groups, search by the identifier directly
+ // For private chats, add + prefix for E.164 format
+ searchTerm := identifier
+ if !isGroup {
+ searchTerm = utils.NormalizePhoneE164(identifier)
+ }
+
+ q := req.URL.Query()
+ q.Add("q", searchTerm)
+ req.URL.RawQuery = q.Encode()
+ req.Header.Set("api_access_token", c.APIToken)
+
+ resp, err := c.HTTPClient.Do(req)
+ if err != nil {
+ return nil, err
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != http.StatusOK {
+ return nil, fmt.Errorf("failed to search contact: status %d", resp.StatusCode)
+ }
+
+ var result struct {
+ Payload []Contact `json:"payload"`
+ }
+ if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
+ return nil, err
+ }
+
+ // For groups, match by Identifier field or custom attribute waha_whatsapp_jid
+ // For private chats, match by phone number
+ for _, contact := range result.Payload {
+ if isGroup {
+ // Check Identifier field first
+ if contact.Identifier == identifier {
+ return &contact, nil
+ }
+ // Fallback: check custom attributes for group JID
+ if jid, ok := contact.CustomAttributes["waha_whatsapp_jid"].(string); ok && jid == identifier {
+ return &contact, nil
+ }
+ } else {
+ if contact.PhoneNumber == searchTerm {
+ return &contact, nil
+ }
+ }
+ }
+
+ return nil, nil
+}
+
+func (c *Client) CreateContact(name, identifier string, isGroup bool) (*Contact, error) {
+ endpoint := fmt.Sprintf("%s/api/v1/accounts/%d/contacts", c.BaseURL, c.AccountID)
+
+ // For groups, use Identifier field
+ // For private chats, use E.164 phone format
+ var phoneNumber, contactIdentifier string
+ if isGroup {
+ // Use the group JID as the identifier
+ contactIdentifier = identifier
+ } else {
+ phoneNumber = utils.NormalizePhoneE164(identifier)
+ }
+
+ payload := CreateContactRequest{
+ InboxID: c.InboxID,
+ Name: name,
+ PhoneNumber: phoneNumber,
+ Identifier: contactIdentifier,
+ CustomAttributes: map[string]interface{}{
+ "waha_whatsapp_jid": identifier,
+ },
+ }
+
+ jsonPayload, err := json.Marshal(payload)
+ if err != nil {
+ return nil, fmt.Errorf("failed to marshal contact payload: %w", err)
+ }
+ logrus.Debugf("Chatwoot CreateContact: Sending payload: %s", string(jsonPayload))
+ req, err := http.NewRequest("POST", endpoint, bytes.NewBuffer(jsonPayload))
+ if err != nil {
+ return nil, err
+ }
+
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("api_access_token", c.APIToken)
+
+ resp, err := c.HTTPClient.Do(req)
+ if err != nil {
+ return nil, err
+ }
+ defer resp.Body.Close()
+
+ bodyBytes, _ := io.ReadAll(resp.Body)
+ logrus.Debugf("Chatwoot CreateContact: Response status=%d body=%s", resp.StatusCode, string(bodyBytes))
+
+ // Chatwoot returns 200 OK for contacts
+ if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated {
+ return nil, fmt.Errorf("failed to create contact: status %d body %s", resp.StatusCode, string(bodyBytes))
+ }
+
+ // Try to decode with payload wrapper first
+ var result struct {
+ Payload Contact `json:"payload"`
+ }
+ if err := json.Unmarshal(bodyBytes, &result); err == nil && result.Payload.ID != 0 {
+ return &result.Payload, nil
+ }
+
+ // Try direct decode (some Chatwoot versions return contact directly)
+ var contact Contact
+ if err := json.Unmarshal(bodyBytes, &contact); err != nil {
+ return nil, fmt.Errorf("failed to decode contact response: %v", err)
+ }
+
+ return &contact, nil
+}
+
+func (c *Client) FindOrCreateContact(name, identifier string, isGroup bool) (*Contact, error) {
+ contact, err := c.FindContactByIdentifier(identifier, isGroup)
+ if err != nil {
+ return nil, err
+ }
+ if contact != nil {
+ // Update contact name if it has changed (e.g., group name changed)
+ if contact.Name != name && name != "" {
+ logrus.Infof("Chatwoot: Updating contact name from '%s' to '%s'", contact.Name, name)
+ if err := c.UpdateContactName(contact.ID, name); err != nil {
+ logrus.Warnf("Chatwoot: Failed to update contact name: %v", err)
+ // Continue anyway, the old name is still usable
+ }
+ contact.Name = name
+ }
+ return contact, nil
+ }
+ return c.CreateContact(name, identifier, isGroup)
+}
+
+// UpdateContactName updates the name of an existing contact
+func (c *Client) UpdateContactName(contactID int, name string) error {
+ endpoint := fmt.Sprintf("%s/api/v1/accounts/%d/contacts/%d", c.BaseURL, c.AccountID, contactID)
+
+ payload := map[string]interface{}{
+ "name": name,
+ }
+
+ jsonPayload, err := json.Marshal(payload)
+ if err != nil {
+ return fmt.Errorf("failed to marshal update payload: %w", err)
+ }
+ req, err := http.NewRequest("PUT", endpoint, bytes.NewBuffer(jsonPayload))
+ if err != nil {
+ return err
+ }
+
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("api_access_token", c.APIToken)
+
+ resp, err := c.HTTPClient.Do(req)
+ if err != nil {
+ return err
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNoContent {
+ body, _ := io.ReadAll(resp.Body)
+ return fmt.Errorf("failed to update contact: status %d body %s", resp.StatusCode, string(body))
+ }
+
+ return nil
+}
+
+func (c *Client) FindConversation(contactID int) (*Conversation, error) {
+ // Use contact-specific conversations endpoint for accurate results
+ endpoint := fmt.Sprintf("%s/api/v1/accounts/%d/contacts/%d/conversations", c.BaseURL, c.AccountID, contactID)
+ req, err := http.NewRequest("GET", endpoint, nil)
+ if err != nil {
+ return nil, err
+ }
+
+ req.Header.Set("api_access_token", c.APIToken)
+
+ resp, err := c.HTTPClient.Do(req)
+ if err != nil {
+ return nil, err
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != http.StatusOK {
+ body, _ := io.ReadAll(resp.Body)
+ return nil, fmt.Errorf("failed to list contact conversations: status %d body %s", resp.StatusCode, string(body))
+ }
+
+ var result struct {
+ Payload []struct {
+ ID int `json:"id"`
+ InboxID int `json:"inbox_id"`
+ Status string `json:"status"`
+ } `json:"payload"`
+ }
+
+ if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
+ return nil, err
+ }
+
+ // Find an open conversation for this inbox
+ for _, conv := range result.Payload {
+ if conv.InboxID == c.InboxID && conv.Status != "resolved" {
+ return &Conversation{
+ ID: conv.ID,
+ ContactID: contactID,
+ InboxID: conv.InboxID,
+ Status: conv.Status,
+ }, nil
+ }
+ }
+
+ return nil, nil
+}
+
+func (c *Client) CreateConversation(contactID int) (*Conversation, error) {
+ endpoint := fmt.Sprintf("%s/api/v1/accounts/%d/conversations", c.BaseURL, c.AccountID)
+
+ payload := CreateConversationRequest{
+ InboxID: c.InboxID,
+ ContactID: contactID,
+ Status: "open",
+ }
+
+ jsonPayload, err := json.Marshal(payload)
+ if err != nil {
+ return nil, fmt.Errorf("failed to marshal conversation payload: %w", err)
+ }
+ req, err := http.NewRequest("POST", endpoint, bytes.NewBuffer(jsonPayload))
+ if err != nil {
+ return nil, err
+ }
+
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("api_access_token", c.APIToken)
+
+ resp, err := c.HTTPClient.Do(req)
+ if err != nil {
+ return nil, err
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != http.StatusOK {
+ body, _ := io.ReadAll(resp.Body)
+ return nil, fmt.Errorf("failed to create conversation: status %d body %s", resp.StatusCode, string(body))
+ }
+
+ var result struct {
+ Payload Conversation `json:"payload"`
+ }
+ // Try to decode into wrapper first
+ bodyBytes, _ := io.ReadAll(resp.Body)
+ // Reset body for decoder
+ resp.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))
+
+ if err := json.NewDecoder(resp.Body).Decode(&result); err == nil && result.Payload.ID != 0 {
+ return &result.Payload, nil
+ }
+
+ // If wrapper failed, try direct decode
+ resp.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))
+ var conversation Conversation
+ if err := json.NewDecoder(resp.Body).Decode(&conversation); err != nil {
+ return nil, err
+ }
+ return &conversation, nil
+}
+
+func (c *Client) FindOrCreateConversation(contactID int) (*Conversation, error) {
+ conv, err := c.FindConversation(contactID)
+ if err != nil {
+ logrus.Errorf("Error finding conversation: %v", err)
+ }
+ if conv != nil {
+ return conv, nil
+ }
+ return c.CreateConversation(contactID)
+}
+
+func (c *Client) CreateMessage(conversationID int, content string, messageType string, attachments []string) error {
+ endpoint := fmt.Sprintf("%s/api/v1/accounts/%d/conversations/%d/messages", c.BaseURL, c.AccountID, conversationID)
+
+ if len(attachments) > 0 {
+ return c.createMessageWithAttachments(endpoint, content, messageType, attachments)
+ }
+
+ payload := CreateMessageRequest{
+ Content: content,
+ MessageType: messageType,
+ Private: false,
+ }
+
+ jsonPayload, err := json.Marshal(payload)
+ if err != nil {
+ return fmt.Errorf("failed to marshal message payload: %w", err)
+ }
+ req, err := http.NewRequest("POST", endpoint, bytes.NewBuffer(jsonPayload))
+ if err != nil {
+ return err
+ }
+
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("api_access_token", c.APIToken)
+
+ resp, err := c.HTTPClient.Do(req)
+ if err != nil {
+ return err
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != http.StatusOK {
+ body, _ := io.ReadAll(resp.Body)
+ return fmt.Errorf("failed to create message: status %d body %s", resp.StatusCode, string(body))
+ }
+
+ return nil
+}
+
+func (c *Client) createMessageWithAttachments(endpoint, content, messageType string, attachments []string) error {
+ body := &bytes.Buffer{}
+ writer := multipart.NewWriter(body)
+
+ _ = writer.WriteField("content", content)
+ _ = writer.WriteField("message_type", messageType)
+ _ = writer.WriteField("private", "false")
+
+ for _, filePath := range attachments {
+ // Process each file in a closure to ensure proper cleanup of file handles
+ // This prevents file descriptor leaks when processing multiple attachments
+ func(fp string) {
+ file, err := os.Open(fp)
+ if err != nil {
+ logrus.Errorf("Failed to open file %s: %v", fp, err)
+ return
+ }
+ defer file.Close()
+
+ // Get file name from path
+ fileName := filepath.Base(fp)
+
+ // Detect MIME type from file extension
+ mimeType := mime.TypeByExtension(filepath.Ext(fp))
+ if mimeType == "" {
+ mimeType = "application/octet-stream"
+ }
+
+ // Create a custom form part with correct Content-Type header
+ // This is needed for Chatwoot to render images inline instead of as file attachments
+ h := make(textproto.MIMEHeader)
+ h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="attachments[]"; filename="%s"`, fileName))
+ h.Set("Content-Type", mimeType)
+
+ part, err := writer.CreatePart(h)
+ if err != nil {
+ logrus.Errorf("Failed to create form part for %s: %v", fp, err)
+ return
+ }
+ io.Copy(part, file)
+ }(filePath)
+ }
+
+ writer.Close()
+
+ req, err := http.NewRequest("POST", endpoint, body)
+ if err != nil {
+ return err
+ }
+
+ req.Header.Set("Content-Type", writer.FormDataContentType())
+ req.Header.Set("api_access_token", c.APIToken)
+
+ resp, err := c.HTTPClient.Do(req)
+ if err != nil {
+ return err
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != http.StatusOK {
+ respBody, _ := io.ReadAll(resp.Body)
+ return fmt.Errorf("failed to create message with attachments: status %d body %s", resp.StatusCode, string(respBody))
+ }
+
+ return nil
+}
diff --git a/src/infrastructure/chatwoot/types.go b/src/infrastructure/chatwoot/types.go
new file mode 100644
index 00000000..b51911de
--- /dev/null
+++ b/src/infrastructure/chatwoot/types.go
@@ -0,0 +1,77 @@
+package chatwoot
+
+type Contact struct {
+ ID int `json:"id"`
+ Name string `json:"name"`
+ Email string `json:"email"`
+ PhoneNumber string `json:"phone_number"`
+ Identifier string `json:"identifier"`
+ CustomAttributes map[string]interface{} `json:"custom_attributes"`
+}
+
+type Conversation struct {
+ ID int `json:"id"`
+ ContactID int `json:"contact_id"`
+ InboxID int `json:"inbox_id"`
+ Status string `json:"status"`
+}
+
+type Message struct {
+ ID int `json:"id"`
+ Content string `json:"content"`
+ MessageType string `json:"message_type"`
+ Private bool `json:"private"`
+ ContentType string `json:"content_type"`
+}
+
+type CreateContactRequest struct {
+ InboxID int `json:"inbox_id"`
+ Name string `json:"name"`
+ PhoneNumber string `json:"phone_number,omitempty"`
+ Identifier string `json:"identifier,omitempty"`
+ CustomAttributes map[string]interface{} `json:"custom_attributes"`
+}
+
+type CreateConversationRequest struct {
+ InboxID int `json:"inbox_id"`
+ ContactID int `json:"contact_id"`
+ Status string `json:"status"`
+}
+
+type CreateMessageRequest struct {
+ Content string `json:"content"`
+ MessageType string `json:"message_type"`
+ Private bool `json:"private"`
+}
+
+type WebhookPayload struct {
+ Event string `json:"event"`
+ MessageType string `json:"message_type"`
+ Content string `json:"content"`
+ Private bool `json:"private"`
+ Account Account `json:"account"`
+ Conversation ConversationWebhook `json:"conversation"`
+ Sender Contact `json:"sender"`
+ Attachments []Attachment `json:"attachments"`
+}
+
+type Attachment struct {
+ ID int `json:"id"`
+ FileType string `json:"file_type"`
+ DataURL string `json:"data_url"`
+ ThumbURL string `json:"thumb_url"`
+ Extension string `json:"extension"`
+}
+
+type ConversationWebhook struct {
+ ID int `json:"id"`
+ Meta ConversationMeta `json:"meta"`
+}
+
+type ConversationMeta struct {
+ Sender Contact `json:"sender"`
+}
+
+type Account struct {
+ ID int `json:"id"`
+}
diff --git a/src/infrastructure/whatsapp/event_message.go b/src/infrastructure/whatsapp/event_message.go
index cb14e7ff..2c2eba76 100644
--- a/src/infrastructure/whatsapp/event_message.go
+++ b/src/infrastructure/whatsapp/event_message.go
@@ -217,12 +217,12 @@ func buildOptionalFields(ctx context.Context, client *whatsmeow.Client, evt *eve
func buildMediaFields(ctx context.Context, client *whatsmeow.Client, evt *events.Message, payload map[string]any) error {
if audioMedia := evt.Message.GetAudioMessage(); audioMedia != nil {
if config.WhatsappAutoDownloadMedia {
- path, err := utils.ExtractMedia(ctx, client, config.PathMedia, audioMedia)
+ extracted, err := utils.ExtractMedia(ctx, client, config.PathMedia, audioMedia)
if err != nil {
logrus.Errorf("Failed to download audio from %s: %v", evt.Info.SourceString(), err)
return pkgError.WebhookError(fmt.Sprintf("Failed to download audio: %v", err))
}
- payload["audio"] = path
+ payload["audio"] = extracted.MediaPath
} else {
payload["audio"] = map[string]any{
"url": audioMedia.GetURL(),
@@ -232,12 +232,12 @@ func buildMediaFields(ctx context.Context, client *whatsmeow.Client, evt *events
if documentMedia := evt.Message.GetDocumentMessage(); documentMedia != nil {
if config.WhatsappAutoDownloadMedia {
- path, err := utils.ExtractMedia(ctx, client, config.PathMedia, documentMedia)
+ extracted, err := utils.ExtractMedia(ctx, client, config.PathMedia, documentMedia)
if err != nil {
logrus.Errorf("Failed to download document from %s: %v", evt.Info.SourceString(), err)
return pkgError.WebhookError(fmt.Sprintf("Failed to download document: %v", err))
}
- payload["document"] = path
+ payload["document"] = extracted.MediaPath
} else {
payload["document"] = map[string]any{
"url": documentMedia.GetURL(),
@@ -248,12 +248,12 @@ func buildMediaFields(ctx context.Context, client *whatsmeow.Client, evt *events
if imageMedia := evt.Message.GetImageMessage(); imageMedia != nil {
if config.WhatsappAutoDownloadMedia {
- path, err := utils.ExtractMedia(ctx, client, config.PathMedia, imageMedia)
+ extracted, err := utils.ExtractMedia(ctx, client, config.PathMedia, imageMedia)
if err != nil {
logrus.Errorf("Failed to download image from %s: %v", evt.Info.SourceString(), err)
return pkgError.WebhookError(fmt.Sprintf("Failed to download image: %v", err))
}
- payload["image"] = path
+ payload["image"] = extracted.MediaPath
} else {
payload["image"] = map[string]any{
"url": imageMedia.GetURL(),
@@ -264,12 +264,12 @@ func buildMediaFields(ctx context.Context, client *whatsmeow.Client, evt *events
if stickerMedia := evt.Message.GetStickerMessage(); stickerMedia != nil {
if config.WhatsappAutoDownloadMedia {
- path, err := utils.ExtractMedia(ctx, client, config.PathMedia, stickerMedia)
+ extracted, err := utils.ExtractMedia(ctx, client, config.PathMedia, stickerMedia)
if err != nil {
logrus.Errorf("Failed to download sticker from %s: %v", evt.Info.SourceString(), err)
return pkgError.WebhookError(fmt.Sprintf("Failed to download sticker: %v", err))
}
- payload["sticker"] = path
+ payload["sticker"] = extracted.MediaPath
} else {
payload["sticker"] = map[string]any{
"url": stickerMedia.GetURL(),
@@ -279,12 +279,12 @@ func buildMediaFields(ctx context.Context, client *whatsmeow.Client, evt *events
if videoMedia := evt.Message.GetVideoMessage(); videoMedia != nil {
if config.WhatsappAutoDownloadMedia {
- path, err := utils.ExtractMedia(ctx, client, config.PathMedia, videoMedia)
+ extracted, err := utils.ExtractMedia(ctx, client, config.PathMedia, videoMedia)
if err != nil {
logrus.Errorf("Failed to download video from %s: %v", evt.Info.SourceString(), err)
return pkgError.WebhookError(fmt.Sprintf("Failed to download video: %v", err))
}
- payload["video"] = path
+ payload["video"] = extracted.MediaPath
} else {
payload["video"] = map[string]any{
"url": videoMedia.GetURL(),
@@ -295,12 +295,12 @@ func buildMediaFields(ctx context.Context, client *whatsmeow.Client, evt *events
if ptvMedia := evt.Message.GetPtvMessage(); ptvMedia != nil {
if config.WhatsappAutoDownloadMedia {
- path, err := utils.ExtractMedia(ctx, client, config.PathMedia, ptvMedia)
+ extracted, err := utils.ExtractMedia(ctx, client, config.PathMedia, ptvMedia)
if err != nil {
logrus.Errorf("Failed to download video note from %s: %v", evt.Info.SourceString(), err)
return pkgError.WebhookError(fmt.Sprintf("Failed to download video note: %v", err))
}
- payload["video_note"] = path
+ payload["video_note"] = extracted.MediaPath
} else {
payload["video_note"] = map[string]any{
"url": ptvMedia.GetURL(),
diff --git a/src/infrastructure/whatsapp/event_message_handler.go b/src/infrastructure/whatsapp/event_message_handler.go
index 43b06d5c..d38b7c5a 100644
--- a/src/infrastructure/whatsapp/event_message_handler.go
+++ b/src/infrastructure/whatsapp/event_message_handler.go
@@ -68,10 +68,10 @@ func handleImageMessage(ctx context.Context, evt *events.Message, client *whatsm
return
}
if img := evt.Message.GetImageMessage(); img != nil {
- if path, err := utils.ExtractMedia(ctx, client, config.PathStorages, img); err != nil {
+ if extracted, err := utils.ExtractMedia(ctx, client, config.PathStorages, img); err != nil {
log.Errorf("Failed to download image: %v", err)
} else {
- log.Infof("Image downloaded to %s", path)
+ log.Infof("Image downloaded to %s", extracted.MediaPath)
}
}
}
@@ -123,7 +123,7 @@ func handleWebhookForward(ctx context.Context, evt *events.Message, client *what
return
}
- if len(config.WhatsappWebhook) > 0 &&
+ if (len(config.WhatsappWebhook) > 0 || config.ChatwootEnabled) &&
!strings.Contains(evt.Info.SourceString(), "broadcast") {
go func(e *events.Message, c *whatsmeow.Client) {
webhookCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
diff --git a/src/infrastructure/whatsapp/webhook_forward.go b/src/infrastructure/whatsapp/webhook_forward.go
index 8bdf098a..38fa78a0 100644
--- a/src/infrastructure/whatsapp/webhook_forward.go
+++ b/src/infrastructure/whatsapp/webhook_forward.go
@@ -3,15 +3,71 @@ package whatsapp
import (
"context"
"fmt"
+ "hash/fnv"
"strings"
+ "sync"
+ "time"
"github.com/aldinokemal/go-whatsapp-web-multidevice/config"
- pkgError "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/error"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/chatwoot"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
"github.com/sirupsen/logrus"
+ "go.mau.fi/whatsmeow/types"
)
var submitWebhookFn = submitWebhook
+// mutexShardCount is the number of mutex shards for contact synchronization.
+// Using a fixed array avoids memory growth from sync.Map while still providing
+// reasonable concurrency (64 shards means max 64 concurrent contact operations).
+const mutexShardCount = 64
+
+// contactMutexShards provides sharded locks to prevent race conditions when creating Chatwoot contacts.
+// This approach prevents memory leaks that would occur with a sync.Map that grows indefinitely.
+var contactMutexShards [mutexShardCount]sync.Mutex
+
+// groupNameCacheEntry holds cached group name with expiration time
+type groupNameCacheEntry struct {
+ name string
+ expiresAt time.Time
+}
+
+var (
+ // groupNameCache provides TTL-based caching for group names to reduce WhatsApp API calls
+ groupNameCache sync.Map
+ groupNameCacheTTL = 5 * time.Minute
+)
+
+// getCachedGroupName retrieves group name from cache if not expired.
+// Returns empty string and false if not cached or expired.
+func getCachedGroupName(groupJID string) (string, bool) {
+ if entry, ok := groupNameCache.Load(groupJID); ok {
+ cached := entry.(groupNameCacheEntry)
+ if time.Now().Before(cached.expiresAt) {
+ return cached.name, true
+ }
+ // Entry expired, delete it
+ groupNameCache.Delete(groupJID)
+ }
+ return "", false
+}
+
+// setCachedGroupName stores group name in cache with TTL.
+func setCachedGroupName(groupJID, name string) {
+ groupNameCache.Store(groupJID, groupNameCacheEntry{
+ name: name,
+ expiresAt: time.Now().Add(groupNameCacheTTL),
+ })
+}
+
+// getContactMutex returns a mutex for the given phone number to serialize contact operations.
+// Uses FNV-1a hash to distribute phones across shards for balanced lock contention.
+func getContactMutex(phone string) *sync.Mutex {
+ h := fnv.New32a()
+ h.Write([]byte(phone))
+ return &contactMutexShards[h.Sum32()%mutexShardCount]
+}
+
// forwardPayloadToConfiguredWebhooks attempts to deliver the provided payload to every configured webhook URL.
// It only returns an error when all webhook deliveries fail. Partial failures are logged and suppressed so
// successful targets still receive the event.
@@ -24,11 +80,20 @@ func forwardPayloadToConfiguredWebhooks(ctx context.Context, payload map[string]
}
}
+ err := forwardToWebhooks(ctx, payload, eventName)
+
+ if eventName == "message" && config.ChatwootEnabled {
+ go forwardToChatwoot(ctx, payload)
+ }
+
+ return err
+}
+
+func forwardToWebhooks(ctx context.Context, payload map[string]any, eventName string) error {
total := len(config.WhatsappWebhook)
logrus.Infof("Forwarding %s to %d configured webhook(s)", eventName, total)
if total == 0 {
- logrus.Infof("No webhook configured for %s; skipping dispatch", eventName)
return nil
}
@@ -45,12 +110,12 @@ func forwardPayloadToConfiguredWebhooks(ctx context.Context, payload map[string]
successes++
}
- if len(failed) == total {
- return pkgError.WebhookError(fmt.Sprintf("all webhook URLs failed for %s: %s", eventName, strings.Join(failed, "; ")))
- }
-
if len(failed) > 0 {
logrus.Warnf("Some webhook URLs failed for %s (succeeded: %d/%d): %s", eventName, successes, total, strings.Join(failed, "; "))
+ // Return error only if ALL webhooks failed
+ if successes == 0 {
+ return fmt.Errorf("all %d webhook(s) failed for %s", total, eventName)
+ }
} else {
logrus.Infof("%s forwarded to all webhook(s)", eventName)
}
@@ -58,6 +123,148 @@ func forwardPayloadToConfiguredWebhooks(ctx context.Context, payload map[string]
return nil
}
+// chatwootContactInfo holds extracted contact information for Chatwoot sync
+type chatwootContactInfo struct {
+ Identifier string
+ Name string
+ IsGroup bool
+ FromName string
+}
+
+// extractChatwootContactInfo extracts contact identifier and name from message payload.
+// For groups, uses the group JID as identifier and tries to fetch group name.
+// For private chats, uses the sender's phone number.
+func extractChatwootContactInfo(ctx context.Context, data map[string]interface{}) (*chatwootContactInfo, error) {
+ from, _ := data["from"].(string)
+ fromName, _ := data["from_name"].(string)
+ chatID, _ := data["chat_id"].(string)
+
+ logrus.Infof("Chatwoot: Processing message from %s (from_name: %s, chat_id: %s)", from, fromName, chatID)
+
+ if from == "" {
+ return nil, fmt.Errorf("empty 'from' field")
+ }
+
+ isGroup := utils.IsGroupJID(chatID)
+ info := &chatwootContactInfo{
+ IsGroup: isGroup,
+ FromName: fromName,
+ }
+
+ if isGroup {
+ info.Identifier = chatID
+ info.Name = getGroupName(ctx, chatID)
+ if info.Name == "" {
+ info.Name = "Group: " + utils.ExtractPhoneFromJID(chatID)
+ }
+ logrus.Infof("Chatwoot: Detected group message, using group contact: %s", info.Name)
+ } else {
+ info.Identifier = utils.ExtractPhoneFromJID(from)
+ info.Name = fromName
+ if info.Name == "" {
+ info.Name = info.Identifier
+ }
+ }
+
+ return info, nil
+}
+
+// buildChatwootMessageContent extracts message body and attachments from the payload.
+// For group messages, prepends the sender name to the content.
+func buildChatwootMessageContent(data map[string]interface{}, isGroup bool, fromName string) (content string, attachments []string) {
+ if body, ok := data["body"].(string); ok && body != "" {
+ content = body
+ }
+
+ // For group messages, prepend sender name to content
+ if isGroup && fromName != "" && content != "" {
+ content = fromName + ": " + content
+ }
+
+ // Extract media attachments
+ mediaFields := []string{"image", "audio", "video", "document", "sticker", "video_note"}
+ for _, field := range mediaFields {
+ if mediaData, ok := data[field]; ok {
+ if path, ok := mediaData.(string); ok && path != "" {
+ attachments = append(attachments, path)
+ logrus.Infof("Chatwoot: Found %s attachment at %s", field, path)
+ }
+ }
+ }
+
+ // Handle empty content
+ if content == "" && len(attachments) == 0 {
+ content = "(Unsupported message type)"
+ logrus.Info("Chatwoot: Message content is empty/unsupported, using placeholder")
+ }
+
+ // For group messages with attachments but no text, still prepend sender name
+ if isGroup && fromName != "" && content == "" && len(attachments) > 0 {
+ content = fromName + ": (media)"
+ }
+
+ return content, attachments
+}
+
+// syncMessageToChatwoot creates or finds contact/conversation and sends the message.
+func syncMessageToChatwoot(cw *chatwoot.Client, info *chatwootContactInfo, content string, attachments []string) error {
+ // Lock per-identifier mutex to prevent duplicate contact/conversation creation
+ mu := getContactMutex(info.Identifier)
+ mu.Lock()
+
+ contact, err := cw.FindOrCreateContact(info.Name, info.Identifier, info.IsGroup)
+ if err != nil {
+ mu.Unlock()
+ return fmt.Errorf("failed to find/create contact for %s: %w", info.Identifier, err)
+ }
+ logrus.Infof("Chatwoot: Contact ID: %d", contact.ID)
+
+ conversation, err := cw.FindOrCreateConversation(contact.ID)
+ mu.Unlock()
+ if err != nil {
+ return fmt.Errorf("failed to find/create conversation for contact %d: %w", contact.ID, err)
+ }
+ logrus.Infof("Chatwoot: Conversation ID: %d", conversation.ID)
+
+ logrus.Infof("Chatwoot: Creating message (Length: %d, Attachments: %d)", len(content), len(attachments))
+ if err := cw.CreateMessage(conversation.ID, content, "incoming", attachments); err != nil {
+ return fmt.Errorf("failed to create message: %w", err)
+ }
+
+ logrus.Infof("Chatwoot: Message synced successfully for %s", info.Identifier)
+ return nil
+}
+
+func forwardToChatwoot(ctx context.Context, payload map[string]any) {
+ logrus.Info("Chatwoot: Attempting to forward message...")
+ cw := chatwoot.GetDefaultClient()
+ if !cw.IsConfigured() {
+ logrus.Warn("Chatwoot: Client is not configured (check CHATWOOT_* env vars)")
+ return
+ }
+
+ data, ok := payload["payload"].(map[string]interface{})
+ if !ok {
+ logrus.Error("Chatwoot: Invalid payload format (missing 'payload' object)")
+ return
+ }
+
+ // Extract contact information
+ info, err := extractChatwootContactInfo(ctx, data)
+ if err != nil {
+ logrus.Warnf("Chatwoot: Skipping message: %v", err)
+ return
+ }
+
+ // Build message content
+ content, attachments := buildChatwootMessageContent(data, info.IsGroup, info.FromName)
+
+ // Sync to Chatwoot
+ if err := syncMessageToChatwoot(cw, info, content, attachments); err != nil {
+ logrus.Errorf("Chatwoot: %v", err)
+ }
+}
+
// isEventWhitelisted checks if the given event name is in the configured whitelist
func isEventWhitelisted(eventName string) bool {
for _, allowed := range config.WhatsappWebhookEvents {
@@ -67,3 +274,51 @@ func isEventWhitelisted(eventName string) bool {
}
return false
}
+
+// getGroupName fetches the group name from WhatsApp using the group JID.
+// Uses a TTL cache to avoid repeated API calls for the same group.
+func getGroupName(ctx context.Context, groupJID string) string {
+ // Check cache first
+ if name, ok := getCachedGroupName(groupJID); ok {
+ logrus.Debugf("Chatwoot: Using cached group name for %s: %s", groupJID, name)
+ return name
+ }
+
+ client := ClientFromContext(ctx)
+ if client == nil {
+ logrus.Debug("Chatwoot: ClientFromContext returned nil, trying GetClient()")
+ client = GetClient()
+ }
+ if client == nil {
+ logrus.Warn("Chatwoot: No WhatsApp client available to fetch group name")
+ return ""
+ }
+
+ jid, err := types.ParseJID(groupJID)
+ if err != nil {
+ logrus.Warnf("Chatwoot: Failed to parse group JID %s: %v", groupJID, err)
+ return ""
+ }
+
+ // Use a fresh context with timeout since the original context may be canceled
+ // (this function is called from a goroutine)
+ freshCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+
+ logrus.Debugf("Chatwoot: Fetching group info for %s", groupJID)
+ groupInfo, err := client.GetGroupInfo(freshCtx, jid)
+ if err != nil {
+ logrus.Warnf("Chatwoot: Failed to get group info for %s: %v", groupJID, err)
+ return ""
+ }
+
+ if groupInfo != nil && groupInfo.Name != "" {
+ logrus.Infof("Chatwoot: Got group name: %s", groupInfo.Name)
+ // Cache the result
+ setCachedGroupName(groupJID, groupInfo.Name)
+ return groupInfo.Name
+ }
+
+ logrus.Debug("Chatwoot: GroupInfo is nil or Name is empty")
+ return ""
+}
diff --git a/src/pkg/utils/general.go b/src/pkg/utils/general.go
index 2eabce42..e0390705 100644
--- a/src/pkg/utils/general.go
+++ b/src/pkg/utils/general.go
@@ -314,26 +314,33 @@ func DownloadAudioFromURL(audioURL string) ([]byte, string, error) {
// Align audio MIME validation with the one used for uploaded files to ensure consistency with WhatsApp requirements.
allowedMimes := map[string]bool{
- "audio/aac": true,
- "audio/amr": true,
- "audio/flac": true,
- "audio/m4a": true,
- "audio/m4r": true,
- "audio/mp3": true,
- "audio/mpeg": true,
- "audio/ogg": true,
- "audio/wma": true,
- "audio/x-ms-wma": true,
- "audio/wav": true,
- "audio/vnd.wav": true,
- "audio/vnd.wave": true,
- "audio/wave": true,
- "audio/x-pn-wav": true,
- "audio/x-wav": true,
- }
-
+ "audio/aac": true,
+ "audio/amr": true,
+ "audio/flac": true,
+ "audio/m4a": true,
+ "audio/m4r": true,
+ "audio/mp3": true,
+ "audio/mpeg": true,
+ "audio/ogg": true,
+ "audio/wma": true,
+ "audio/x-ms-wma": true,
+ "audio/wav": true,
+ "audio/vnd.wav": true,
+ "audio/vnd.wave": true,
+ "audio/wave": true,
+ "audio/x-pn-wav": true,
+ "audio/x-wav": true,
+ "video/mp4": true, // Sometimes audio is served as mp4
+ "application/ogg": true, // Ogg audio
+ "application/x-mpeg": true,
+ "audio/webm": true, // WebM audio
+ "video/webm": true, // WebM audio/video
+ "audio/mp4": true,
+ }
+
+ // If content type is generic or not in list, just warn but allow download (let WhatsApp reject if invalid)
if !allowedMimes[contentType] {
- return nil, "", fmt.Errorf("invalid content type: %s", contentType)
+ logrus.Warnf("DownloadAudioFromURL: unexpected content type '%s', proceeding anyway", contentType)
}
// Validate content length when it is provided by the server.
@@ -485,3 +492,58 @@ func UniqueStrings(input []string) []string {
}
return result
}
+
+// DownloadFileFromURL downloads a file from the provided URL and returns the bytes and sanitized filename.
+// It enforces max file size limit.
+func DownloadFileFromURL(fileURL string) ([]byte, string, error) {
+ client := &http.Client{
+ Timeout: 30 * time.Second,
+ CheckRedirect: func(req *http.Request, via []*http.Request) error {
+ if len(via) >= 10 {
+ return fmt.Errorf("too many redirects")
+ }
+ return nil
+ },
+ }
+
+ resp, err := client.Get(fileURL)
+ if err != nil {
+ return nil, "", err
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != http.StatusOK {
+ return nil, "", fmt.Errorf("HTTP request failed with status: %s", resp.Status)
+ }
+
+ // Validate content length when it is provided by the server.
+ maxSize := config.WhatsappSettingMaxFileSize
+ if resp.ContentLength > 0 && resp.ContentLength > maxSize {
+ return nil, "", fmt.Errorf("file size %d exceeds maximum allowed size %d", resp.ContentLength, maxSize)
+ }
+
+ // Limit reader
+ limit := maxSize
+ if limit < math.MaxInt64 {
+ limit++
+ }
+
+ limitedReader := &io.LimitedReader{R: resp.Body, N: limit}
+ fileData, err := io.ReadAll(limitedReader)
+ if err != nil {
+ return nil, "", err
+ }
+ if int64(len(fileData)) > maxSize {
+ return nil, "", fmt.Errorf("downloaded file size of %d bytes exceeds the maximum allowed size of %d bytes", len(fileData), maxSize)
+ }
+
+ // Derive filename from URL path
+ segments := strings.Split(fileURL, "/")
+ fileName := segments[len(segments)-1]
+ fileName = strings.Split(fileName, "?")[0]
+ if fileName == "" {
+ fileName = fmt.Sprintf("file_%d", time.Now().Unix())
+ }
+
+ return fileData, fileName, nil
+}
diff --git a/src/pkg/utils/general_test.go b/src/pkg/utils/general_test.go
index f9fc16ca..a8455cc9 100644
--- a/src/pkg/utils/general_test.go
+++ b/src/pkg/utils/general_test.go
@@ -461,10 +461,10 @@ func (suite *UtilsTestSuite) TestDownloadAudioFromURL() {
assert.NoError(suite.T(), err)
assert.Equal(suite.T(), "test.m4a", filename)
- // Test invalid content type
- _, _, err = utils.DownloadAudioFromURL(server.URL + "/invalid.mp3")
- assert.Error(suite.T(), err)
- assert.Contains(suite.T(), err.Error(), "invalid content type")
+ // Test invalid content type - should now warn but still proceed (changed behavior for Chatwoot compatibility)
+ data, filename, err = utils.DownloadAudioFromURL(server.URL + "/invalid.mp3")
+ assert.NoError(suite.T(), err) // Now proceeds with warning instead of error
+ assert.NotEmpty(suite.T(), data)
// Test file too large by content length
_, _, err = utils.DownloadAudioFromURL(server.URL + "/large.mp3")
diff --git a/src/pkg/utils/phone.go b/src/pkg/utils/phone.go
new file mode 100644
index 00000000..9d1f670e
--- /dev/null
+++ b/src/pkg/utils/phone.go
@@ -0,0 +1,31 @@
+package utils
+
+import "strings"
+
+// NormalizePhoneE164 ensures phone has + prefix for E.164 format.
+// Returns empty string if input is empty.
+func NormalizePhoneE164(phone string) string {
+ phone = strings.TrimSpace(phone)
+ if phone != "" && !strings.HasPrefix(phone, "+") {
+ return "+" + phone
+ }
+ return phone
+}
+
+// StripPhonePrefix removes + prefix from phone number.
+func StripPhonePrefix(phone string) string {
+ return strings.TrimPrefix(strings.TrimSpace(phone), "+")
+}
+
+// ExtractPhoneFromJID extracts phone number from JID by stripping the domain part.
+// For example, "[email protected]" becomes "1234567890".
+func ExtractPhoneFromJID(jid string) string {
+ return strings.Split(jid, "@")[0]
+}
+
+// CleanPhoneForWhatsApp prepares a phone number for WhatsApp sending.
+// Removes + prefix and trims whitespace.
+func CleanPhoneForWhatsApp(phone string) string {
+ phone = strings.ReplaceAll(phone, "+", "")
+ return strings.TrimSpace(phone)
+}
diff --git a/src/pkg/utils/response.go b/src/pkg/utils/response.go
index a421aa87..aa202872 100644
--- a/src/pkg/utils/response.go
+++ b/src/pkg/utils/response.go
@@ -1,8 +1,19 @@
package utils
+import (
+ "github.com/gofiber/fiber/v2"
+)
+
type ResponseData struct {
Status int `json:"-"`
Code string `json:"code"`
Message string `json:"message"`
Results any `json:"results,omitempty"`
}
+
+func ResponseError(c *fiber.Ctx, message string) error {
+ return c.Status(fiber.StatusBadRequest).JSON(ResponseData{
+ Code: "INVALID_REQUEST",
+ Message: message,
+ })
+}
diff --git a/src/ui/rest/chatwoot.go b/src/ui/rest/chatwoot.go
new file mode 100644
index 00000000..c0db5ba9
--- /dev/null
+++ b/src/ui/rest/chatwoot.go
@@ -0,0 +1,176 @@
+package rest
+
+import (
+ domainApp "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/app"
+ domainSend "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/send"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/chatwoot"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
+ "github.com/gofiber/fiber/v2"
+ "github.com/sirupsen/logrus"
+)
+
+type ChatwootHandler struct {
+ AppUsecase domainApp.IAppUsecase
+ SendUsecase domainSend.ISendUsecase
+}
+
+func NewChatwootHandler(appUsecase domainApp.IAppUsecase, sendUsecase domainSend.ISendUsecase) *ChatwootHandler {
+ return &ChatwootHandler{
+ AppUsecase: appUsecase,
+ SendUsecase: sendUsecase,
+ }
+}
+
+func (h *ChatwootHandler) HandleWebhook(c *fiber.Ctx) error {
+ logrus.Debugf("Chatwoot Webhook raw body: %s", string(c.Body()))
+
+ var payload chatwoot.WebhookPayload
+ if err := c.BodyParser(&payload); err != nil {
+ return utils.ResponseError(c, "Invalid payload")
+ }
+
+ contact := payload.Conversation.Meta.Sender
+ logrus.Debugf("Chatwoot Webhook: event=%s message_type=%s contact_id=%d contact_phone=%s",
+ payload.Event, payload.MessageType, contact.ID, contact.PhoneNumber)
+
+ if payload.Event != "message_created" {
+ return c.SendStatus(fiber.StatusOK)
+ }
+
+ if payload.MessageType != "outgoing" {
+ return c.SendStatus(fiber.StatusOK)
+ }
+
+ if payload.Private {
+ return c.SendStatus(fiber.StatusOK)
+ }
+
+ customAttrs := contact.CustomAttributes
+ var destination string
+ if val, ok := customAttrs["waha_whatsapp_jid"]; ok {
+ if strVal, ok := val.(string); ok {
+ destination = strVal
+ }
+ }
+ if destination == "" && contact.PhoneNumber != "" {
+ destination = contact.PhoneNumber
+ }
+
+ if destination == "" {
+ logrus.Warnf("Chatwoot Webhook: No destination phone for contact ID %d", contact.ID)
+ return c.SendStatus(fiber.StatusOK)
+ }
+
+ // Check if this is a group message (JID ends with @g.us)
+ isGroup := utils.IsGroupJID(destination)
+
+ // Clean up the destination for WhatsApp sending
+ destination = utils.CleanPhoneForWhatsApp(destination)
+
+ // For private chats, strip the @s.whatsapp.net suffix if present
+ // For groups, keep the full JID (including @g.us)
+ if !isGroup {
+ destination = utils.ExtractPhoneFromJID(destination)
+ }
+
+ logrus.Debugf("Chatwoot Webhook: Sending to destination=%s isGroup=%v", destination, isGroup)
+
+ // Handle attachments if present
+ if len(payload.Attachments) > 0 {
+ for _, attachment := range payload.Attachments {
+ if err := h.handleAttachment(c, destination, attachment, payload.Content); err != nil {
+ logrus.Errorf("Chatwoot Webhook: Failed to send attachment %d: %v", attachment.ID, err)
+ }
+ }
+ // Return early after sending attachments - caption was already included
+ return c.SendStatus(fiber.StatusOK)
+ }
+
+ // If content is present (and not just an attachment caption), send it as text
+ if payload.Content != "" {
+ req := domainSend.MessageRequest{
+ Message: payload.Content,
+ }
+ req.Phone = destination
+
+ _, err := h.SendUsecase.SendText(c.Context(), req)
+ if err != nil {
+ // Log with more context but still return 200 to prevent Chatwoot retries
+ logrus.WithFields(logrus.Fields{
+ "destination": destination,
+ "is_group": isGroup,
+ "error": err.Error(),
+ }).Error("Chatwoot Webhook: Failed to send message (returning 200 to prevent retry)")
+ return c.SendStatus(fiber.StatusOK)
+ }
+ logrus.Infof("Chatwoot Webhook: Sent text message to %s", destination)
+ }
+
+ return c.SendStatus(fiber.StatusOK)
+}
+
+func (h *ChatwootHandler) handleAttachment(c *fiber.Ctx, phone string, att chatwoot.Attachment, caption string) error {
+ switch att.FileType {
+ case "image":
+ req := domainSend.ImageRequest{
+ BaseRequest: domainSend.BaseRequest{Phone: phone},
+ Caption: caption,
+ ImageURL: &att.DataURL,
+ }
+ _, err := h.SendUsecase.SendImage(c.Context(), req)
+ if err == nil {
+ logrus.Infof("Chatwoot Webhook: Sent image attachment to %s", phone)
+ }
+ return err
+
+ case "audio":
+ req := domainSend.AudioRequest{
+ BaseRequest: domainSend.BaseRequest{Phone: phone},
+ AudioURL: &att.DataURL,
+ PTT: true, // Send as PTT (Voice Note) for better mobile experience
+ }
+ _, err := h.SendUsecase.SendAudio(c.Context(), req)
+ if err == nil {
+ logrus.Infof("Chatwoot Webhook: Sent audio attachment to %s", phone)
+ return nil
+ }
+
+ logrus.Warnf("Chatwoot Webhook: Failed to send as audio (%v), retrying as file...", err)
+ // Fallback to sending as file
+ reqFile := domainSend.FileRequest{
+ BaseRequest: domainSend.BaseRequest{Phone: phone},
+ FileURL: &att.DataURL,
+ Caption: caption,
+ }
+ _, err = h.SendUsecase.SendFile(c.Context(), reqFile)
+ if err == nil {
+ logrus.Infof("Chatwoot Webhook: Sent audio as file attachment to %s", phone)
+ }
+ return err
+
+ case "video":
+ req := domainSend.VideoRequest{
+ BaseRequest: domainSend.BaseRequest{Phone: phone},
+ Caption: caption,
+ VideoURL: &att.DataURL,
+ }
+ _, err := h.SendUsecase.SendVideo(c.Context(), req)
+ if err == nil {
+ logrus.Infof("Chatwoot Webhook: Sent video attachment to %s", phone)
+ }
+ return err
+
+ default:
+ // Default to file for other types
+ req := domainSend.FileRequest{
+ BaseRequest: domainSend.BaseRequest{Phone: phone},
+ FileURL: &att.DataURL,
+ Caption: caption,
+ }
+ _, err := h.SendUsecase.SendFile(c.Context(), req)
+ if err == nil {
+ logrus.Infof("Chatwoot Webhook: Sent file attachment to %s", phone)
+ }
+ return err
+ }
+}
diff --git a/src/usecase/send.go b/src/usecase/send.go
index 56fbb8c9..66168d3d 100644
--- a/src/usecase/send.go
+++ b/src/usecase/send.go
@@ -375,8 +375,22 @@ func (service serviceSend) SendFile(ctx context.Context, request domainSend.File
return response, err
}
- fileBytes := helpers.MultipartFormFileHeaderToBytes(request.File)
- fileMimeType := resolveDocumentMIME(request.File.Filename, fileBytes)
+ var (
+ fileBytes []byte
+ fileName string
+ )
+
+ if request.FileURL != nil && *request.FileURL != "" {
+ fileBytes, fileName, err = utils.DownloadFileFromURL(*request.FileURL)
+ if err != nil {
+ return response, pkgError.InternalServerError(fmt.Sprintf("failed to download file from URL: %v", err))
+ }
+ } else if request.File != nil {
+ fileBytes = helpers.MultipartFormFileHeaderToBytes(request.File)
+ fileName = request.File.Filename
+ }
+
+ fileMimeType := resolveDocumentMIME(fileName, fileBytes)
// Send to WA server
uploadedFile, err := service.uploadMedia(ctx, client, whatsmeow.MediaDocument, fileBytes, dataWaRecipient)
@@ -388,11 +402,11 @@ func (service serviceSend) SendFile(ctx context.Context, request domainSend.File
msg := &waE2E.Message{DocumentMessage: &waE2E.DocumentMessage{
URL: proto.String(uploadedFile.URL),
Mimetype: proto.String(fileMimeType),
- Title: proto.String(request.File.Filename),
+ Title: proto.String(fileName),
FileSHA256: uploadedFile.FileSHA256,
FileLength: proto.Uint64(uploadedFile.FileLength),
MediaKey: uploadedFile.MediaKey,
- FileName: proto.String(request.File.Filename),
+ FileName: proto.String(fileName),
FileEncSHA256: uploadedFile.FileEncSHA256,
DirectPath: proto.String(uploadedFile.DirectPath),
Caption: proto.String(request.Caption),
@@ -974,14 +988,24 @@ func (service serviceSend) SendAudio(ctx context.Context, request domainSend.Aud
}
var (
- audioBytes []byte
- audioMimeType string
- audioFilename string
- audioDuration uint32
- tempAudioPath string
- deleteTempFile bool
+ audioBytes []byte
+ audioMimeType string
+ audioFilename string
+ audioDuration uint32
+ tempAudioPath string
+ deleteTempFile bool
+ deletedItems []string
)
+ // Cleanup temporary files on exit
+ defer func() {
+ for _, path := range deletedItems {
+ if err := os.Remove(path); err != nil && !os.IsNotExist(err) {
+ logrus.Warnf("Failed to cleanup temporary audio file %s: %v", path, err)
+ }
+ }
+ }()
+
// Handle audio from URL or file
if request.AudioURL != nil && *request.AudioURL != "" {
audioBytes, audioFilename, err = utils.DownloadAudioFromURL(*request.AudioURL)
@@ -1025,6 +1049,86 @@ func (service serviceSend) SendAudio(ctx context.Context, request domainSend.Aud
waveformData = generateWaveform(tempAudioPath)
}
+ // If PTT is requested, convert audio to OGG Opus format for WhatsApp voice note compatibility
+ // WhatsApp clients require OGG Opus format for voice notes to play correctly
+ if request.PTT {
+ // Check if already OGG format - skip conversion
+ isAlreadyOgg := strings.HasPrefix(audioMimeType, "audio/ogg") ||
+ strings.HasPrefix(audioMimeType, "application/ogg")
+
+ if !isAlreadyOgg {
+ // Check if ffmpeg is installed
+ _, err := exec.LookPath("ffmpeg")
+ if err != nil {
+ return response, pkgError.InternalServerError("ffmpeg not installed (required for PTT voice notes)")
+ }
+
+ // Get absolute base directory for temporary files
+ absBaseDir, err := filepath.Abs(config.PathSendItems)
+ if err != nil {
+ return response, pkgError.InternalServerError(fmt.Sprintf("failed to resolve base directory: %v", err))
+ }
+
+ generateUUID := fiberUtils.UUIDv4()
+
+ // Save input audio to temporary file
+ inputPath := filepath.Join(absBaseDir, fmt.Sprintf("audio_input_%s", generateUUID))
+ if err := os.WriteFile(inputPath, audioBytes, 0644); err != nil {
+ return response, pkgError.InternalServerError(fmt.Sprintf("failed to save audio for conversion: %v", err))
+ }
+ deletedItems = append(deletedItems, inputPath)
+
+ // Output path for converted OGG Opus file
+ outputPath := filepath.Join(absBaseDir, fmt.Sprintf("audio_ptt_%s.ogg", generateUUID))
+ deletedItems = append(deletedItems, outputPath)
+
+ // Convert to OGG Opus using ffmpeg
+ // Opus codec is required for WhatsApp voice notes
+ // -c:a libopus: Use Opus codec
+ // -b:a 64k: Bitrate (64kbps is good quality for voice)
+ // -vbr on: Variable bitrate for better quality
+ // -application voip: Optimize for voice
+ // -ar 48000: Sample rate (Opus requires 48kHz)
+ // -ac 1: Mono (WhatsApp voice notes are mono)
+ convCtx, cancel := context.WithTimeout(ctx, 60*time.Second)
+ defer cancel()
+
+ cmdConvert := exec.CommandContext(convCtx, "ffmpeg",
+ "-i", inputPath,
+ "-c:a", "libopus",
+ "-b:a", "64k",
+ "-vbr", "on",
+ "-application", "voip",
+ "-ar", "48000",
+ "-ac", "1",
+ "-y", // Overwrite output if exists
+ outputPath,
+ )
+
+ var stderr bytes.Buffer
+ cmdConvert.Stderr = &stderr
+
+ if err := cmdConvert.Run(); err != nil {
+ logrus.Errorf("ffmpeg PTT conversion failed: %v, stderr: %s", err, stderr.String())
+ return response, pkgError.InternalServerError(fmt.Sprintf("failed to convert audio to OGG Opus for PTT: %v", err))
+ }
+
+ // Read converted audio
+ audioBytes, err = os.ReadFile(outputPath)
+ if err != nil {
+ return response, pkgError.InternalServerError(fmt.Sprintf("failed to read converted audio: %v", err))
+ }
+
+ // Update MIME type to OGG Opus
+ audioMimeType = "audio/ogg; codecs=opus"
+
+ logrus.Infof("Converted audio to OGG Opus for PTT: %d bytes", len(audioBytes))
+ } else {
+ // Already OGG format, ensure MIME type is correctly set
+ audioMimeType = "audio/ogg; codecs=opus"
+ }
+ }
+
// upload to WhatsApp servers
audioUploaded, err := service.uploadMedia(ctx, client, whatsmeow.MediaAudio, audioBytes, dataWaRecipient)
if err != nil {
diff --git a/src/validations/send_validation.go b/src/validations/send_validation.go
index d8ce3c18..e744c316 100644
--- a/src/validations/send_validation.go
+++ b/src/validations/send_validation.go
@@ -198,7 +198,6 @@ func ValidateSendSticker(ctx context.Context, request domainSend.StickerRequest)
func ValidateSendFile(ctx context.Context, request domainSend.FileRequest) error {
err := validation.ValidateStructWithContext(ctx, &request,
validation.Field(&request.Phone, validation.Required),
- validation.Field(&request.File, validation.Required),
)
if err != nil {
@@ -210,9 +209,25 @@ func ValidateSendFile(ctx context.Context, request domainSend.FileRequest) error
return err
}
- if request.File.Size > config.WhatsappSettingMaxFileSize { // 10MB
- maxSizeString := humanize.Bytes(uint64(config.WhatsappSettingMaxFileSize))
- return pkgError.ValidationError(fmt.Sprintf("max file upload is %s, please upload in cloud and send via text if your file is higher than %s", maxSizeString, maxSizeString))
+ // Either File or FileURL must be provided
+ if request.File == nil && (request.FileURL == nil || *request.FileURL == "") {
+ return pkgError.ValidationError("either File or FileURL must be provided")
+ }
+
+ if request.File != nil {
+ if request.File.Size > config.WhatsappSettingMaxFileSize { // 10MB
+ maxSizeString := humanize.Bytes(uint64(config.WhatsappSettingMaxFileSize))
+ return pkgError.ValidationError(fmt.Sprintf("max file upload is %s, please upload in cloud and send via text if your file is higher than %s", maxSizeString, maxSizeString))
+ }
+ }
+
+ if request.FileURL != nil {
+ if *request.FileURL == "" {
+ return pkgError.ValidationError("FileURL cannot be empty")
+ }
+ if err := validation.Validate(*request.FileURL, is.URL); err != nil {
+ return pkgError.ValidationError("FileURL must be a valid URL")
+ }
}
if err := validateDuration(request.Duration); err != nil {
diff --git a/src/validations/send_validation_test.go b/src/validations/send_validation_test.go
index f537fac0..7c2bfe79 100644
--- a/src/validations/send_validation_test.go
+++ b/src/validations/send_validation_test.go
@@ -173,7 +173,7 @@ func TestValidateSendFile(t *testing.T) {
},
File: nil,
}},
- err: pkgError.ValidationError("file: cannot be blank."),
+ err: pkgError.ValidationError("either File or FileURL must be provided"),
},
}