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 message history sync & webhook auth fix (#565)

Aldino Kemal3b87f4e909dd
diff --git a/CLAUDE.md b/CLAUDE.md
index a5f0c64e..6b32d24e 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -56,6 +56,15 @@ This is a Go-based WhatsApp Web API server supporting both REST API and MCP (Mod
- **Chat Storage**: Separate SQLite database for chat history (`storages/chatstorage.db`)
- **Database URIs**: Configurable via `DB_URI` and `DB_KEYS_URI` environment variables
+### Device ID vs JID (Critical)
+
+The system has two distinct identifiers for devices that must not be confused:
+
+- **Device ID** (`devices.device_id`): User-assigned alias (e.g. `"busine"`) or auto-generated UUID. Used as the key in `DeviceManager.devices` map and returned by `DeviceInstance.ID()`. This is what `ResolveDevice()` returns as `resolvedID`.
+- **JID** (`devices.jid`): Full WhatsApp JID (e.g. `"[email protected]"`). Derived from `client.Store.ID.ToNonAD().String()` and returned by `DeviceInstance.JID()`.
+
+**The `chats` and `messages` tables store `device_id` as the JID**, not the user-assigned alias. When querying chat storage, always use `DeviceInstance.JID()` (falling back to `ID()` if JID is empty). The `deviceChatStorage` wrapper handles this automatically via `newDeviceChatStorage(storageDeviceID, ...)` where `storageDeviceID` is resolved to the JID in `loadFromRegistry()` and `ensureInstance()`.
+
### Mode-Specific Architecture
- **REST Mode**: Fiber web server with HTML templates, WebSocket support, middleware stack
diff --git a/docs/chatwoot.md b/docs/chatwoot.md
index ef663a2a..7cca5d5e 100644
--- a/docs/chatwoot.md
+++ b/docs/chatwoot.md
@@ -31,6 +31,8 @@ Before setting up the integration, ensure you have:
| `CHATWOOT_ACCOUNT_ID` | Yes | - | Your Chatwoot account ID |
| `CHATWOOT_INBOX_ID` | Yes | - | The inbox ID for WhatsApp messages |
| `CHATWOOT_DEVICE_ID` | No | - | Specific device ID for outbound messages (required for multi-device setups) |
+| `CHATWOOT_IMPORT_MESSAGES` | No | `false` | Enable message history sync to Chatwoot |
+| `CHATWOOT_DAYS_LIMIT_IMPORT_MESSAGES` | No | `3` | Number of days of history to import |
### Configuration Examples
@@ -42,6 +44,10 @@ CHATWOOT_API_TOKEN=your_api_token_here
CHATWOOT_ACCOUNT_ID=12345
CHATWOOT_INBOX_ID=67890
CHATWOOT_DEVICE_ID=my-whatsapp-device
+
+# Optional: History sync settings
+CHATWOOT_IMPORT_MESSAGES=true
+CHATWOOT_DAYS_LIMIT_IMPORT_MESSAGES=7
```
**CLI Flags:**
@@ -135,6 +141,64 @@ CHATWOOT_DEVICE_ID=my-support-device
- If `CHATWOOT_DEVICE_ID` is **not set** and **multiple devices** exist, outbound messages will **fail**
- If the specified device is not found or not connected, outbound messages will fail with a `DEVICE_NOT_AVAILABLE` error
+## Message History Sync
+
+The history sync feature allows you to import existing WhatsApp message history into Chatwoot. This is useful when you want to have context from past conversations when starting to use Chatwoot.
+
+### Enabling Auto-Sync
+
+To automatically sync history when a device connects:
+
+```bash
+CHATWOOT_IMPORT_MESSAGES=true
+CHATWOOT_DAYS_LIMIT_IMPORT_MESSAGES=7 # Sync last 7 days
+```
+
+### Manual Sync via API
+
+You can trigger a sync manually using the REST API:
+
+**Start Sync:**
+```bash
+curl -X POST "http://your-api:3000/chatwoot/sync" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "device_id": "my-device-id",
+ "days_limit": 7,
+ "include_media": true,
+ "include_groups": true
+ }'
+```
+
+**Check Sync Status:**
+```bash
+curl "http://your-api:3000/chatwoot/sync/status?device_id=my-device-id"
+```
+
+### Sync Options
+
+| Option | Default | Description |
+|--------|---------|-------------|
+| `days_limit` | 3 | Number of days of history to import |
+| `include_media` | true | Download and sync media attachments |
+| `include_groups` | true | Include group chat messages |
+
+### How It Works
+
+1. **Reads stored messages** from the local chat storage database
+2. **Creates contacts** in Chatwoot for each chat participant
+3. **Creates conversations** for each chat
+4. **Imports messages** with timestamps, preserving chronological order
+5. **Downloads and attaches media** (if enabled and media is still available)
+
+### Notes
+
+- Messages are prefixed with their original timestamp for context: `[2024-01-15 14:30] Hello!`
+- Group messages include the sender name: `[2024-01-15 14:30] John: Hello!`
+- Media older than ~2 weeks may be unavailable on WhatsApp servers
+- The sync runs in the background and can be monitored via the status endpoint
+- Only one sync can run per device at a time
+
## Supported Features
### Incoming Messages (WhatsApp → Chatwoot)
@@ -150,6 +214,8 @@ CHATWOOT_DEVICE_ID=my-support-device
| Location | ✅ | Shown as text with coordinates |
| Contacts | ✅ | vCard information preserved |
+**Outgoing messages (sent from your own WhatsApp device)** are automatically forwarded to Chatwoot as `outgoing` messages.
+
### Outgoing Messages (Chatwoot → WhatsApp)
| Message Type | Supported | Notes |
@@ -328,6 +394,7 @@ Expected response: `200 OK` or error with details
- Consider network-level restrictions on the webhook endpoint
- Monitor for unusual activity in Chatwoot logs
- Use strong authentication for the WhatsApp API (`APP_BASIC_AUTH`)
+- **Note:** The `/chatwoot/webhook` endpoint is excluded from basic auth to allow Chatwoot to send webhooks without credentials. The `/chatwoot/sync` endpoints require authentication.
## API Reference
diff --git a/docs/openapi.yaml b/docs/openapi.yaml
index ef2f5ff2..2405bca6 100644
--- a/docs/openapi.yaml
+++ b/docs/openapi.yaml
@@ -27,6 +27,8 @@ tags:
description: Group setting
- name: newsletter
description: newsletter setting
+ - name: chatwoot
+ description: Chatwoot integration for customer support
security:
- basicAuth: []
@@ -3067,6 +3069,124 @@ paths:
schema:
$ref: '#/components/schemas/ErrorInternalServer'
+ /chatwoot/sync:
+ post:
+ operationId: chatwootSyncHistory
+ tags:
+ - chatwoot
+ summary: Sync message history to Chatwoot
+ description: |
+ Initiates a background sync of WhatsApp message history to Chatwoot.
+ Messages from the configured number of days will be imported.
+ This endpoint requires CHATWOOT_ENABLED=true in configuration.
+ requestBody:
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ device_id:
+ type: string
+ description: Device ID to sync (uses CHATWOOT_DEVICE_ID if not specified)
+ days_limit:
+ type: integer
+ default: 3
+ description: Number of days of history to sync
+ include_media:
+ type: boolean
+ default: true
+ description: Include media attachments in sync
+ include_groups:
+ type: boolean
+ default: true
+ description: Include group chats in sync
+ responses:
+ '200':
+ description: Sync initiated successfully
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ChatwootSyncResponse'
+ '400':
+ description: Bad Request (device not found or Chatwoot not configured)
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorBadRequest'
+ '409':
+ description: Sync already in progress
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ status:
+ type: integer
+ example: 409
+ code:
+ type: string
+ example: SYNC_ALREADY_RUNNING
+ message:
+ type: string
+ example: A sync is already in progress for this device
+ results:
+ type: object
+ properties:
+ progress:
+ $ref: '#/components/schemas/ChatwootSyncStatusResponse/properties/results'
+
+ /chatwoot/sync/status:
+ get:
+ operationId: chatwootSyncStatus
+ tags:
+ - chatwoot
+ summary: Get Chatwoot sync progress
+ description: Returns the current sync progress for a device
+ parameters:
+ - name: device_id
+ in: query
+ description: Device ID to check sync status for
+ schema:
+ type: string
+ responses:
+ '200':
+ description: Sync status retrieved
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ChatwootSyncStatusResponse'
+ '400':
+ description: Bad Request
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorBadRequest'
+
+ /chatwoot/webhook:
+ post:
+ operationId: chatwootWebhook
+ tags:
+ - chatwoot
+ summary: Chatwoot webhook endpoint
+ description: |
+ Receives webhook events from Chatwoot and sends messages to WhatsApp.
+ Configure this URL in your Chatwoot inbox webhook settings.
+ requestBody:
+ content:
+ application/json:
+ schema:
+ type: object
+ description: Chatwoot webhook payload (see Chatwoot documentation)
+ responses:
+ '200':
+ description: Webhook processed
+ '503':
+ description: Device not available
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorBadRequest'
+
components:
parameters:
DeviceIdHeader:
@@ -4316,3 +4436,79 @@ components:
type: string
example: '[email protected]'
description: The group ID
+
+ ChatwootSyncResponse:
+ type: object
+ properties:
+ status:
+ type: integer
+ example: 200
+ code:
+ type: string
+ example: SYNC_STARTED
+ message:
+ type: string
+ example: History sync initiated in background
+ results:
+ type: object
+ properties:
+ device_id:
+ type: string
+ example: my-device-id
+ days_limit:
+ type: integer
+ example: 3
+ include_media:
+ type: boolean
+ example: true
+ include_groups:
+ type: boolean
+ example: true
+ ChatwootSyncStatusResponse:
+ type: object
+ properties:
+ status:
+ type: integer
+ example: 200
+ code:
+ type: string
+ example: SUCCESS
+ message:
+ type: string
+ example: Sync status retrieved
+ results:
+ type: object
+ properties:
+ device_id:
+ type: string
+ example: my-device-id
+ status:
+ type: string
+ enum: [idle, running, completed, failed]
+ example: running
+ total_chats:
+ type: integer
+ example: 10
+ synced_chats:
+ type: integer
+ example: 5
+ total_messages:
+ type: integer
+ example: 100
+ synced_messages:
+ type: integer
+ example: 50
+ failed_messages:
+ type: integer
+ example: 2
+ current_chat:
+ type: string
+ example: "[email protected]"
+ started_at:
+ type: string
+ format: date-time
+ completed_at:
+ type: string
+ format: date-time
+ error:
+ type: string
diff --git a/docs/webhook-payload.md b/docs/webhook-payload.md
index 75864b72..83f76134 100644
--- a/docs/webhook-payload.md
+++ b/docs/webhook-payload.md
@@ -154,6 +154,7 @@ Fields commonly found inside the `payload` object:
| `from_lid` | string | LID (Linked ID) of the sender if available |
| `from_name` | string | Display name (pushname) of the sender |
| `timestamp` | string | RFC3339 formatted timestamp (e.g., `2023-10-15T10:30:00Z`) |
+| `is_from_me` | boolean | Whether the message was sent by the current user |
## Message Events
@@ -170,6 +171,7 @@ Fields commonly found inside the `payload` object:
"from_lid": "251556368777322@lid",
"from_name": "John Doe",
"timestamp": "2023-10-15T10:30:00Z",
+ "is_from_me": false,
"body": "Hello, how are you?"
}
}
@@ -187,6 +189,7 @@ Fields commonly found inside the `payload` object:
"from": "[email protected]",
"from_name": "John Doe",
"timestamp": "2023-10-15T10:35:00Z",
+ "is_from_me": false,
"body": "I'm doing great, thanks!",
"replied_to_id": "3EB0C127D7BACC83D6A1",
"quoted_body": "Hello, how are you?"
@@ -206,6 +209,7 @@ Fields commonly found inside the `payload` object:
"from": "[email protected]",
"from_name": "John Doe",
"timestamp": "2023-10-15T10:40:00Z",
+ "is_from_me": false,
"reaction": "👍",
"reacted_message_id": "3EB0C127D7BACC83D6A1"
}
@@ -802,6 +806,7 @@ Triggered when a message is deleted for the current user (DeleteForMe event).
"from": "[email protected]",
"from_name": "John Doe",
"timestamp": "2025-07-13T11:13:30Z",
+ "is_from_me": true,
"revoked_message_id": "94D13237B4D7F33EE4A63228BBD79EC0",
"revoked_from_me": true,
"revoked_chat": "[email protected]"
@@ -823,6 +828,7 @@ When a message is edited, the webhook includes the original message ID to track
"from": "[email protected]",
"from_name": "John Doe",
"timestamp": "2025-07-13T11:14:19Z",
+ "is_from_me": false,
"original_message_id": "94D13237B4D7F33EE4A63228BBD79EC0",
"body": "Updated message text"
}
diff --git a/readme.md b/readme.md
index 664d785d..2378ef12 100644
--- a/readme.md
+++ b/readme.md
@@ -206,7 +206,8 @@ To use environment variables:
| `CHATWOOT_ACCOUNT_ID` | Chatwoot account ID | - | `CHATWOOT_ACCOUNT_ID=12345` |
| `CHATWOOT_INBOX_ID` | Chatwoot inbox ID | - | `CHATWOOT_INBOX_ID=67890` |
| `CHATWOOT_DEVICE_ID` | WhatsApp device ID for Chatwoot (multi-device setup) | - | `[email protected]` |
-| `WHATSAPP_WEBHOOK_INCLUDE_OUTGOING` | Include outgoing messages in webhook notifications | `false` | `WHATSAPP_WEBHOOK_INCLUDE_OUTGOING=true` |
+| `CHATWOOT_IMPORT_MESSAGES` | Enable message history sync to Chatwoot | `false` | `CHATWOOT_IMPORT_MESSAGES=true` |
+| `CHATWOOT_DAYS_LIMIT_IMPORT_MESSAGES` | Days of history to import | `3` | `CHATWOOT_DAYS_LIMIT_IMPORT_MESSAGES=7` |
**Documentation:**
diff --git a/src/.env.example b/src/.env.example
index 9001706c..e68ae5ac 100644
--- a/src/.env.example
+++ b/src/.env.example
@@ -30,3 +30,5 @@ CHATWOOT_API_TOKEN=xxxxxxxx
CHATWOOT_ACCOUNT_ID=111111
CHATWOOT_INBOX_ID=000000
CHATWOOT_DEVICE_ID=
+CHATWOOT_IMPORT_MESSAGES=false
+CHATWOOT_DAYS_LIMIT_IMPORT_MESSAGES=3
diff --git a/src/cmd/rest.go b/src/cmd/rest.go
index 3f9f12ae..0a2a5d5d 100644
--- a/src/cmd/rest.go
+++ b/src/cmd/rest.go
@@ -76,6 +76,20 @@ func restServer(_ *cobra.Command, _ []string) {
AllowHeaders: "Origin, Content-Type, Accept",
}))
+ // Device manager - needed for chatwoot webhook
+ dm := whatsapp.GetDeviceManager()
+
+ // Chatwoot webhook - registered BEFORE basic auth middleware
+ // This allows Chatwoot to send webhooks without authentication
+ if config.ChatwootEnabled {
+ chatwootHandler := rest.NewChatwootHandler(appUsecase, sendUsecase, dm, chatStorageRepo)
+ webhookPath := "/chatwoot/webhook"
+ if config.AppBasePath != "" {
+ webhookPath = config.AppBasePath + webhookPath
+ }
+ app.Post(webhookPath, chatwootHandler.HandleWebhook)
+ }
+
if len(config.AppBasicAuthCredential) > 0 {
account := make(map[string]string)
for _, basicAuth := range config.AppBasicAuthCredential {
@@ -97,9 +111,6 @@ func restServer(_ *cobra.Command, _ []string) {
apiGroup = app.Group(config.AppBasePath)
}
- // Device manager aware routing
- dm := whatsapp.GetDeviceManager()
-
registerDeviceScopedRoutes := func(r fiber.Router) {
rest.InitRestApp(r, appUsecase)
rest.InitRestChat(r, chatUsecase)
@@ -118,10 +129,11 @@ func restServer(_ *cobra.Command, _ []string) {
headerDeviceGroup := apiGroup.Group("", middleware.DeviceMiddleware(dm))
registerDeviceScopedRoutes(headerDeviceGroup)
- // Chatwoot webhook - handles device resolution internally (not device-scoped)
+ // Chatwoot sync routes - require authentication (webhook is registered earlier without auth)
if config.ChatwootEnabled {
- chatwootHandler := rest.NewChatwootHandler(appUsecase, sendUsecase, dm)
- apiGroup.Post("/chatwoot/webhook", chatwootHandler.HandleWebhook)
+ chatwootHandler := rest.NewChatwootHandler(appUsecase, sendUsecase, dm, chatStorageRepo)
+ apiGroup.Post("/chatwoot/sync", chatwootHandler.SyncHistory)
+ apiGroup.Get("/chatwoot/sync/status", chatwootHandler.SyncStatus)
}
apiGroup.Get("/", func(c *fiber.Ctx) error {
diff --git a/src/cmd/root.go b/src/cmd/root.go
index 6722b7a8..31264631 100644
--- a/src/cmd/root.go
+++ b/src/cmd/root.go
@@ -137,9 +137,6 @@ func initEnvConfig() {
events := strings.Split(envWebhookEvents, ",")
config.WhatsappWebhookEvents = events
}
- if viper.IsSet("whatsapp_webhook_include_outgoing") {
- config.WhatsappWebhookIncludeOutgoing = viper.GetBool("whatsapp_webhook_include_outgoing")
- }
if viper.IsSet("whatsapp_account_validation") {
config.WhatsappAccountValidation = viper.GetBool("whatsapp_account_validation")
}
@@ -166,6 +163,13 @@ func initEnvConfig() {
if envChatwootDeviceID := viper.GetString("chatwoot_device_id"); envChatwootDeviceID != "" {
config.ChatwootDeviceID = envChatwootDeviceID
}
+ // Chatwoot History Sync settings
+ if viper.IsSet("chatwoot_import_messages") {
+ config.ChatwootImportMessages = viper.GetBool("chatwoot_import_messages")
+ }
+ if viper.IsSet("chatwoot_days_limit_import_messages") {
+ config.ChatwootDaysLimitImportMessages = viper.GetInt("chatwoot_days_limit_import_messages")
+ }
}
func initFlags() {
@@ -272,12 +276,6 @@ func initFlags() {
config.WhatsappWebhookEvents,
`whitelist of events to forward to webhook (empty = all events) --webhook-events <string> | example: --webhook-events="message,message.ack,group.participants"`,
)
- rootCmd.PersistentFlags().BoolVarP(
- &config.WhatsappWebhookIncludeOutgoing,
- "webhook-include-outgoing", "",
- config.WhatsappWebhookIncludeOutgoing,
- `include outgoing messages (sent from phone) in webhook notifications --webhook-include-outgoing <true/false> | example: --webhook-include-outgoing=true`,
- )
rootCmd.PersistentFlags().BoolVarP(
&config.WhatsappAccountValidation,
"account-validation", "",
@@ -304,6 +302,18 @@ func initFlags() {
config.ChatwootDeviceID,
`device ID for Chatwoot outbound messages --chatwoot-device-id <string> | example: --chatwoot-device-id="my-device"`,
)
+ rootCmd.PersistentFlags().BoolVarP(
+ &config.ChatwootImportMessages,
+ "chatwoot-import-messages", "",
+ config.ChatwootImportMessages,
+ `enable message history import to Chatwoot --chatwoot-import-messages <true/false> | example: --chatwoot-import-messages=true`,
+ )
+ rootCmd.PersistentFlags().IntVarP(
+ &config.ChatwootDaysLimitImportMessages,
+ "chatwoot-days-limit-import-messages", "",
+ config.ChatwootDaysLimitImportMessages,
+ `days of message history to import to Chatwoot --chatwoot-days-limit-import-messages <int> | example: --chatwoot-days-limit-import-messages=7`,
+ )
}
func initChatStorage() (*sql.DB, error) {
diff --git a/src/config/settings.go b/src/config/settings.go
index 1db89f39..d29ee200 100644
--- a/src/config/settings.go
+++ b/src/config/settings.go
@@ -33,7 +33,6 @@ var (
WhatsappWebhookSecret = "secret"
WhatsappWebhookInsecureSkipVerify = false // Skip TLS certificate verification for webhooks (insecure)
WhatsappWebhookEvents []string // Whitelist of events to forward to webhook (empty = all events)
- WhatsappWebhookIncludeOutgoing = false // Include outgoing messages (sent from phone) in webhook notifications
WhatsappAutoRejectCall = false // Auto-reject incoming calls
WhatsappLogLevel = "ERROR"
WhatsappSettingMaxImageSize int64 = 20000000 // 20MB
@@ -54,4 +53,8 @@ var (
ChatwootAccountID = 0
ChatwootInboxID = 0
ChatwootDeviceID = "" // Device ID for outbound messages (required for multi-device)
+
+ // Chatwoot History Sync settings
+ ChatwootImportMessages = false // Enable message history import to Chatwoot
+ ChatwootDaysLimitImportMessages = 3 // Days of history to import (default: 3)
)
diff --git a/src/infrastructure/chatwoot/client.go b/src/infrastructure/chatwoot/client.go
index f576763e..5ad5f446 100644
--- a/src/infrastructure/chatwoot/client.go
+++ b/src/infrastructure/chatwoot/client.go
@@ -31,6 +31,12 @@ type Client struct {
var (
defaultClient *Client
defaultClientOnce sync.Once
+
+ // sentMessageIDs tracks Chatwoot message IDs created by our API to prevent
+ // echo loops: WhatsApp msg → synced to Chatwoot → Chatwoot webhook fires →
+ // would re-send to WhatsApp without this guard.
+ sentMessageIDs sync.Map
+ sentMessageIDsTTL = 5 * time.Minute
)
// GetDefaultClient returns a shared Chatwoot client instance.
@@ -42,6 +48,47 @@ func GetDefaultClient() *Client {
return defaultClient
}
+func MarkMessageAsSent(messageID int) {
+ if messageID == 0 {
+ return
+ }
+ sentMessageIDs.Store(messageID, time.Now())
+}
+
+func IsMessageSentByUs(messageID int) bool {
+ if messageID == 0 {
+ return false
+ }
+ val, ok := sentMessageIDs.Load(messageID)
+ if !ok {
+ return false
+ }
+ storedAt := val.(time.Time)
+ if time.Since(storedAt) > sentMessageIDsTTL {
+ sentMessageIDs.Delete(messageID)
+ return false
+ }
+ // Don't delete on check — Chatwoot may fire multiple webhook events
+ // (e.g. message_created + conversation_updated) for the same message.
+ // Entries are cleaned up by the background sweeper after TTL expires.
+ return true
+}
+
+func init() {
+ go func() {
+ ticker := time.NewTicker(sentMessageIDsTTL)
+ defer ticker.Stop()
+ for range ticker.C {
+ sentMessageIDs.Range(func(key, value interface{}) bool {
+ if time.Since(value.(time.Time)) > sentMessageIDsTTL {
+ sentMessageIDs.Delete(key)
+ }
+ return true
+ })
+ }
+ }()
+}
+
func NewClient() *Client {
return &Client{
BaseURL: strings.TrimRight(config.ChatwootURL, "/"),
@@ -107,15 +154,15 @@ func (c *Client) doRequest(method, endpoint string, payload interface{}, result
func (c *Client) FindContactByIdentifier(identifier string, isGroup bool) (*Contact, error) {
endpoint := fmt.Sprintf("%s/api/v1/accounts/%d/contacts/search", c.BaseURL, c.AccountID)
+ logrus.Debugf("Chatwoot: Finding contact by identifier endpoint=%s identifier=%s isGroup=%v", endpoint, identifier, isGroup)
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 {
+ isIdentifierBased := isGroup || strings.HasSuffix(identifier, "@lid")
+ if !isIdentifierBased {
searchTerm = utils.NormalizePhoneE164(identifier)
}
@@ -131,7 +178,8 @@ func (c *Client) FindContactByIdentifier(identifier string, isGroup bool) (*Cont
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
- return nil, fmt.Errorf("failed to search contact: status %d", resp.StatusCode)
+ body, _ := io.ReadAll(resp.Body)
+ return nil, fmt.Errorf("failed to search contact: status %d body %s", resp.StatusCode, string(body))
}
var result struct {
@@ -144,12 +192,10 @@ func (c *Client) FindContactByIdentifier(identifier string, isGroup bool) (*Cont
// 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 isIdentifierBased {
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
}
@@ -168,9 +214,9 @@ func (c *Client) CreateContact(name, identifier string, isGroup bool) (*Contact,
// For groups, use Identifier field
// For private chats, use E.164 phone format
+ // For @lid JIDs (non-phone WhatsApp IDs), use Identifier field
var phoneNumber, contactIdentifier string
- if isGroup {
- // Use the group JID as the identifier
+ if isGroup || strings.HasSuffix(identifier, "@lid") {
contactIdentifier = identifier
} else {
phoneNumber = utils.NormalizePhoneE164(identifier)
@@ -213,21 +259,31 @@ func (c *Client) CreateContact(name, identifier string, isGroup bool) (*Contact,
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 {
+ // Chatwoot API returns: {"payload": {"contact": {...}, "contact_inbox": {...}}}
+ var nestedResult struct {
+ Payload struct {
+ Contact Contact `json:"contact"`
+ } `json:"payload"`
+ }
+ if err := json.Unmarshal(bodyBytes, &nestedResult); err == nil && nestedResult.Payload.Contact.ID != 0 {
+ return &nestedResult.Payload.Contact, nil
+ }
+
+ // Fallback: some Chatwoot versions return {"payload": Contact{...}} directly
+ var flatResult struct {
Payload Contact `json:"payload"`
}
- if err := json.Unmarshal(bodyBytes, &result); err == nil && result.Payload.ID != 0 {
- return &result.Payload, nil
+ if err := json.Unmarshal(bodyBytes, &flatResult); err == nil && flatResult.Payload.ID != 0 {
+ return &flatResult.Payload, nil
}
- // Try direct decode (some Chatwoot versions return contact directly)
+ // Last resort: try direct decode (contact at root level)
var contact Contact
- if err := json.Unmarshal(bodyBytes, &contact); err != nil {
- return nil, fmt.Errorf("failed to decode contact response: %v", err)
+ if err := json.Unmarshal(bodyBytes, &contact); err == nil && contact.ID != 0 {
+ return &contact, nil
}
- return &contact, nil
+ return nil, fmt.Errorf("failed to decode contact response (no valid ID found): %s", string(bodyBytes))
}
func (c *Client) FindOrCreateContact(name, identifier string, isGroup bool) (*Contact, error) {
@@ -364,25 +420,22 @@ func (c *Client) CreateConversation(contactID int) (*Conversation, error) {
return nil, fmt.Errorf("failed to create conversation: status %d body %s", resp.StatusCode, string(body))
}
+ bodyBytes, _ := io.ReadAll(resp.Body)
+ logrus.Debugf("Chatwoot CreateConversation: Response body=%s", string(bodyBytes))
+
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 {
+ if err := json.Unmarshal(bodyBytes, &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
+ if err := json.Unmarshal(bodyBytes, &conversation); err == nil && conversation.ID != 0 {
+ return &conversation, nil
}
- return &conversation, nil
+
+ return nil, fmt.Errorf("failed to decode conversation response (no valid ID found): %s", string(bodyBytes))
}
func (c *Client) FindOrCreateConversation(contactID int) (*Conversation, error) {
@@ -396,7 +449,7 @@ func (c *Client) FindOrCreateConversation(contactID int) (*Conversation, error)
return c.CreateConversation(contactID)
}
-func (c *Client) CreateMessage(conversationID int, content string, messageType string, attachments []string) error {
+func (c *Client) CreateMessage(conversationID int, content string, messageType string, attachments []string) (int, error) {
endpoint := fmt.Sprintf("%s/api/v1/accounts/%d/conversations/%d/messages", c.BaseURL, c.AccountID, conversationID)
if len(attachments) > 0 {
@@ -411,11 +464,11 @@ func (c *Client) CreateMessage(conversationID int, content string, messageType s
jsonPayload, err := json.Marshal(payload)
if err != nil {
- return fmt.Errorf("failed to marshal message payload: %w", err)
+ return 0, fmt.Errorf("failed to marshal message payload: %w", err)
}
req, err := http.NewRequest("POST", endpoint, bytes.NewBuffer(jsonPayload))
if err != nil {
- return err
+ return 0, err
}
req.Header.Set("Content-Type", "application/json")
@@ -423,19 +476,27 @@ func (c *Client) CreateMessage(conversationID int, content string, messageType s
resp, err := c.HTTPClient.Do(req)
if err != nil {
- return err
+ return 0, err
}
defer resp.Body.Close()
+ bodyBytes, _ := io.ReadAll(resp.Body)
+
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 0, fmt.Errorf("failed to create message: status %d body %s", resp.StatusCode, string(bodyBytes))
}
- return nil
+ var result struct {
+ ID int `json:"id"`
+ }
+ if err := json.Unmarshal(bodyBytes, &result); err == nil && result.ID != 0 {
+ return result.ID, nil
+ }
+
+ return 0, nil
}
-func (c *Client) createMessageWithAttachments(endpoint, content, messageType string, attachments []string) error {
+func (c *Client) createMessageWithAttachments(endpoint, content, messageType string, attachments []string) (int, error) {
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
@@ -454,17 +515,14 @@ func (c *Client) createMessageWithAttachments(endpoint, content, messageType str
}
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
+ // Custom form part with correct Content-Type for Chatwoot to render images inline
h := make(textproto.MIMEHeader)
h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="attachments[]"; filename="%s"`, fileName))
h.Set("Content-Type", mimeType)
@@ -482,7 +540,7 @@ func (c *Client) createMessageWithAttachments(endpoint, content, messageType str
req, err := http.NewRequest("POST", endpoint, body)
if err != nil {
- return err
+ return 0, err
}
req.Header.Set("Content-Type", writer.FormDataContentType())
@@ -490,14 +548,22 @@ func (c *Client) createMessageWithAttachments(endpoint, content, messageType str
resp, err := c.HTTPClient.Do(req)
if err != nil {
- return err
+ return 0, err
}
defer resp.Body.Close()
+ respBody, _ := io.ReadAll(resp.Body)
+
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 0, fmt.Errorf("failed to create message with attachments: status %d body %s", resp.StatusCode, string(respBody))
}
- return nil
+ var result struct {
+ ID int `json:"id"`
+ }
+ if err := json.Unmarshal(respBody, &result); err == nil && result.ID != 0 {
+ return result.ID, nil
+ }
+
+ return 0, nil
}
diff --git a/src/infrastructure/chatwoot/sync.go b/src/infrastructure/chatwoot/sync.go
new file mode 100644
index 00000000..4d700dff
--- /dev/null
+++ b/src/infrastructure/chatwoot/sync.go
@@ -0,0 +1,437 @@
+package chatwoot
+
+import (
+ "context"
+ "fmt"
+ "os"
+ "path/filepath"
+ "sort"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/config"
+ domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
+ "github.com/sirupsen/logrus"
+ "go.mau.fi/whatsmeow"
+ "go.mau.fi/whatsmeow/proto/waE2E"
+ "google.golang.org/protobuf/proto"
+)
+
+// SyncService handles message history synchronization to Chatwoot
+type SyncService struct {
+ client *Client
+ chatStorageRepo domainChatStorage.IChatStorageRepository
+
+ // Track sync progress per device
+ progressMap map[string]*SyncProgress
+ progressMu sync.RWMutex
+}
+
+// NewSyncService creates a new sync service instance
+func NewSyncService(
+ client *Client,
+ chatStorageRepo domainChatStorage.IChatStorageRepository,
+) *SyncService {
+ return &SyncService{
+ client: client,
+ chatStorageRepo: chatStorageRepo,
+ progressMap: make(map[string]*SyncProgress),
+ }
+}
+
+// GetProgress returns the current sync progress for a device
+func (s *SyncService) GetProgress(deviceID string) *SyncProgress {
+ s.progressMu.RLock()
+ defer s.progressMu.RUnlock()
+
+ if progress, ok := s.progressMap[deviceID]; ok {
+ cloned := progress.Clone()
+ return &cloned
+ }
+ return nil
+}
+
+// IsRunning returns true if a sync is currently running for the device
+func (s *SyncService) IsRunning(deviceID string) bool {
+ s.progressMu.RLock()
+ defer s.progressMu.RUnlock()
+
+ if progress, ok := s.progressMap[deviceID]; ok {
+ return progress.IsRunning()
+ }
+ return false
+}
+
+// SyncHistory performs the initial message history sync to Chatwoot
+func (s *SyncService) SyncHistory(ctx context.Context, deviceID string, waClient *whatsmeow.Client, opts SyncOptions) (*SyncProgress, error) {
+ // Atomic check-and-set to prevent race condition
+ progress := NewSyncProgress(deviceID)
+ s.progressMu.Lock()
+ if existing, ok := s.progressMap[deviceID]; ok && existing.IsRunning() {
+ s.progressMu.Unlock()
+ cloned := existing.Clone()
+ return &cloned, fmt.Errorf("sync already in progress for device %s", deviceID)
+ }
+ s.progressMap[deviceID] = progress
+ s.progressMu.Unlock()
+
+ progress.SetRunning()
+
+ logrus.Infof("Chatwoot Sync: Starting history sync for device %s (days: %d, media: %v, groups: %v)",
+ deviceID, opts.DaysLimit, opts.IncludeMedia, opts.IncludeGroups)
+
+ // 1. Get all chats for this device
+ chats, err := s.chatStorageRepo.GetChats(&domainChatStorage.ChatFilter{
+ DeviceID: deviceID,
+ })
+ if err != nil {
+ progress.SetFailed(err)
+ return progress, fmt.Errorf("failed to get chats: %w", err)
+ }
+
+ progress.SetTotals(len(chats), 0)
+ logrus.Infof("Chatwoot Sync: Found %d chats to sync", len(chats))
+
+ // 2. Calculate time boundary
+ sinceTime := time.Now().AddDate(0, 0, -opts.DaysLimit)
+
+ // 3. Process each chat
+ for _, chat := range chats {
+ if err := ctx.Err(); err != nil {
+ progress.SetFailed(err)
+ return progress, err // Context cancelled
+ }
+
+ progress.UpdateChat(chat.JID)
+
+ err := s.syncChat(ctx, deviceID, chat, sinceTime, waClient, opts, progress)
+ if err != nil {
+ logrus.Errorf("Chatwoot Sync: Failed to sync chat %s: %v", chat.JID, err)
+ progress.IncrementFailedChats()
+ // Continue with other chats
+ } else {
+ progress.IncrementSyncedChats()
+ }
+ }
+
+ progress.SetCompleted()
+ logrus.Infof("Chatwoot Sync: Completed for device %s. Chats: %d (failed: %d), Messages: %d (failed: %d)",
+ deviceID, progress.SyncedChats, progress.FailedChats, progress.SyncedMessages, progress.FailedMessages)
+
+ return progress, nil
+}
+
+// syncChat syncs a single chat's messages to Chatwoot
+func (s *SyncService) syncChat(
+ ctx context.Context,
+ deviceID string,
+ chat *domainChatStorage.Chat,
+ sinceTime time.Time,
+ waClient *whatsmeow.Client,
+ opts SyncOptions,
+ progress *SyncProgress,
+) error {
+ isGroup := strings.HasSuffix(chat.JID, "@g.us")
+
+ // Skip groups if not configured
+ if isGroup && !opts.IncludeGroups {
+ logrus.Debugf("Chatwoot Sync: Skipping group %s (groups disabled)", chat.JID)
+ return nil
+ }
+
+ logrus.Infof("Chatwoot Sync: Processing chat %s (%s)", chat.Name, chat.JID)
+
+ // 1. Find or create contact in Chatwoot
+ contactName := chat.Name
+ if contactName == "" {
+ contactName = utils.ExtractPhoneFromJID(chat.JID)
+ }
+
+ contact, err := s.client.FindOrCreateContact(contactName, chat.JID, isGroup)
+ if err != nil {
+ return fmt.Errorf("failed to create contact: %w", err)
+ }
+ logrus.Debugf("Chatwoot Sync: Contact ID: %d", contact.ID)
+
+ // 2. Find or create conversation
+ conversation, err := s.client.FindOrCreateConversation(contact.ID)
+ if err != nil {
+ return fmt.Errorf("failed to create conversation: %w", err)
+ }
+ logrus.Debugf("Chatwoot Sync: Conversation ID: %d", conversation.ID)
+
+ // 3. Get messages since time boundary
+ messages, err := s.chatStorageRepo.GetMessages(&domainChatStorage.MessageFilter{
+ DeviceID: deviceID,
+ ChatJID: chat.JID,
+ StartTime: &sinceTime,
+ Limit: opts.MaxMessagesPerChat,
+ })
+ if err != nil {
+ return fmt.Errorf("failed to get messages: %w", err)
+ }
+
+ if len(messages) == 0 {
+ logrus.Debugf("Chatwoot Sync: No messages to sync for %s", chat.JID)
+ return nil
+ }
+
+ progress.AddMessages(len(messages))
+ logrus.Infof("Chatwoot Sync: Found %d messages for %s", len(messages), chat.JID)
+
+ // 4. Sort messages by timestamp (oldest first for proper ordering)
+ sort.Slice(messages, func(i, j int) bool {
+ return messages[i].Timestamp.Before(messages[j].Timestamp)
+ })
+
+ // 5. Sync each message
+ for i, msg := range messages {
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+
+ err := s.syncMessage(ctx, conversation.ID, msg, waClient, opts, isGroup)
+ if err != nil {
+ logrus.Warnf("Chatwoot Sync: Failed to sync message %s: %v", msg.ID, err)
+ progress.IncrementFailedMessages()
+ // Continue with other messages
+ } else {
+ progress.IncrementSyncedMessages()
+ }
+
+ // Rate limiting: pause between batches
+ if i > 0 && i%opts.BatchSize == 0 {
+ time.Sleep(opts.DelayBetweenBatches)
+ }
+ }
+
+ return nil
+}
+
+// syncMessage syncs a single message to Chatwoot
+func (s *SyncService) syncMessage(
+ ctx context.Context,
+ conversationID int,
+ msg *domainChatStorage.Message,
+ waClient *whatsmeow.Client,
+ opts SyncOptions,
+ isGroup bool,
+) error {
+ // Determine message type: "incoming" or "outgoing"
+ messageType := "incoming"
+ if msg.IsFromMe {
+ messageType = "outgoing"
+ }
+
+ // Build content
+ content := msg.Content
+ if content == "" && msg.MediaType != "" {
+ content = fmt.Sprintf("[%s]", msg.MediaType) // Placeholder for media-only
+ }
+
+ // Add timestamp prefix for historical context
+ timePrefix := msg.Timestamp.Format("2006-01-02 15:04")
+
+ // For group messages, add sender info
+ if isGroup && !msg.IsFromMe && msg.Sender != "" {
+ senderName := utils.ExtractPhoneFromJID(msg.Sender)
+ content = fmt.Sprintf("[%s] %s: %s", timePrefix, senderName, content)
+ } else {
+ content = fmt.Sprintf("[%s] %s", timePrefix, content)
+ }
+
+ var attachments []string
+
+ // Handle media if enabled and present
+ if opts.IncludeMedia && msg.MediaType != "" && msg.URL != "" && len(msg.MediaKey) > 0 {
+ filePath, err := s.downloadMedia(ctx, msg, waClient)
+ if err != nil {
+ logrus.Debugf("Chatwoot Sync: Failed to download media for message %s: %v", msg.ID, err)
+ // Continue without media - it might be expired
+ content += " [media unavailable]"
+ } else if filePath != "" {
+ attachments = append(attachments, filePath)
+ }
+ }
+
+ // Send to Chatwoot and register the returned ID in the dedup cache so the
+ // resulting webhook event is recognized as "ours" and not forwarded back to WhatsApp.
+ msgID, err := s.client.CreateMessage(conversationID, content, messageType, attachments)
+
+ for _, fp := range attachments {
+ if err := os.Remove(fp); err != nil {
+ logrus.Debugf("Chatwoot Sync: Failed to remove temp file %s: %v", fp, err)
+ }
+ }
+
+ if err != nil {
+ return fmt.Errorf("failed to create message: %w", err)
+ }
+
+ MarkMessageAsSent(msgID)
+
+ return nil
+}
+
+// downloadMedia downloads media for a message and returns the temp file path
+func (s *SyncService) downloadMedia(ctx context.Context, msg *domainChatStorage.Message, waClient *whatsmeow.Client) (string, error) {
+ if msg.URL == "" || len(msg.MediaKey) == 0 {
+ return "", fmt.Errorf("missing media URL or key")
+ }
+
+ if waClient == nil {
+ return "", fmt.Errorf("WhatsApp client not available")
+ }
+
+ // Create downloadable message based on type
+ var downloadable whatsmeow.DownloadableMessage
+
+ switch msg.MediaType {
+ case "image":
+ downloadable = &waE2E.ImageMessage{
+ URL: proto.String(msg.URL),
+ MediaKey: msg.MediaKey,
+ FileSHA256: msg.FileSHA256,
+ FileEncSHA256: msg.FileEncSHA256,
+ FileLength: proto.Uint64(msg.FileLength),
+ }
+ case "video":
+ downloadable = &waE2E.VideoMessage{
+ URL: proto.String(msg.URL),
+ MediaKey: msg.MediaKey,
+ FileSHA256: msg.FileSHA256,
+ FileEncSHA256: msg.FileEncSHA256,
+ FileLength: proto.Uint64(msg.FileLength),
+ }
+ case "audio", "ptt":
+ downloadable = &waE2E.AudioMessage{
+ URL: proto.String(msg.URL),
+ MediaKey: msg.MediaKey,
+ FileSHA256: msg.FileSHA256,
+ FileEncSHA256: msg.FileEncSHA256,
+ FileLength: proto.Uint64(msg.FileLength),
+ }
+ case "document":
+ downloadable = &waE2E.DocumentMessage{
+ URL: proto.String(msg.URL),
+ MediaKey: msg.MediaKey,
+ FileSHA256: msg.FileSHA256,
+ FileEncSHA256: msg.FileEncSHA256,
+ FileLength: proto.Uint64(msg.FileLength),
+ }
+ case "sticker":
+ downloadable = &waE2E.StickerMessage{
+ URL: proto.String(msg.URL),
+ MediaKey: msg.MediaKey,
+ FileSHA256: msg.FileSHA256,
+ FileEncSHA256: msg.FileEncSHA256,
+ FileLength: proto.Uint64(msg.FileLength),
+ }
+ default:
+ return "", fmt.Errorf("unsupported media type: %s", msg.MediaType)
+ }
+
+ // Download
+ data, err := waClient.Download(ctx, downloadable)
+ if err != nil {
+ return "", fmt.Errorf("download failed: %w", err)
+ }
+
+ // Write to temp file
+ ext := getExtensionForMediaType(msg.MediaType, msg.Filename)
+ tmpFile, err := os.CreateTemp("", fmt.Sprintf("chatwoot-sync-*%s", ext))
+ if err != nil {
+ return "", fmt.Errorf("failed to create temp file: %w", err)
+ }
+ defer tmpFile.Close()
+
+ if _, err := tmpFile.Write(data); err != nil {
+ os.Remove(tmpFile.Name())
+ return "", fmt.Errorf("failed to write media: %w", err)
+ }
+
+ return tmpFile.Name(), nil
+}
+
+// getExtensionForMediaType returns the file extension for a media type
+func getExtensionForMediaType(mediaType, filename string) string {
+ if filename != "" {
+ if ext := filepath.Ext(filename); ext != "" {
+ return ext
+ }
+ }
+ switch mediaType {
+ case "image":
+ return ".jpg"
+ case "video":
+ return ".mp4"
+ case "audio", "ptt":
+ return ".ogg"
+ case "document":
+ return ".bin"
+ case "sticker":
+ return ".webp"
+ default:
+ return ""
+ }
+}
+
+// Global sync service instance for REST endpoints
+var (
+ globalSyncService *SyncService
+ globalSyncServiceOnce sync.Once
+)
+
+// GetSyncService returns a shared sync service instance
+func GetSyncService(
+ client *Client,
+ chatStorageRepo domainChatStorage.IChatStorageRepository,
+) *SyncService {
+ globalSyncServiceOnce.Do(func() {
+ globalSyncService = NewSyncService(client, chatStorageRepo)
+ })
+ return globalSyncService
+}
+
+// GetDefaultSyncService returns the global sync service if initialized
+func GetDefaultSyncService() *SyncService {
+ return globalSyncService
+}
+
+// TriggerAutoSync is called when a device connects to optionally start auto-sync
+func TriggerAutoSync(deviceID string, chatStorageRepo domainChatStorage.IChatStorageRepository, waClient *whatsmeow.Client) {
+ if !config.ChatwootEnabled || !config.ChatwootImportMessages {
+ return
+ }
+
+ client := GetDefaultClient()
+ if !client.IsConfigured() {
+ logrus.Warn("Chatwoot Sync: Auto-sync skipped - Chatwoot not configured")
+ return
+ }
+
+ // Resolve the storage device ID (JID) from the WhatsApp client,
+ // since chats are stored under the full JID, not the user-assigned alias.
+ storageDeviceID := deviceID
+ if waClient != nil && waClient.Store != nil && waClient.Store.ID != nil {
+ if jid := waClient.Store.ID.ToNonAD().String(); jid != "" {
+ storageDeviceID = jid
+ }
+ }
+
+ syncService := GetSyncService(client, chatStorageRepo)
+
+ go func() {
+ opts := DefaultSyncOptions()
+ opts.DaysLimit = config.ChatwootDaysLimitImportMessages
+
+ logrus.Infof("Chatwoot Sync: Auto-sync triggered for device %s", storageDeviceID)
+
+ _, err := syncService.SyncHistory(context.Background(), storageDeviceID, waClient, opts)
+ if err != nil {
+ logrus.Errorf("Chatwoot Sync: Auto-sync failed for device %s: %v", storageDeviceID, err)
+ }
+ }()
+}
diff --git a/src/infrastructure/chatwoot/sync_test.go b/src/infrastructure/chatwoot/sync_test.go
new file mode 100644
index 00000000..e6e699d6
--- /dev/null
+++ b/src/infrastructure/chatwoot/sync_test.go
@@ -0,0 +1,190 @@
+package chatwoot
+
+import (
+ "testing"
+ "time"
+)
+
+func TestSyncProgress_SetRunning(t *testing.T) {
+ p := NewSyncProgress("test-device")
+
+ if p.Status != "idle" {
+ t.Errorf("expected initial status 'idle', got '%s'", p.Status)
+ }
+
+ p.SetRunning()
+
+ if p.Status != "running" {
+ t.Errorf("expected status 'running', got '%s'", p.Status)
+ }
+
+ if p.StartedAt == nil {
+ t.Error("expected StartedAt to be set")
+ }
+}
+
+func TestSyncProgress_SetCompleted(t *testing.T) {
+ p := NewSyncProgress("test-device")
+ p.SetRunning()
+ p.SetCompleted()
+
+ if p.Status != "completed" {
+ t.Errorf("expected status 'completed', got '%s'", p.Status)
+ }
+
+ if p.CompletedAt == nil {
+ t.Error("expected CompletedAt to be set")
+ }
+}
+
+func TestSyncProgress_SetFailed(t *testing.T) {
+ p := NewSyncProgress("test-device")
+ p.SetRunning()
+
+ testErr := &testError{msg: "test error"}
+ p.SetFailed(testErr)
+
+ if p.Status != "failed" {
+ t.Errorf("expected status 'failed', got '%s'", p.Status)
+ }
+
+ if p.Error != "test error" {
+ t.Errorf("expected error 'test error', got '%s'", p.Error)
+ }
+}
+
+func TestSyncProgress_Counters(t *testing.T) {
+ p := NewSyncProgress("test-device")
+
+ p.SetTotals(10, 100)
+ if p.TotalChats != 10 || p.TotalMessages != 100 {
+ t.Errorf("expected totals (10, 100), got (%d, %d)", p.TotalChats, p.TotalMessages)
+ }
+
+ p.IncrementSyncedChats()
+ p.IncrementSyncedChats()
+ if p.SyncedChats != 2 {
+ t.Errorf("expected synced chats 2, got %d", p.SyncedChats)
+ }
+
+ p.IncrementSyncedMessages()
+ p.IncrementSyncedMessages()
+ p.IncrementSyncedMessages()
+ if p.SyncedMessages != 3 {
+ t.Errorf("expected synced messages 3, got %d", p.SyncedMessages)
+ }
+
+ p.IncrementFailedMessages()
+ if p.FailedMessages != 1 {
+ t.Errorf("expected failed messages 1, got %d", p.FailedMessages)
+ }
+
+ p.AddMessages(50)
+ if p.TotalMessages != 150 {
+ t.Errorf("expected total messages 150, got %d", p.TotalMessages)
+ }
+}
+
+func TestSyncProgress_Clone(t *testing.T) {
+ p := NewSyncProgress("test-device")
+ p.SetRunning()
+ p.SetTotals(10, 100)
+ p.IncrementSyncedChats()
+ p.UpdateChat("test-chat")
+
+ cloned := p.Clone()
+
+ if cloned.DeviceID != p.DeviceID {
+ t.Error("clone DeviceID mismatch")
+ }
+ if cloned.Status != p.Status {
+ t.Error("clone Status mismatch")
+ }
+ if cloned.TotalChats != p.TotalChats {
+ t.Error("clone TotalChats mismatch")
+ }
+ if cloned.CurrentChat != p.CurrentChat {
+ t.Error("clone CurrentChat mismatch")
+ }
+}
+
+func TestSyncProgress_IsRunning(t *testing.T) {
+ p := NewSyncProgress("test-device")
+
+ if p.IsRunning() {
+ t.Error("expected IsRunning false initially")
+ }
+
+ p.SetRunning()
+ if !p.IsRunning() {
+ t.Error("expected IsRunning true after SetRunning")
+ }
+
+ p.SetCompleted()
+ if p.IsRunning() {
+ t.Error("expected IsRunning false after SetCompleted")
+ }
+}
+
+func TestDefaultSyncOptions(t *testing.T) {
+ opts := DefaultSyncOptions()
+
+ if opts.DaysLimit != 3 {
+ t.Errorf("expected DaysLimit 3, got %d", opts.DaysLimit)
+ }
+
+ if !opts.IncludeMedia {
+ t.Error("expected IncludeMedia true")
+ }
+
+ if !opts.IncludeGroups {
+ t.Error("expected IncludeGroups true")
+ }
+
+ if opts.MaxMessagesPerChat != 500 {
+ t.Errorf("expected MaxMessagesPerChat 500, got %d", opts.MaxMessagesPerChat)
+ }
+
+ if opts.BatchSize != 10 {
+ t.Errorf("expected BatchSize 10, got %d", opts.BatchSize)
+ }
+
+ if opts.DelayBetweenBatches != 500*time.Millisecond {
+ t.Errorf("expected DelayBetweenBatches 500ms, got %v", opts.DelayBetweenBatches)
+ }
+}
+
+func TestGetExtensionForMediaType(t *testing.T) {
+ tests := []struct {
+ mediaType string
+ filename string
+ expected string
+ }{
+ {"image", "", ".jpg"},
+ {"video", "", ".mp4"},
+ {"audio", "", ".ogg"},
+ {"ptt", "", ".ogg"},
+ {"document", "", ".bin"},
+ {"sticker", "", ".webp"},
+ {"unknown", "", ""},
+ {"image", "photo.png", ".png"},
+ {"document", "report.pdf", ".pdf"},
+ }
+
+ for _, tt := range tests {
+ result := getExtensionForMediaType(tt.mediaType, tt.filename)
+ if result != tt.expected {
+ t.Errorf("getExtensionForMediaType(%s, %s) = %s, expected %s",
+ tt.mediaType, tt.filename, result, tt.expected)
+ }
+ }
+}
+
+// testError is a simple error implementation for testing
+type testError struct {
+ msg string
+}
+
+func (e *testError) Error() string {
+ return e.msg
+}
diff --git a/src/infrastructure/chatwoot/sync_types.go b/src/infrastructure/chatwoot/sync_types.go
new file mode 100644
index 00000000..5285980b
--- /dev/null
+++ b/src/infrastructure/chatwoot/sync_types.go
@@ -0,0 +1,188 @@
+package chatwoot
+
+import (
+ "sync"
+ "time"
+)
+
+// SyncState tracks what has been synced to avoid duplicates
+type SyncState struct {
+ DeviceID string `db:"device_id"`
+ ChatJID string `db:"chat_jid"`
+ LastSyncedMsgID string `db:"last_synced_msg_id"`
+ LastSyncedTime time.Time `db:"last_synced_time"`
+ SyncStatus string `db:"sync_status"` // pending, in_progress, completed, failed
+ MessagesSynced int `db:"messages_synced"`
+ MessagesFailed int `db:"messages_failed"`
+ CreatedAt time.Time `db:"created_at"`
+ UpdatedAt time.Time `db:"updated_at"`
+}
+
+// SyncProgress tracks overall sync progress
+type SyncProgress struct {
+ DeviceID string `json:"device_id"`
+ Status string `json:"status"` // idle, running, completed, failed
+ TotalChats int `json:"total_chats"`
+ SyncedChats int `json:"synced_chats"`
+ FailedChats int `json:"failed_chats"`
+ TotalMessages int `json:"total_messages"`
+ SyncedMessages int `json:"synced_messages"`
+ FailedMessages int `json:"failed_messages"`
+ CurrentChat string `json:"current_chat,omitempty"`
+ StartedAt *time.Time `json:"started_at,omitempty"`
+ CompletedAt *time.Time `json:"completed_at,omitempty"`
+ Error string `json:"error,omitempty"`
+ mu sync.RWMutex
+}
+
+// SyncOptions configures the sync behavior
+type SyncOptions struct {
+ DaysLimit int // Days of history to import
+ IncludeMedia bool // Download and sync media attachments
+ IncludeGroups bool // Include group chats
+ MaxMessagesPerChat int // Limit messages per chat to prevent huge syncs
+ BatchSize int // Messages per batch (for rate limiting)
+ DelayBetweenBatches time.Duration // Delay between batches
+}
+
+// SyncRequest is the API request for triggering a sync
+type SyncRequest struct {
+ DeviceID string `json:"device_id,omitempty"`
+ DaysLimit int `json:"days_limit,omitempty"`
+ IncludeMedia bool `json:"include_media"`
+ IncludeGroups bool `json:"include_groups"`
+}
+
+// SyncResponse is the API response for sync operations
+type SyncResponse struct {
+ Status string `json:"status"`
+ Message string `json:"message"`
+ Progress *SyncProgress `json:"progress,omitempty"`
+}
+
+// DefaultSyncOptions returns reasonable default sync options
+func DefaultSyncOptions() SyncOptions {
+ return SyncOptions{
+ DaysLimit: 3,
+ IncludeMedia: true,
+ IncludeGroups: true,
+ MaxMessagesPerChat: 500,
+ BatchSize: 10,
+ DelayBetweenBatches: 500 * time.Millisecond,
+ }
+}
+
+// NewSyncProgress creates a new sync progress tracker
+func NewSyncProgress(deviceID string) *SyncProgress {
+ return &SyncProgress{
+ DeviceID: deviceID,
+ Status: "idle",
+ }
+}
+
+// SetRunning marks the sync as running
+func (p *SyncProgress) SetRunning() {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ p.Status = "running"
+ now := time.Now()
+ p.StartedAt = &now
+}
+
+// SetCompleted marks the sync as completed
+func (p *SyncProgress) SetCompleted() {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ p.Status = "completed"
+ now := time.Now()
+ p.CompletedAt = &now
+}
+
+// SetFailed marks the sync as failed
+func (p *SyncProgress) SetFailed(err error) {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ p.Status = "failed"
+ now := time.Now()
+ p.CompletedAt = &now
+ if err != nil {
+ p.Error = err.Error()
+ }
+}
+
+// UpdateChat updates the current chat being synced
+func (p *SyncProgress) UpdateChat(chatJID string) {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ p.CurrentChat = chatJID
+}
+
+// IncrementSyncedChats increments the synced chats counter
+func (p *SyncProgress) IncrementSyncedChats() {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ p.SyncedChats++
+}
+
+// IncrementFailedChats increments the failed chats counter
+func (p *SyncProgress) IncrementFailedChats() {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ p.FailedChats++
+}
+
+// IncrementSyncedMessages increments the synced messages counter
+func (p *SyncProgress) IncrementSyncedMessages() {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ p.SyncedMessages++
+}
+
+// IncrementFailedMessages increments the failed messages counter
+func (p *SyncProgress) IncrementFailedMessages() {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ p.FailedMessages++
+}
+
+// SetTotals sets the total counts
+func (p *SyncProgress) SetTotals(chats, messages int) {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ p.TotalChats = chats
+ p.TotalMessages = messages
+}
+
+// AddMessages adds to total messages count
+func (p *SyncProgress) AddMessages(count int) {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ p.TotalMessages += count
+}
+
+// Clone returns a thread-safe copy of the progress
+func (p *SyncProgress) Clone() SyncProgress {
+ p.mu.RLock()
+ defer p.mu.RUnlock()
+ return SyncProgress{
+ DeviceID: p.DeviceID,
+ Status: p.Status,
+ TotalChats: p.TotalChats,
+ SyncedChats: p.SyncedChats,
+ FailedChats: p.FailedChats,
+ TotalMessages: p.TotalMessages,
+ SyncedMessages: p.SyncedMessages,
+ FailedMessages: p.FailedMessages,
+ CurrentChat: p.CurrentChat,
+ StartedAt: p.StartedAt,
+ CompletedAt: p.CompletedAt,
+ Error: p.Error,
+ }
+}
+
+// IsRunning returns true if sync is currently running
+func (p *SyncProgress) IsRunning() bool {
+ p.mu.RLock()
+ defer p.mu.RUnlock()
+ return p.Status == "running"
+}
diff --git a/src/infrastructure/chatwoot/types.go b/src/infrastructure/chatwoot/types.go
index b51911de..7bb7c503 100644
--- a/src/infrastructure/chatwoot/types.go
+++ b/src/infrastructure/chatwoot/types.go
@@ -45,6 +45,7 @@ type CreateMessageRequest struct {
}
type WebhookPayload struct {
+ ID int `json:"id"`
Event string `json:"event"`
MessageType string `json:"message_type"`
Content string `json:"content"`
diff --git a/src/infrastructure/whatsapp/auto_reply.go b/src/infrastructure/whatsapp/auto_reply.go
index 76d0d633..e7edc6ab 100644
--- a/src/infrastructure/whatsapp/auto_reply.go
+++ b/src/infrastructure/whatsapp/auto_reply.go
@@ -44,27 +44,7 @@ func handleAutoReply(ctx context.Context, evt *events.Message, chatStorageRepo d
// Require actual typed text (not captions or synthetic labels)
hasText := false
- // Unwrap FutureProof wrappers to access the inner message content first
- innerMsg := evt.Message
- for i := 0; i < 3; i++ { // safeguard against excessively nested wrappers
- if vm := innerMsg.GetViewOnceMessage(); vm != nil && vm.GetMessage() != nil {
- innerMsg = vm.GetMessage()
- continue
- }
- if em := innerMsg.GetEphemeralMessage(); em != nil && em.GetMessage() != nil {
- innerMsg = em.GetMessage()
- continue
- }
- if vm2 := innerMsg.GetViewOnceMessageV2(); vm2 != nil && vm2.GetMessage() != nil {
- innerMsg = vm2.GetMessage()
- continue
- }
- if vm2e := innerMsg.GetViewOnceMessageV2Extension(); vm2e != nil && vm2e.GetMessage() != nil {
- innerMsg = vm2e.GetMessage()
- continue
- }
- break
- }
+ innerMsg := utils.UnwrapMessage(evt.Message)
// Check for genuine typed text on the unwrapped content
if conv := innerMsg.GetConversation(); conv != "" {
diff --git a/src/infrastructure/whatsapp/chatwoot_forward_test.go b/src/infrastructure/whatsapp/chatwoot_forward_test.go
new file mode 100644
index 00000000..3bf996a6
--- /dev/null
+++ b/src/infrastructure/whatsapp/chatwoot_forward_test.go
@@ -0,0 +1,45 @@
+package whatsapp
+
+import "testing"
+
+func TestChatwootMessageTypeFromPayload(t *testing.T) {
+ tests := []struct {
+ name string
+ isFromMe any
+ expected string
+ }{
+ {
+ name: "incoming message",
+ isFromMe: false,
+ expected: "incoming",
+ },
+ {
+ name: "outgoing message",
+ isFromMe: true,
+ expected: "outgoing",
+ },
+ {
+ name: "missing field defaults to incoming",
+ isFromMe: nil,
+ expected: "incoming",
+ },
+ {
+ name: "non-bool field defaults to incoming",
+ isFromMe: "true",
+ expected: "incoming",
+ },
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ payload := map[string]any{}
+ if tc.isFromMe != nil {
+ payload["is_from_me"] = tc.isFromMe
+ }
+
+ if got := chatwootMessageTypeFromPayload(payload); got != tc.expected {
+ t.Fatalf("expected %s, got %s", tc.expected, got)
+ }
+ })
+ }
+}
diff --git a/src/infrastructure/whatsapp/event_message.go b/src/infrastructure/whatsapp/event_message.go
index 2c2eba76..2d66f124 100644
--- a/src/infrastructure/whatsapp/event_message.go
+++ b/src/infrastructure/whatsapp/event_message.go
@@ -8,6 +8,7 @@ import (
"time"
"go.mau.fi/whatsmeow"
+ "go.mau.fi/whatsmeow/proto/waE2E"
"go.mau.fi/whatsmeow/types"
"github.com/aldinokemal/go-whatsapp-web-multidevice/config"
@@ -75,9 +76,12 @@ func createWebhookEvent(ctx context.Context, client *whatsmeow.Client, evt *even
func buildEventPayload(ctx context.Context, client *whatsmeow.Client, evt *events.Message) (string, map[string]any, error) {
payload := make(map[string]any)
+ msg := utils.UnwrapMessage(evt.Message)
+
// Common fields for all message types
payload["id"] = evt.Info.ID
payload["timestamp"] = evt.Info.Timestamp.Format(time.RFC3339)
+ payload["is_from_me"] = evt.Info.IsFromMe
// Build from/from_lid fields
buildFromFields(ctx, client, evt, payload)
@@ -88,7 +92,7 @@ func buildEventPayload(ctx context.Context, client *whatsmeow.Client, evt *event
}
// Check for protocol messages (revoke, edit)
- if protocolMessage := evt.Message.GetProtocolMessage(); protocolMessage != nil {
+ if protocolMessage := msg.GetProtocolMessage(); protocolMessage != nil {
protocolType := protocolMessage.GetType().String()
switch protocolType {
@@ -118,7 +122,7 @@ func buildEventPayload(ctx context.Context, client *whatsmeow.Client, evt *event
}
// Check for reaction message
- if reactionMessage := evt.Message.GetReactionMessage(); reactionMessage != nil {
+ if reactionMessage := msg.GetReactionMessage(); reactionMessage != nil {
payload["reaction"] = reactionMessage.GetText()
if key := reactionMessage.GetKey(); key != nil {
payload["reacted_message_id"] = key.GetID()
@@ -132,7 +136,7 @@ func buildEventPayload(ctx context.Context, client *whatsmeow.Client, evt *event
}
// Add optional fields
- if err := buildOptionalFields(ctx, client, evt, payload); err != nil {
+ if err := buildOptionalFields(ctx, client, evt, msg, payload); err != nil {
return "", nil, err
}
@@ -140,16 +144,18 @@ func buildEventPayload(ctx context.Context, client *whatsmeow.Client, evt *event
}
func buildFromFields(ctx context.Context, client *whatsmeow.Client, evt *events.Message, payload map[string]any) {
- // Always set chat_id from evt.Info.Chat (works for both private and group)
- payload["chat_id"] = evt.Info.Chat.ToNonAD().String()
+ chatJID := evt.Info.Chat.ToNonAD()
+ if chatJID.Server == "lid" {
+ payload["chat_lid"] = chatJID.String()
+ chatJID = NormalizeJIDFromLID(ctx, chatJID, client).ToNonAD()
+ }
+ payload["chat_id"] = chatJID.String()
- // Try to get from_lid from sender
senderJID := evt.Info.Sender
if senderJID.Server == "lid" {
payload["from_lid"] = senderJID.ToNonAD().String()
}
- // Resolve sender JID (convert LID to phone number if needed)
normalizedSenderJID := NormalizeJIDFromLID(ctx, senderJID, client)
payload["from"] = normalizedSenderJID.ToNonAD().String()
}
@@ -194,7 +200,7 @@ func buildMessageBody(ctx context.Context, client *whatsmeow.Client, evt *events
return nil
}
-func buildOptionalFields(ctx context.Context, client *whatsmeow.Client, evt *events.Message, payload map[string]any) error {
+func buildOptionalFields(ctx context.Context, client *whatsmeow.Client, evt *events.Message, msg *waE2E.Message, payload map[string]any) error {
if evt.IsViewOnce {
payload["view_once"] = true
}
@@ -203,23 +209,21 @@ func buildOptionalFields(ctx context.Context, client *whatsmeow.Client, evt *eve
payload["forwarded"] = true
}
- // Handle media types
- if err := buildMediaFields(ctx, client, evt, payload); err != nil {
+ if err := buildMediaFields(ctx, client, msg, payload); err != nil {
return err
}
- // Handle other message types
- buildOtherMessageTypes(evt, payload)
+ buildOtherMessageTypes(msg, payload)
return nil
}
-func buildMediaFields(ctx context.Context, client *whatsmeow.Client, evt *events.Message, payload map[string]any) error {
- if audioMedia := evt.Message.GetAudioMessage(); audioMedia != nil {
+func buildMediaFields(ctx context.Context, client *whatsmeow.Client, msg *waE2E.Message, payload map[string]any) error {
+ if audioMedia := msg.GetAudioMessage(); audioMedia != nil {
if config.WhatsappAutoDownloadMedia {
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)
+ logrus.Errorf("Failed to download audio: %v", err)
return pkgError.WebhookError(fmt.Sprintf("Failed to download audio: %v", err))
}
payload["audio"] = extracted.MediaPath
@@ -230,11 +234,11 @@ func buildMediaFields(ctx context.Context, client *whatsmeow.Client, evt *events
}
}
- if documentMedia := evt.Message.GetDocumentMessage(); documentMedia != nil {
+ if documentMedia := msg.GetDocumentMessage(); documentMedia != nil {
if config.WhatsappAutoDownloadMedia {
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)
+ logrus.Errorf("Failed to download document: %v", err)
return pkgError.WebhookError(fmt.Sprintf("Failed to download document: %v", err))
}
payload["document"] = extracted.MediaPath
@@ -246,11 +250,11 @@ func buildMediaFields(ctx context.Context, client *whatsmeow.Client, evt *events
}
}
- if imageMedia := evt.Message.GetImageMessage(); imageMedia != nil {
+ if imageMedia := msg.GetImageMessage(); imageMedia != nil {
if config.WhatsappAutoDownloadMedia {
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)
+ logrus.Errorf("Failed to download image: %v", err)
return pkgError.WebhookError(fmt.Sprintf("Failed to download image: %v", err))
}
payload["image"] = extracted.MediaPath
@@ -262,11 +266,11 @@ func buildMediaFields(ctx context.Context, client *whatsmeow.Client, evt *events
}
}
- if stickerMedia := evt.Message.GetStickerMessage(); stickerMedia != nil {
+ if stickerMedia := msg.GetStickerMessage(); stickerMedia != nil {
if config.WhatsappAutoDownloadMedia {
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)
+ logrus.Errorf("Failed to download sticker: %v", err)
return pkgError.WebhookError(fmt.Sprintf("Failed to download sticker: %v", err))
}
payload["sticker"] = extracted.MediaPath
@@ -277,11 +281,11 @@ func buildMediaFields(ctx context.Context, client *whatsmeow.Client, evt *events
}
}
- if videoMedia := evt.Message.GetVideoMessage(); videoMedia != nil {
+ if videoMedia := msg.GetVideoMessage(); videoMedia != nil {
if config.WhatsappAutoDownloadMedia {
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)
+ logrus.Errorf("Failed to download video: %v", err)
return pkgError.WebhookError(fmt.Sprintf("Failed to download video: %v", err))
}
payload["video"] = extracted.MediaPath
@@ -293,11 +297,11 @@ func buildMediaFields(ctx context.Context, client *whatsmeow.Client, evt *events
}
}
- if ptvMedia := evt.Message.GetPtvMessage(); ptvMedia != nil {
+ if ptvMedia := msg.GetPtvMessage(); ptvMedia != nil {
if config.WhatsappAutoDownloadMedia {
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)
+ logrus.Errorf("Failed to download video note: %v", err)
return pkgError.WebhookError(fmt.Sprintf("Failed to download video note: %v", err))
}
payload["video_note"] = extracted.MediaPath
@@ -312,24 +316,24 @@ func buildMediaFields(ctx context.Context, client *whatsmeow.Client, evt *events
return nil
}
-func buildOtherMessageTypes(evt *events.Message, payload map[string]any) {
- if contactMessage := evt.Message.GetContactMessage(); contactMessage != nil {
+func buildOtherMessageTypes(msg *waE2E.Message, payload map[string]any) {
+ if contactMessage := msg.GetContactMessage(); contactMessage != nil {
payload["contact"] = contactMessage
}
- if listMessage := evt.Message.GetListMessage(); listMessage != nil {
+ if listMessage := msg.GetListMessage(); listMessage != nil {
payload["list"] = listMessage
}
- if liveLocationMessage := evt.Message.GetLiveLocationMessage(); liveLocationMessage != nil {
+ if liveLocationMessage := msg.GetLiveLocationMessage(); liveLocationMessage != nil {
payload["live_location"] = liveLocationMessage
}
- if locationMessage := evt.Message.GetLocationMessage(); locationMessage != nil {
+ if locationMessage := msg.GetLocationMessage(); locationMessage != nil {
payload["location"] = locationMessage
}
- if orderMessage := evt.Message.GetOrderMessage(); orderMessage != nil {
+ if orderMessage := msg.GetOrderMessage(); orderMessage != nil {
payload["order"] = orderMessage
}
}
diff --git a/src/infrastructure/whatsapp/event_message_handler.go b/src/infrastructure/whatsapp/event_message_handler.go
index 61c88a2f..06bfbd53 100644
--- a/src/infrastructure/whatsapp/event_message_handler.go
+++ b/src/infrastructure/whatsapp/event_message_handler.go
@@ -114,15 +114,6 @@ func handleWebhookForward(ctx context.Context, evt *events.Message, client *what
}
}
- // Skip webhook for outgoing messages (IsFromMe) unless explicitly configured to include them.
- // By default, we skip to avoid duplicate webhooks when multiple devices are connected.
- // The sender's device receives an echo of the sent message.
- // Note: Protocol messages (REVOKE, MESSAGE_EDIT) are allowed through above.
- if evt.Info.IsFromMe && !config.WhatsappWebhookIncludeOutgoing {
- log.Debugf("Skipping webhook for outgoing message %s (IsFromMe=true)", evt.Info.ID)
- return
- }
-
if (len(config.WhatsappWebhook) > 0 || config.ChatwootEnabled) &&
!strings.Contains(evt.Info.SourceString(), "broadcast") {
go func(e *events.Message, c *whatsmeow.Client) {
diff --git a/src/infrastructure/whatsapp/event_message_test.go b/src/infrastructure/whatsapp/event_message_test.go
new file mode 100644
index 00000000..a1fee6ca
--- /dev/null
+++ b/src/infrastructure/whatsapp/event_message_test.go
@@ -0,0 +1,92 @@
+package whatsapp
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ "go.mau.fi/whatsmeow/proto/waCommon"
+ "go.mau.fi/whatsmeow/proto/waE2E"
+ "go.mau.fi/whatsmeow/types"
+ "go.mau.fi/whatsmeow/types/events"
+)
+
+func TestBuildEventPayloadIncludesIsFromMe(t *testing.T) {
+ evt := &events.Message{
+ Info: types.MessageInfo{
+ MessageSource: types.MessageSource{
+ Chat: types.NewJID("123", types.DefaultUserServer),
+ Sender: types.NewJID("123", types.DefaultUserServer),
+ IsFromMe: true,
+ },
+ ID: "MSG123",
+ Timestamp: time.Date(2026, time.February, 8, 10, 0, 0, 0, time.UTC),
+ },
+ Message: &waE2E.Message{
+ Conversation: protoString("hello"),
+ },
+ }
+
+ eventType, payload, err := buildEventPayload(context.Background(), nil, evt)
+ if err != nil {
+ t.Fatalf("expected no error, got %v", err)
+ }
+ if eventType != EventTypeMessage {
+ t.Fatalf("expected event type %s, got %s", EventTypeMessage, eventType)
+ }
+ if value, ok := payload["is_from_me"]; !ok {
+ t.Fatalf("expected is_from_me in payload")
+ } else if isFromMe, ok := value.(bool); !ok || !isFromMe {
+ t.Fatalf("expected is_from_me=true, got %v", value)
+ }
+}
+
+func TestBuildEventPayloadRevokedIncludesIsFromMe(t *testing.T) {
+ key := &waCommon.MessageKey{
+ RemoteJID: protoString("[email protected]"),
+ FromMe: protoBool(true),
+ ID: protoString("REV123"),
+ }
+ evt := &events.Message{
+ Info: types.MessageInfo{
+ MessageSource: types.MessageSource{
+ Chat: types.NewJID("123", types.DefaultUserServer),
+ Sender: types.NewJID("123", types.DefaultUserServer),
+ IsFromMe: true,
+ },
+ ID: "MSG124",
+ Timestamp: time.Date(2026, time.February, 8, 10, 0, 0, 0, time.UTC),
+ },
+ Message: &waE2E.Message{
+ ProtocolMessage: &waE2E.ProtocolMessage{
+ Type: protoProtocolMessageType(waE2E.ProtocolMessage_REVOKE),
+ Key: key,
+ },
+ },
+ }
+
+ eventType, payload, err := buildEventPayload(context.Background(), nil, evt)
+ if err != nil {
+ t.Fatalf("expected no error, got %v", err)
+ }
+ if eventType != EventTypeMessageRevoked {
+ t.Fatalf("expected event type %s, got %s", EventTypeMessageRevoked, eventType)
+ }
+ if value, ok := payload["is_from_me"]; !ok {
+ t.Fatalf("expected is_from_me in payload")
+ } else if isFromMe, ok := value.(bool); !ok || !isFromMe {
+ t.Fatalf("expected is_from_me=true, got %v", value)
+ }
+}
+
+func protoString(value string) *string {
+ return &value
+}
+
+func protoBool(value bool) *bool {
+ return &value
+}
+
+func protoProtocolMessageType(value waE2E.ProtocolMessage_Type) *waE2E.ProtocolMessage_Type {
+ return &value
+}
diff --git a/src/infrastructure/whatsapp/webhook_forward.go b/src/infrastructure/whatsapp/webhook_forward.go
index 38fa78a0..6eb1331d 100644
--- a/src/infrastructure/whatsapp/webhook_forward.go
+++ b/src/infrastructure/whatsapp/webhook_forward.go
@@ -129,6 +129,7 @@ type chatwootContactInfo struct {
Name string
IsGroup bool
FromName string
+ IsFromMe bool
}
// extractChatwootContactInfo extracts contact identifier and name from message payload.
@@ -138,8 +139,9 @@ func extractChatwootContactInfo(ctx context.Context, data map[string]interface{}
from, _ := data["from"].(string)
fromName, _ := data["from_name"].(string)
chatID, _ := data["chat_id"].(string)
+ isFromMe, _ := data["is_from_me"].(bool)
- logrus.Infof("Chatwoot: Processing message from %s (from_name: %s, chat_id: %s)", from, fromName, chatID)
+ logrus.Infof("Chatwoot: Processing message from %s (from_name: %s, chat_id: %s, is_from_me: %v)", from, fromName, chatID, isFromMe)
if from == "" {
return nil, fmt.Errorf("empty 'from' field")
@@ -158,6 +160,9 @@ func extractChatwootContactInfo(ctx context.Context, data map[string]interface{}
info.Name = "Group: " + utils.ExtractPhoneFromJID(chatID)
}
logrus.Infof("Chatwoot: Detected group message, using group contact: %s", info.Name)
+ } else if isFromMe {
+ info.Identifier = utils.ExtractPhoneFromJID(chatID)
+ info.Name = info.Identifier
} else {
info.Identifier = utils.ExtractPhoneFromJID(from)
info.Name = fromName
@@ -176,6 +181,10 @@ func buildChatwootMessageContent(data map[string]interface{}, isGroup bool, from
content = body
}
+ if content == "" {
+ content = extractStructuredMessageContent(data)
+ }
+
// For group messages, prepend sender name to content
if isGroup && fromName != "" && content != "" {
content = fromName + ": " + content
@@ -206,6 +215,93 @@ func buildChatwootMessageContent(data map[string]interface{}, isGroup bool, from
return content, attachments
}
+func chatwootMessageTypeFromPayload(data map[string]interface{}) string {
+ if isFromMe, ok := data["is_from_me"].(bool); ok && isFromMe {
+ return "outgoing"
+ }
+ return "incoming"
+}
+
+func extractStructuredMessageContent(data map[string]interface{}) string {
+ if contact, ok := data["contact"]; ok && contact != nil {
+ if cm, ok := contact.(interface {
+ GetDisplayName() string
+ GetVcard() string
+ }); ok {
+ name := cm.GetDisplayName()
+ phone := extractPhoneFromVCard(cm.GetVcard())
+ switch {
+ case name != "" && phone != "":
+ return fmt.Sprintf("Contact: %s (%s)", name, phone)
+ case name != "":
+ return "Contact: " + name
+ case phone != "":
+ return "Contact: " + phone
+ }
+ }
+ return "Contact shared"
+ }
+
+ if location, ok := data["location"]; ok && location != nil {
+ if lm, ok := location.(interface {
+ GetDegreesLatitude() float64
+ GetDegreesLongitude() float64
+ GetName() string
+ }); ok {
+ name := lm.GetName()
+ if name != "" {
+ return fmt.Sprintf("Location: %s (%.6f, %.6f)", name, lm.GetDegreesLatitude(), lm.GetDegreesLongitude())
+ }
+ return fmt.Sprintf("Location: %.6f, %.6f", lm.GetDegreesLatitude(), lm.GetDegreesLongitude())
+ }
+ return "Location shared"
+ }
+
+ if liveLocation, ok := data["live_location"]; ok && liveLocation != nil {
+ if lm, ok := liveLocation.(interface {
+ GetDegreesLatitude() float64
+ GetDegreesLongitude() float64
+ }); ok {
+ return fmt.Sprintf("Live Location: %.6f, %.6f", lm.GetDegreesLatitude(), lm.GetDegreesLongitude())
+ }
+ return "Live location shared"
+ }
+
+ if list, ok := data["list"]; ok && list != nil {
+ if lm, ok := list.(interface{ GetTitle() string }); ok {
+ title := lm.GetTitle()
+ if title != "" {
+ return "List: " + title
+ }
+ }
+ return "List message"
+ }
+
+ if order, ok := data["order"]; ok && order != nil {
+ if om, ok := order.(interface{ GetOrderTitle() string }); ok {
+ title := om.GetOrderTitle()
+ if title != "" {
+ return "Order: " + title
+ }
+ }
+ return "Order message"
+ }
+
+ return ""
+}
+
+func extractPhoneFromVCard(vcard string) string {
+ for _, line := range strings.Split(vcard, "\n") {
+ line = strings.TrimSpace(line)
+ if strings.HasPrefix(strings.ToUpper(line), "TEL") {
+ if idx := strings.LastIndex(line, ":"); idx >= 0 {
+ return strings.TrimSpace(line[idx+1:])
+ }
+ }
+ }
+ return ""
+}
+
// 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
@@ -227,9 +323,15 @@ func syncMessageToChatwoot(cw *chatwoot.Client, info *chatwootContactInfo, conte
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 {
+ messageType := "incoming"
+ if info.IsFromMe {
+ messageType = "outgoing"
+ }
+ msgID, err := cw.CreateMessage(conversation.ID, content, messageType, attachments)
+ if err != nil {
return fmt.Errorf("failed to create message: %w", err)
}
+ chatwoot.MarkMessageAsSent(msgID)
logrus.Infof("Chatwoot: Message synced successfully for %s", info.Identifier)
return nil
@@ -258,6 +360,7 @@ func forwardToChatwoot(ctx context.Context, payload map[string]any) {
// Build message content
content, attachments := buildChatwootMessageContent(data, info.IsGroup, info.FromName)
+ info.IsFromMe = chatwootMessageTypeFromPayload(data) == "outgoing"
// Sync to Chatwoot
if err := syncMessageToChatwoot(cw, info, content, attachments); err != nil {
diff --git a/src/pkg/utils/phone.go b/src/pkg/utils/phone.go
index 9d1f670e..7c07ce64 100644
--- a/src/pkg/utils/phone.go
+++ b/src/pkg/utils/phone.go
@@ -3,10 +3,15 @@ package utils
import "strings"
// NormalizePhoneE164 ensures phone has + prefix for E.164 format.
+// Strips WhatsApp JID suffixes (@s.whatsapp.net, @lid, etc.) before formatting.
// Returns empty string if input is empty.
func NormalizePhoneE164(phone string) string {
phone = strings.TrimSpace(phone)
- if phone != "" && !strings.HasPrefix(phone, "+") {
+ if phone == "" {
+ return phone
+ }
+ phone = ExtractPhoneFromJID(phone)
+ if !strings.HasPrefix(phone, "+") {
return "+" + phone
}
return phone
diff --git a/src/pkg/utils/whatsapp.go b/src/pkg/utils/whatsapp.go
index debff508..751b0cbf 100644
--- a/src/pkg/utils/whatsapp.go
+++ b/src/pkg/utils/whatsapp.go
@@ -697,16 +697,49 @@ func GetMessageDigestOrSignature(msg, key []byte) (string, error) {
return hex.EncodeToString(mac.Sum(nil)), nil
}
+// UnwrapMessage unwraps FutureProof wrappers (ephemeral, view-once, etc.)
+// to access the inner message content. WhatsApp wraps messages in these
+// containers when disappearing messages or view-once is enabled.
+// The original message is not modified; the unwrapped inner message is returned.
+func UnwrapMessage(msg *waE2E.Message) *waE2E.Message {
+ if msg == nil {
+ return msg
+ }
+ inner := msg
+ for i := 0; i < 3; i++ { // safeguard against excessively nested wrappers
+ if vm := inner.GetViewOnceMessage(); vm != nil && vm.GetMessage() != nil {
+ inner = vm.GetMessage()
+ continue
+ }
+ if em := inner.GetEphemeralMessage(); em != nil && em.GetMessage() != nil {
+ inner = em.GetMessage()
+ continue
+ }
+ if vm2 := inner.GetViewOnceMessageV2(); vm2 != nil && vm2.GetMessage() != nil {
+ inner = vm2.GetMessage()
+ continue
+ }
+ if vm2e := inner.GetViewOnceMessageV2Extension(); vm2e != nil && vm2e.GetMessage() != nil {
+ inner = vm2e.GetMessage()
+ continue
+ }
+ break
+ }
+ return inner
+}
+
// BuildEventMessage builds event message structure
func BuildEventMessage(evt *events.Message) (message EvtMessage) {
- message.Text = evt.Message.GetConversation()
+ msg := UnwrapMessage(evt.Message)
+
+ message.Text = msg.GetConversation()
message.ID = evt.Info.ID
- if extendedMessage := evt.Message.GetExtendedTextMessage(); extendedMessage != nil {
+ if extendedMessage := msg.GetExtendedTextMessage(); extendedMessage != nil {
message.Text = extendedMessage.GetText()
message.RepliedId = extendedMessage.ContextInfo.GetStanzaID()
message.QuotedMessage = extendedMessage.ContextInfo.GetQuotedMessage().GetConversation()
- } else if protocolMessage := evt.Message.GetProtocolMessage(); protocolMessage != nil {
+ } else if protocolMessage := msg.GetProtocolMessage(); protocolMessage != nil {
if editedMessage := protocolMessage.GetEditedMessage(); editedMessage != nil {
if extendedText := editedMessage.GetExtendedTextMessage(); extendedText != nil {
message.Text = extendedText.GetText()
@@ -719,20 +752,20 @@ func BuildEventMessage(evt *events.Message) (message EvtMessage) {
return message
}
-// BuildEventReaction builds event reaction structure
func BuildEventReaction(evt *events.Message) (waReaction EvtReaction) {
- if reactionMessage := evt.Message.GetReactionMessage(); reactionMessage != nil {
+ msg := UnwrapMessage(evt.Message)
+ if reactionMessage := msg.GetReactionMessage(); reactionMessage != nil {
waReaction.Message = reactionMessage.GetText()
waReaction.ID = reactionMessage.GetKey().GetID()
}
return waReaction
}
-// BuildForwarded checks if message is forwarded
func BuildForwarded(evt *events.Message) bool {
- if extendedText := evt.Message.GetExtendedTextMessage(); extendedText != nil {
+ msg := UnwrapMessage(evt.Message)
+ if extendedText := msg.GetExtendedTextMessage(); extendedText != nil {
return extendedText.ContextInfo.GetIsForwarded()
- } else if protocolMessage := evt.Message.GetProtocolMessage(); protocolMessage != nil {
+ } else if protocolMessage := msg.GetProtocolMessage(); protocolMessage != nil {
if editedMessage := protocolMessage.GetEditedMessage(); editedMessage != nil {
if extendedText := editedMessage.GetExtendedTextMessage(); extendedText != nil {
return extendedText.ContextInfo.GetIsForwarded()
diff --git a/src/ui/rest/chatwoot.go b/src/ui/rest/chatwoot.go
index 5322afe6..4ca42705 100644
--- a/src/ui/rest/chatwoot.go
+++ b/src/ui/rest/chatwoot.go
@@ -1,10 +1,12 @@
package rest
import (
+ "context"
"fmt"
"github.com/aldinokemal/go-whatsapp-web-multidevice/config"
domainApp "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/chatwoot"
"github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/whatsapp"
@@ -14,16 +16,23 @@ import (
)
type ChatwootHandler struct {
- AppUsecase domainApp.IAppUsecase
- SendUsecase domainSend.ISendUsecase
- DeviceManager *whatsapp.DeviceManager
+ AppUsecase domainApp.IAppUsecase
+ SendUsecase domainSend.ISendUsecase
+ DeviceManager *whatsapp.DeviceManager
+ ChatStorageRepo domainChatStorage.IChatStorageRepository
}
-func NewChatwootHandler(appUsecase domainApp.IAppUsecase, sendUsecase domainSend.ISendUsecase, dm *whatsapp.DeviceManager) *ChatwootHandler {
+func NewChatwootHandler(
+ appUsecase domainApp.IAppUsecase,
+ sendUsecase domainSend.ISendUsecase,
+ dm *whatsapp.DeviceManager,
+ chatStorageRepo domainChatStorage.IChatStorageRepository,
+) *ChatwootHandler {
return &ChatwootHandler{
- AppUsecase: appUsecase,
- SendUsecase: sendUsecase,
- DeviceManager: dm,
+ AppUsecase: appUsecase,
+ SendUsecase: sendUsecase,
+ DeviceManager: dm,
+ ChatStorageRepo: chatStorageRepo,
}
}
@@ -66,6 +75,11 @@ func (h *ChatwootHandler) HandleWebhook(c *fiber.Ctx) error {
return c.SendStatus(fiber.StatusOK)
}
+ if chatwoot.IsMessageSentByUs(payload.ID) {
+ logrus.Debugf("Chatwoot Webhook: Skipping echo message %d (created by our API)", payload.ID)
+ return c.SendStatus(fiber.StatusOK)
+ }
+
customAttrs := contact.CustomAttributes
var destination string
if val, ok := customAttrs["waha_whatsapp_jid"]; ok {
@@ -195,3 +209,152 @@ func (h *ChatwootHandler) handleAttachment(c *fiber.Ctx, phone string, att chatw
return err
}
}
+
+// SyncHistory triggers a message history sync to Chatwoot
+// POST /chatwoot/sync
+func (h *ChatwootHandler) SyncHistory(c *fiber.Ctx) error {
+ // Parse request body
+ var req chatwoot.SyncRequest
+ if err := c.BodyParser(&req); err != nil {
+ // Try query parameters as fallback
+ req.DeviceID = c.Query("device_id", config.ChatwootDeviceID)
+ req.DaysLimit = c.QueryInt("days", config.ChatwootDaysLimitImportMessages)
+ req.IncludeMedia = c.QueryBool("media", true)
+ req.IncludeGroups = c.QueryBool("groups", true)
+ }
+
+ // Default values
+ if req.DeviceID == "" {
+ req.DeviceID = config.ChatwootDeviceID
+ }
+ if req.DaysLimit <= 0 {
+ req.DaysLimit = config.ChatwootDaysLimitImportMessages
+ }
+
+ // Resolve device
+ instance, resolvedID, err := h.DeviceManager.ResolveDevice(req.DeviceID)
+ if err != nil {
+ return c.Status(fiber.StatusBadRequest).JSON(utils.ResponseData{
+ Status: fiber.StatusBadRequest,
+ Code: "DEVICE_NOT_FOUND",
+ Message: fmt.Sprintf("Failed to resolve device: %v", err),
+ })
+ }
+
+ // Get Chatwoot client
+ cwClient := chatwoot.GetDefaultClient()
+ if !cwClient.IsConfigured() {
+ return c.Status(fiber.StatusBadRequest).JSON(utils.ResponseData{
+ Status: fiber.StatusBadRequest,
+ Code: "CHATWOOT_NOT_CONFIGURED",
+ Message: "Chatwoot is not configured. Set CHATWOOT_URL, CHATWOOT_API_TOKEN, CHATWOOT_ACCOUNT_ID, and CHATWOOT_INBOX_ID.",
+ })
+ }
+
+ // Get or create sync service
+ syncService := chatwoot.GetSyncService(cwClient, h.ChatStorageRepo)
+ waClient := instance.GetClient()
+
+ // Use JID as the storage device ID since chats are stored with the full JID
+ // (e.g. "[email protected]"), not the user-assigned device alias (e.g. "busine").
+ storageDeviceID := instance.JID()
+ if storageDeviceID == "" {
+ storageDeviceID = resolvedID
+ }
+
+ // Check if already running
+ if syncService.IsRunning(storageDeviceID) {
+ progress := syncService.GetProgress(storageDeviceID)
+ return c.Status(fiber.StatusConflict).JSON(utils.ResponseData{
+ Status: fiber.StatusConflict,
+ Code: "SYNC_ALREADY_RUNNING",
+ Message: "A sync is already in progress for this device",
+ Results: map[string]interface{}{
+ "progress": progress,
+ },
+ })
+ }
+
+ // Build sync options
+ opts := chatwoot.DefaultSyncOptions()
+ opts.DaysLimit = req.DaysLimit
+ opts.IncludeMedia = req.IncludeMedia
+ opts.IncludeGroups = req.IncludeGroups
+
+ // Start async sync
+ go func() {
+ ctx := context.Background()
+ progress, err := syncService.SyncHistory(ctx, storageDeviceID, waClient, opts)
+ if err != nil {
+ logrus.Errorf("Chatwoot Sync: Failed for device %s: %v", storageDeviceID, err)
+ } else {
+ logrus.Infof("Chatwoot Sync: Completed for device %s - %d/%d messages synced",
+ storageDeviceID, progress.SyncedMessages, progress.TotalMessages)
+ }
+ }()
+
+ return c.JSON(utils.ResponseData{
+ Status: 200,
+ Code: "SYNC_STARTED",
+ Message: "History sync initiated in background",
+ Results: map[string]interface{}{
+ "device_id": resolvedID,
+ "days_limit": opts.DaysLimit,
+ "include_media": opts.IncludeMedia,
+ "include_groups": opts.IncludeGroups,
+ },
+ })
+}
+
+// SyncStatus returns the current sync progress
+// GET /chatwoot/sync/status
+func (h *ChatwootHandler) SyncStatus(c *fiber.Ctx) error {
+ deviceID := c.Query("device_id", config.ChatwootDeviceID)
+
+ instance, resolvedID, err := h.DeviceManager.ResolveDevice(deviceID)
+ if err != nil {
+ return c.Status(fiber.StatusBadRequest).JSON(utils.ResponseData{
+ Status: fiber.StatusBadRequest,
+ Code: "DEVICE_NOT_FOUND",
+ Message: fmt.Sprintf("Failed to resolve device: %v", err),
+ })
+ }
+
+ storageDeviceID := instance.JID()
+ if storageDeviceID == "" {
+ storageDeviceID = resolvedID
+ }
+
+ syncService := chatwoot.GetDefaultSyncService()
+ if syncService == nil {
+ return c.JSON(utils.ResponseData{
+ Status: 200,
+ Code: "SUCCESS",
+ Message: "No sync has been initiated yet",
+ Results: map[string]interface{}{
+ "device_id": resolvedID,
+ "status": "idle",
+ },
+ })
+ }
+
+ progress := syncService.GetProgress(storageDeviceID)
+ if progress == nil {
+ return c.JSON(utils.ResponseData{
+ Status: 200,
+ Code: "SUCCESS",
+ Message: "No sync progress found for this device",
+ Results: map[string]interface{}{
+ "device_id": resolvedID,
+ "status": "idle",
+ },
+ })
+ }
+
+ return c.JSON(utils.ResponseData{
+ Status: 200,
+ Code: "SUCCESS",
+ Message: "Sync status retrieved",
+ Results: progress,
+ })
+}
diff --git a/src/usecase/app.go b/src/usecase/app.go
index 4e233914..b9c2e877 100644
--- a/src/usecase/app.go
+++ b/src/usecase/app.go
@@ -48,9 +48,17 @@ func (service *serviceApp) Login(ctx context.Context, deviceID string) (response
// Disconnect first to ensure QR flow starts cleanly.
client.Disconnect()
+ // Use a detached context for the QR channel so the pairing session
+ // survives after the HTTP response is sent. The HTTP request context
+ // has a short timeout (e.g. 45s) which would cancel the QR emitter
+ // and disconnect the client before the user can scan the code.
+ // Total QR window: ~160s (first code 60s + five codes at 20s each).
+ qrCtx, qrCancel := context.WithTimeout(context.Background(), 3*time.Minute)
+
chImage := make(chan string, 1) // Buffered to prevent goroutine leak
- ch, err := client.GetQRChannel(ctx)
+ ch, err := client.GetQRChannel(qrCtx)
if err != nil {
+ qrCancel()
logrus.Errorf("[LOGIN][%s] GetQRChannel failed: %v", deviceID, err)
if errors.Is(err, whatsmeow.ErrQRStoreContainsID) {
_ = client.Connect()
@@ -64,6 +72,7 @@ func (service *serviceApp) Login(ctx context.Context, deviceID string) (response
}
go func() {
+ defer qrCancel()
defer close(chImage) // Ensure channel is closed when done
for evt := range ch {
response.Code = evt.Code
@@ -80,11 +89,10 @@ func (service *serviceApp) Login(ctx context.Context, deviceID string) (response
logrus.Errorf("[LOGIN][%s] error when remove qrImage file: %v", deviceID, err)
}
}(qrPath, response.Duration)
- // Use select to avoid blocking if context is canceled
select {
case chImage <- qrPath:
- case <-ctx.Done():
- logrus.Warnf("[LOGIN][%s] Context canceled while sending QR path", deviceID)
+ case <-qrCtx.Done():
+ logrus.Warnf("[LOGIN][%s] QR context canceled while sending QR path", deviceID)
return
}
} else {
@@ -94,6 +102,7 @@ func (service *serviceApp) Login(ctx context.Context, deviceID string) (response
}()
if err = client.Connect(); err != nil {
+ qrCancel()
logger.Error("Error when connect to whatsapp", err)
return response, pkgError.ErrReconnect
}