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: support multi account

Aldino Kemal1b762b81c588
diff --git a/.github/workflows/build-docker-image.yaml b/.github/workflows/build-docker-image.yaml
index 331c06b4..2c8369d5 100644
--- a/.github/workflows/build-docker-image.yaml
+++ b/.github/workflows/build-docker-image.yaml
@@ -32,17 +32,13 @@ jobs:
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Build and push
- uses: docker/build-push-action@v5
+ uses: docker/build-push-action@v6
with:
push: true
context: .
file: ./docker/golang.Dockerfile
tags: |
- ${{ secrets.REGISTRY_USERNAME }}/go-whatsapp-web-multidevice:latest
- ${{ secrets.REGISTRY_USERNAME }}/go-whatsapp-web-multidevice:latest-amd
${{ secrets.REGISTRY_USERNAME }}/go-whatsapp-web-multidevice:${{ github.ref_name }}-amd
- ghcr.io/${{ github.repository_owner }}/go-whatsapp-web-multidevice:latest
- ghcr.io/${{ github.repository_owner }}/go-whatsapp-web-multidevice:latest-amd
ghcr.io/${{ github.repository_owner }}/go-whatsapp-web-multidevice:${{ github.ref_name }}-amd
build-and-push-arm:
@@ -68,15 +64,13 @@ jobs:
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Build and push
- uses: docker/build-push-action@v5
+ uses: docker/build-push-action@v6
with:
push: true
context: .
file: ./docker/golang.Dockerfile
tags: |
- ${{ secrets.REGISTRY_USERNAME }}/go-whatsapp-web-multidevice:latest-arm
${{ secrets.REGISTRY_USERNAME }}/go-whatsapp-web-multidevice:${{ github.ref_name }}-arm
- ghcr.io/${{ github.repository_owner }}/go-whatsapp-web-multidevice:latest-arm
ghcr.io/${{ github.repository_owner }}/go-whatsapp-web-multidevice:${{ github.ref_name }}-arm
merge-manifest:
@@ -105,18 +99,8 @@ jobs:
docker buildx imagetools create -t ${{ secrets.REGISTRY_USERNAME }}/go-whatsapp-web-multidevice:${{ github.ref_name }} \
${{ secrets.REGISTRY_USERNAME }}/go-whatsapp-web-multidevice:${{ github.ref_name }}-amd \
${{ secrets.REGISTRY_USERNAME }}/go-whatsapp-web-multidevice:${{ github.ref_name }}-arm
- - name: Create Latest Manifest
- run: |
- docker buildx imagetools create -t ${{ secrets.REGISTRY_USERNAME }}/go-whatsapp-web-multidevice:latest \
- ${{ secrets.REGISTRY_USERNAME }}/go-whatsapp-web-multidevice:latest-amd \
- ${{ secrets.REGISTRY_USERNAME }}/go-whatsapp-web-multidevice:latest-arm
- name: Create Versioned Manifest (GHCR) (${{ github.ref_name }})
run: |
- docker buildx imagetools create -t ghcr.io/aldinokemal/go-whatsapp-web-multidevice:${{ github.ref_name }} \
- ghcr.io/aldinokemal/go-whatsapp-web-multidevice:${{ github.ref_name }}-amd \
- ghcr.io/aldinokemal/go-whatsapp-web-multidevice:${{ github.ref_name }}-arm
- - name: Create Latest Manifest (GHCR)
- run: |
- docker buildx imagetools create -t ghcr.io/aldinokemal/go-whatsapp-web-multidevice:latest \
- ghcr.io/aldinokemal/go-whatsapp-web-multidevice:latest-amd \
- ghcr.io/aldinokemal/go-whatsapp-web-multidevice:latest-arm
\ No newline at end of file
+ docker buildx imagetools create -t ghcr.io/${{ github.repository_owner }}/go-whatsapp-web-multidevice:${{ github.ref_name }} \
+ ghcr.io/${{ github.repository_owner }}/go-whatsapp-web-multidevice:${{ github.ref_name }}-amd \
+ ghcr.io/${{ github.repository_owner }}/go-whatsapp-web-multidevice:${{ github.ref_name }}-arm
diff --git a/.github/workflows/claude-code-review-manual.yml b/.github/workflows/claude-code-review-manual.yml
deleted file mode 100644
index c8a372b8..00000000
--- a/.github/workflows/claude-code-review-manual.yml
+++ /dev/null
@@ -1,77 +0,0 @@
-name: Claude Code Review - Manual Fork PR Review
-
-on:
- workflow_dispatch:
- inputs:
- pr_number:
- description: 'PR number to review'
- required: true
- type: string
- review_focus:
- description: 'Specific areas to focus on (optional)'
- required: false
- type: string
-
-jobs:
- claude-review-manual:
- runs-on: ubuntu-latest
- permissions:
- contents: read
- pull-requests: write
- issues: write
- id-token: write
-
- steps:
- - name: Checkout repository
- uses: actions/checkout@v4
- with:
- fetch-depth: 1
-
- - name: Get PR details
- id: pr
- uses: actions/github-script@v7
- with:
- result-encoding: string
- script: |
- const { data: pr } = await github.rest.pulls.get({
- owner: context.repo.owner,
- repo: context.repo.repo,
- pull_number: ${{ inputs.pr_number }}
- });
-
- // Checkout the PR branch
- await exec.exec('git', ['fetch', 'origin', `pull/${{ inputs.pr_number }}/head:pr-${{ inputs.pr_number }}`]);
- await exec.exec('git', ['checkout', `pr-${{ inputs.pr_number }}`]);
-
- return pr.html_url;
-
- - name: Run Claude Code Review
- id: claude-review
- uses: anthropics/claude-code-action@beta
- with:
- claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
- github_token: ${{ secrets.GITHUB_TOKEN }}
- direct_prompt: |
- Please review PR #${{ inputs.pr_number }} with focus on:
- ${{ inputs.review_focus || 'General code review covering Go best practices, security, and maintainability' }}
-
- **For Go code (.go files):**
- - Go idioms and best practices
- - Error handling patterns
- - Interface design and implementation
- - Memory management and potential leaks
- - Concurrency safety (goroutines, channels, mutexes)
- - Code organization and package structure
- - Performance considerations
- - Security vulnerabilities
- - Test coverage and quality
-
- **For Frontend code (HTML/CSS/JS files):**
- - JavaScript/Vue.js best practices and patterns
- - HTML semantics and accessibility
- - CSS performance and maintainability
- - Cross-browser compatibility
- - Frontend security (XSS, CSRF prevention)
- - UI/UX considerations
-
- Please provide constructive feedback and post it as a comment on PR #${{ inputs.pr_number }}.
\ No newline at end of file
diff --git a/.github/workflows/claude-code-review.yml b/.github/workflows/claude-code-review.yml
deleted file mode 100644
index b129b16c..00000000
--- a/.github/workflows/claude-code-review.yml
+++ /dev/null
@@ -1,90 +0,0 @@
-name: Claude Code Review - Internal PRs Only
-
-on:
- # Note: Only handles internal PRs due to Claude action limitations
- # Fork PRs don't have sufficient permissions to post comments
- pull_request:
- types: [opened, synchronize]
- paths:
- - "src/**/*.go"
- - "go.mod"
- - "go.sum"
- - "src/views/**/*.html"
- - "src/views/**/*.css"
- - "src/views/**/*.js"
- - "src/views/**/*.svg"
-
-jobs:
- claude-review:
- # Only run for internal PRs to avoid permission issues
- if: github.event.pull_request.head.repo.full_name == github.event.pull_request.base.repo.full_name
- runs-on: ubuntu-latest
- permissions:
- contents: read
- pull-requests: write
- issues: write
- id-token: write
-
- steps:
- - name: Checkout repository
- uses: actions/checkout@v4
- with:
- fetch-depth: 1
-
- - name: Run Claude Code Review
- id: claude-review
- uses: anthropics/claude-code-action@beta
- with:
- claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
- github_token: ${{ secrets.GITHUB_TOKEN }}
-
- # Optional: Specify model (defaults to Claude Sonnet 4, uncomment for Claude Opus 4)
- # model: "claude-opus-4-20250514"
-
- # Direct prompt for automated review (no @claude mention needed)
- direct_prompt: |
- Please review this Go application pull request and provide feedback on:
-
- **For Go code (.go files):**
- - Go idioms and best practices
- - Error handling patterns
- - Interface design and implementation
- - Memory management and potential leaks
- - Concurrency safety (goroutines, channels, mutexes)
- - Code organization and package structure
- - Performance considerations
- - Security vulnerabilities
- - Test coverage and quality
- - Proper use of Go standard library
- - Documentation and code comments
-
- **For Frontend code (HTML/CSS/JS files):**
- - JavaScript/Vue.js best practices and patterns
- - HTML semantics and accessibility
- - CSS performance and maintainability
- - Cross-browser compatibility
- - Frontend security (XSS, CSRF prevention)
- - UI/UX considerations
- - Code organization and modularity
- - Performance optimizations (DOM manipulation, asset loading)
- - Responsive design implementation
- - Vue.js component architecture and lifecycle management
-
- **General concerns:**
- - API integration between frontend and backend
- - Data validation on both client and server sides
- - Error handling consistency across the stack
- - Security best practices for the full application
-
- Be constructive and helpful in your feedback, focusing on language-specific concerns for each file type.
-
- # Optional: Use sticky comments to make Claude reuse the same comment on subsequent pushes to the same PR
- # use_sticky_comment: true
-
- # Optional: Add specific tools for running Go tests and linting, plus frontend tools
- allowed_tools: "Bash(cd src && go test ./...),Bash(cd src && go vet ./...),Bash(cd src && go fmt ./...),Bash(cd src && go mod tidy),Bash(find src/views -name '*.html' -exec htmlhint {} \\;),Bash(find src/views -name '*.css' -exec csslint {} \\;),Bash(find src/views -name '*.js' -exec jshint {} \\;)"
-
- # Optional: Skip review for certain conditions
- # if: |
- # !contains(github.event.pull_request.title, '[skip-review]') &&
- # !contains(github.event.pull_request.title, '[WIP]')
diff --git a/.github/workflows/claude.yml b/.github/workflows/claude.yml
deleted file mode 100644
index 64a3e5b1..00000000
--- a/.github/workflows/claude.yml
+++ /dev/null
@@ -1,64 +0,0 @@
-name: Claude Code
-
-on:
- issue_comment:
- types: [created]
- pull_request_review_comment:
- types: [created]
- issues:
- types: [opened, assigned]
- pull_request_review:
- types: [submitted]
-
-jobs:
- claude:
- if: |
- (github.event_name == 'issue_comment' && contains(github.event.comment.body, '@claude')) ||
- (github.event_name == 'pull_request_review_comment' && contains(github.event.comment.body, '@claude')) ||
- (github.event_name == 'pull_request_review' && contains(github.event.review.body, '@claude')) ||
- (github.event_name == 'issues' && (contains(github.event.issue.body, '@claude') || contains(github.event.issue.title, '@claude')))
- runs-on: ubuntu-latest
- permissions:
- contents: read
- pull-requests: read
- issues: read
- id-token: write
- actions: read # Required for Claude to read CI results on PRs
- steps:
- - name: Checkout repository
- uses: actions/checkout@v4
- with:
- fetch-depth: 1
-
- - name: Run Claude Code
- id: claude
- uses: anthropics/claude-code-action@beta
- with:
- claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
-
- # This is an optional setting that allows Claude to read CI results on PRs
- additional_permissions: |
- actions: read
-
- # Optional: Specify model (defaults to Claude Sonnet 4, uncomment for Claude Opus 4)
- # model: "claude-opus-4-20250514"
-
- # Optional: Customize the trigger phrase (default: @claude)
- # trigger_phrase: "/claude"
-
- # Optional: Trigger when specific user is assigned to an issue
- # assignee_trigger: "claude-bot"
-
- # Optional: Allow Claude to run specific commands
- # allowed_tools: "Bash(npm install),Bash(npm run build),Bash(npm run test:*),Bash(npm run lint:*)"
-
- # Optional: Add custom instructions for Claude to customize its behavior for your project
- # custom_instructions: |
- # Follow our coding standards
- # Ensure all new code has tests
- # Use TypeScript for new files
-
- # Optional: Custom environment variables for Claude
- # claude_env: |
- # NODE_ENV: test
-
diff --git a/.github/workflows/set-latest-tag.yaml b/.github/workflows/set-latest-tag.yaml
new file mode 100644
index 00000000..40126388
--- /dev/null
+++ b/.github/workflows/set-latest-tag.yaml
@@ -0,0 +1,58 @@
+name: Set Latest Tag
+
+on:
+ workflow_dispatch:
+ inputs:
+ tag:
+ description: 'Tag version to promote to latest (e.g., v7.0.0)'
+ required: true
+ type: string
+
+jobs:
+ set-latest:
+ environment: production
+ runs-on: ubuntu-latest
+ permissions:
+ contents: read
+ packages: write
+ steps:
+ - name: Login Registry
+ uses: docker/login-action@v3
+ with:
+ username: ${{ secrets.REGISTRY_USERNAME }}
+ password: ${{ secrets.REGISTRY_PASSWORD }}
+ - name: Login GitHub Container Registry
+ uses: docker/login-action@v3
+ with:
+ registry: ghcr.io
+ username: ${{ github.actor }}
+ password: ${{ secrets.GITHUB_TOKEN }}
+ - name: Set up Docker Buildx
+ uses: docker/setup-buildx-action@v3
+ - name: Validate tag exists (Docker Hub)
+ run: |
+ echo "Checking if tag ${{ inputs.tag }} exists on Docker Hub..."
+ if ! docker buildx imagetools inspect ${{ secrets.REGISTRY_USERNAME }}/go-whatsapp-web-multidevice:${{ inputs.tag }} > /dev/null 2>&1; then
+ echo "::error::Tag ${{ inputs.tag }} does not exist on Docker Hub. Please ensure the tag has been built first."
+ exit 1
+ fi
+ echo "Tag ${{ inputs.tag }} found on Docker Hub."
+ - name: Validate tag exists (GHCR)
+ run: |
+ echo "Checking if tag ${{ inputs.tag }} exists on GHCR..."
+ if ! docker buildx imagetools inspect ghcr.io/${{ github.repository_owner }}/go-whatsapp-web-multidevice:${{ inputs.tag }} > /dev/null 2>&1; then
+ echo "::error::Tag ${{ inputs.tag }} does not exist on GHCR. Please ensure the tag has been built first."
+ exit 1
+ fi
+ echo "Tag ${{ inputs.tag }} found on GHCR."
+ - name: Create Latest Manifest (Docker Hub)
+ run: |
+ docker buildx imagetools create \
+ -t ${{ secrets.REGISTRY_USERNAME }}/go-whatsapp-web-multidevice:latest \
+ ${{ secrets.REGISTRY_USERNAME }}/go-whatsapp-web-multidevice:${{ inputs.tag }}
+ - name: Create Latest Manifest (GHCR)
+ run: |
+ docker buildx imagetools create \
+ -t ghcr.io/${{ github.repository_owner }}/go-whatsapp-web-multidevice:latest \
+ ghcr.io/${{ github.repository_owner }}/go-whatsapp-web-multidevice:${{ inputs.tag }}
+
diff --git a/.gitignore b/.gitignore
index d40855cb..6eea7997 100644
--- a/.gitignore
+++ b/.gitignore
@@ -12,3 +12,5 @@ storages
bin
.playwright-mcp
.cursor/mcp.json
+.factory
+.vscode/settings.json
diff --git a/CLAUDE.md b/AGENTS.md
similarity index 93%
rename from CLAUDE.md
rename to AGENTS.md
index 796c0ba5..a5f0c64e 100644
--- a/CLAUDE.md
+++ b/AGENTS.md
@@ -1,4 +1,4 @@
-# CLAUDE.md
+# AGENTS.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
@@ -72,12 +72,13 @@ This is a Go-based WhatsApp Web API server supporting both REST API and MCP (Mod
### WhatsApp Integration
- Uses whatsmeow library for WhatsApp Web protocol
-- Supports multi-device WhatsApp accounts
-- Auto-reconnection and connection monitoring
+- **Multi-device login support**: Can connect and manage multiple WhatsApp accounts simultaneously
+- Auto-reconnection and connection monitoring per device
- Media compression and webhook support
## Important Notes
+- Supports multiple WhatsApp device connections in a single server instance
- The application cannot run both REST and MCP modes simultaneously (limitation from whatsmeow library)
- All source code must be in the `src/` directory
- Media files are stored in `src/statics/media/` and `src/storages/`
diff --git a/docs/openapi.yaml b/docs/openapi.yaml
index 93ea84b6..23f5a584 100644
--- a/docs/openapi.yaml
+++ b/docs/openapi.yaml
@@ -1,13 +1,20 @@
openapi: "3.0.0"
info:
title: WhatsApp API MultiDevice
- version: 6.13.1
- description: This API is used for sending whatsapp via API
+ version: 8.0.0
+ description: |
+ This API is used for sending whatsapp via API.
+
+ Device scoping:
+ - Send `X-Device-Id` on all device-scoped REST calls.
+ - WebSocket: connect to `/ws?device_id=<id>`.
servers:
- url: http://localhost:3000
tags:
- name: app
description: Initial Connection to Whatsapp server
+ - name: device
+ description: Device management for multi-device support
- name: user
description: Getting information
- name: send
@@ -30,6 +37,8 @@ paths:
tags:
- app
summary: Login to whatsapp server
+ parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
responses:
'200':
description: OK
@@ -50,6 +59,7 @@ paths:
- app
summary: Login with pairing code
parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
- name: phone
in: query
schema:
@@ -75,6 +85,8 @@ paths:
tags:
- app
summary: Remove database and logout
+ parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
responses:
'200':
description: OK
@@ -94,6 +106,8 @@ paths:
tags:
- app
summary: Reconnecting to whatsapp server
+ parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
responses:
'200':
description: OK
@@ -113,6 +127,10 @@ paths:
tags:
- app
summary: Get list connected devices
+ description: >
+ Returns all device IDs known to the server, including placeholders
+ created via the device API. Devices are now persisted in the storage
+ registry so IDs remain stable after application restarts.
responses:
'200':
description: OK
@@ -126,6 +144,358 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/ErrorInternalServer'
+ /app/status:
+ get:
+ operationId: appStatus
+ tags:
+ - app
+ summary: Get connection status
+ description: Check whether the WhatsApp client is connected and logged in
+ parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
+ responses:
+ '200':
+ description: OK
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ status:
+ type: integer
+ example: 200
+ code:
+ type: string
+ example: SUCCESS
+ message:
+ type: string
+ example: Connection status retrieved
+ results:
+ type: object
+ properties:
+ is_connected:
+ type: boolean
+ description: Whether the device is connected to WhatsApp servers
+ is_logged_in:
+ type: boolean
+ description: Whether the device is logged in to WhatsApp
+ device_id:
+ type: string
+ description: The device ID
+ example: '[email protected]'
+ '400':
+ description: Bad Request
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorBadRequest'
+ '500':
+ description: Internal Server Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorInternalServer'
+
+ # Device Management API (v8)
+ /devices:
+ get:
+ operationId: listDevices
+ tags:
+ - device
+ summary: List all devices
+ description: Returns all registered devices with their connection status
+ responses:
+ '200':
+ description: OK
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/DeviceListResponse'
+ '500':
+ description: Internal Server Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorInternalServer'
+ post:
+ operationId: addDevice
+ tags:
+ - device
+ summary: Add a new device
+ description: Create a new device slot for multi-device management
+ requestBody:
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ device_id:
+ type: string
+ description: Optional custom device ID. If not provided, one will be generated.
+ example: 'my-custom-device-id'
+ responses:
+ '200':
+ description: OK
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/DeviceAddResponse'
+ '400':
+ description: Bad Request
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorBadRequest'
+ '500':
+ description: Internal Server Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorInternalServer'
+
+ /devices/{device_id}:
+ get:
+ operationId: getDevice
+ tags:
+ - device
+ summary: Get device info
+ description: Get detailed information about a specific device
+ parameters:
+ - name: device_id
+ in: path
+ required: true
+ schema:
+ type: string
+ description: Device ID
+ responses:
+ '200':
+ description: OK
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/DeviceInfoResponse'
+ '404':
+ description: Device not found
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorNotFound'
+ '500':
+ description: Internal Server Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorInternalServer'
+ delete:
+ operationId: removeDevice
+ tags:
+ - device
+ summary: Remove a device
+ description: Remove a device from the server (does not logout from WhatsApp)
+ parameters:
+ - name: device_id
+ in: path
+ required: true
+ schema:
+ type: string
+ description: Device ID
+ responses:
+ '200':
+ description: OK
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/GenericResponse'
+ '404':
+ description: Device not found
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorNotFound'
+ '500':
+ description: Internal Server Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorInternalServer'
+
+ /devices/{device_id}/login:
+ get:
+ operationId: loginDevice
+ tags:
+ - device
+ summary: Login device with QR code
+ description: Initiate QR code login for a specific device
+ parameters:
+ - name: device_id
+ in: path
+ required: true
+ schema:
+ type: string
+ description: Device ID
+ responses:
+ '200':
+ description: OK
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/LoginResponse'
+ '404':
+ description: Device not found
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorNotFound'
+ '500':
+ description: Internal Server Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorInternalServer'
+
+ /devices/{device_id}/login/code:
+ post:
+ operationId: loginDeviceWithCode
+ tags:
+ - device
+ summary: Login device with pairing code
+ description: Initiate pairing code login for a specific device
+ parameters:
+ - name: device_id
+ in: path
+ required: true
+ schema:
+ type: string
+ description: Device ID
+ - name: phone
+ in: query
+ required: true
+ schema:
+ type: string
+ example: '628912344551'
+ description: Phone number to pair with
+ responses:
+ '200':
+ description: OK
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/LoginWithCodeResponse'
+ '404':
+ description: Device not found
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorNotFound'
+ '500':
+ description: Internal Server Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorInternalServer'
+
+ /devices/{device_id}/logout:
+ post:
+ operationId: logoutDevice
+ tags:
+ - device
+ summary: Logout device
+ description: Logout a specific device from WhatsApp and remove its session
+ parameters:
+ - name: device_id
+ in: path
+ required: true
+ schema:
+ type: string
+ description: Device ID
+ responses:
+ '200':
+ description: OK
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/GenericResponse'
+ '404':
+ description: Device not found
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorNotFound'
+ '500':
+ description: Internal Server Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorInternalServer'
+
+ /devices/{device_id}/reconnect:
+ post:
+ operationId: reconnectDevice
+ tags:
+ - device
+ summary: Reconnect device
+ description: Reconnect a specific device to WhatsApp
+ parameters:
+ - name: device_id
+ in: path
+ required: true
+ schema:
+ type: string
+ description: Device ID
+ responses:
+ '200':
+ description: OK
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/GenericResponse'
+ '404':
+ description: Device not found
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorNotFound'
+ '500':
+ description: Internal Server Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorInternalServer'
+
+ /devices/{device_id}/status:
+ get:
+ operationId: getDeviceStatus
+ tags:
+ - device
+ summary: Get device connection status
+ description: Get the current connection status of a specific device
+ parameters:
+ - name: device_id
+ in: path
+ required: true
+ schema:
+ type: string
+ description: Device ID
+ responses:
+ '200':
+ description: OK
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/DeviceStatusResponse'
+ '404':
+ description: Device not found
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorNotFound'
+ '500':
+ description: Internal Server Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorInternalServer'
+
/user/info:
get:
operationId: userInfo
@@ -133,6 +503,7 @@ paths:
- user
summary: User Info
parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
- name: phone
in: query
schema:
@@ -165,6 +536,7 @@ paths:
- user
summary: User Avatar
parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
- name: phone
in: query
schema:
@@ -207,6 +579,8 @@ paths:
tags:
- user
summary: User Change Avatar
+ parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
requestBody:
content:
multipart/form-data:
@@ -243,6 +617,8 @@ paths:
- user
summary: User Change Push Name
description: Update the display name (push name) shown to others in WhatsApp
+ parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
requestBody:
content:
application/json:
@@ -280,6 +656,8 @@ paths:
tags:
- user
summary: User My Privacy Setting
+ parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
responses:
'200':
description: OK
@@ -299,6 +677,8 @@ paths:
tags:
- user
summary: User My List Groups
+ parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
responses:
'200':
description: OK
@@ -319,6 +699,8 @@ paths:
tags:
- user
summary: User My List Groups
+ parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
responses:
'200':
description: OK
@@ -338,6 +720,8 @@ paths:
tags:
- user
summary: Get list of user contacts
+ parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
responses:
'200':
description: OK
@@ -358,6 +742,7 @@ paths:
- user
summary: Check if user is on WhatsApp
parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
- name: phone
in: query
schema:
@@ -391,6 +776,7 @@ paths:
summary: Get Business Profile Information
description: Retrieve detailed business profile information for a WhatsApp business account
parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
- name: phone
in: query
required: true
@@ -424,6 +810,8 @@ paths:
tags:
- send
summary: Send Message
+ parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
requestBody:
content:
application/json:
@@ -475,6 +863,8 @@ paths:
tags:
- send
summary: Send Image
+ parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
requestBody:
content:
multipart/form-data:
@@ -538,6 +928,8 @@ paths:
tags:
- send
summary: Send Audio
+ parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
requestBody:
content:
multipart/form-data:
@@ -589,6 +981,8 @@ paths:
tags:
- send
summary: Send File
+ parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
requestBody:
content:
multipart/form-data:
@@ -641,6 +1035,8 @@ paths:
- send
summary: Send Sticker
description: Send sticker with automatic conversion to WebP format
+ parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
requestBody:
content:
multipart/form-data:
@@ -692,6 +1088,8 @@ paths:
tags:
- send
summary: Send Video
+ parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
requestBody:
content:
multipart/form-data:
@@ -755,6 +1153,8 @@ paths:
tags:
- send
summary: Send Contact
+ parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
requestBody:
content:
application/json:
@@ -806,6 +1206,8 @@ paths:
tags:
- send
summary: Send Link
+ parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
requestBody:
content:
application/json:
@@ -857,6 +1259,8 @@ paths:
tags:
- send
summary: Send Location
+ parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
requestBody:
content:
application/json:
@@ -908,6 +1312,8 @@ paths:
tags:
- send
summary: Send Poll / Vote
+ parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
requestBody:
required: true
content:
@@ -967,6 +1373,8 @@ paths:
tags:
- send
summary: Send presence status
+ parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
requestBody:
required: true
content:
@@ -1011,6 +1419,8 @@ paths:
- send
summary: Send chat presence (typing indicator)
description: Send typing indicator to start or stop showing that you are composing a message
+ parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
requestBody:
required: true
content:
@@ -1056,6 +1466,7 @@ paths:
- message
summary: Revoke Message
parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
- in: path
name: message_id
schema:
@@ -1098,6 +1509,7 @@ paths:
- message
summary: Delete Message
parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
- in: path
name: message_id
schema:
@@ -1140,6 +1552,7 @@ paths:
- message
summary: Send reaction to message
parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
- in: path
name: message_id
schema:
@@ -1186,6 +1599,7 @@ paths:
- message
summary: Edit message by message ID before 15 minutes
parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
- in: path
name: message_id
schema:
@@ -1235,6 +1649,7 @@ paths:
- message
summary: Mark as read message
parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
- in: path
name: message_id
schema:
@@ -1279,6 +1694,7 @@ paths:
- message
summary: Star message
parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
- in: path
name: message_id
schema:
@@ -1323,6 +1739,7 @@ paths:
- message
summary: Unstar message
parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
- in: path
name: message_id
schema:
@@ -1360,7 +1777,84 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/ErrorInternalServer'
-
+ /message/{message_id}/download:
+ get:
+ operationId: downloadMessageMedia
+ tags:
+ - message
+ summary: Download media from message
+ description: Download media content (image, video, audio, document) from a message
+ parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
+ - in: path
+ name: message_id
+ schema:
+ type: string
+ required: true
+ description: Message ID
+ example: '3EB0123456789ABCDEF'
+ - in: query
+ name: phone
+ schema:
+ type: string
+ required: true
+ description: Phone number with country code
+ example: '[email protected]'
+ responses:
+ '200':
+ description: OK
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ status:
+ type: integer
+ example: 200
+ code:
+ type: string
+ example: SUCCESS
+ message:
+ type: string
+ example: Media downloaded successfully
+ results:
+ type: object
+ properties:
+ status:
+ type: string
+ example: Media downloaded successfully
+ mime_type:
+ type: string
+ example: image/jpeg
+ file_size:
+ type: integer
+ example: 524288
+ file_name:
+ type: string
+ example: image.jpg
+ data:
+ type: string
+ format: byte
+ description: Base64 encoded media data
+ '400':
+ description: Bad Request
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorBadRequest'
+ '404':
+ description: Message or media not found
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorNotFound'
+ '500':
+ description: Internal Server Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorInternalServer'
+
/chats:
get:
operationId: listChats
@@ -1369,6 +1863,7 @@ paths:
summary: Get list of chats
description: Retrieve a list of chat conversations with their basic information
parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
- name: limit
in: query
schema:
@@ -1426,6 +1921,7 @@ paths:
summary: Get messages from a specific chat
description: Retrieve messages from a specific chat conversation with filtering options
parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
- in: path
name: chat_jid
schema:
@@ -1513,6 +2009,7 @@ paths:
summary: Label or unlabel a chat
description: Apply or remove a label from a chat conversation
parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
- in: path
name: chat_jid
schema:
@@ -1581,6 +2078,7 @@ paths:
summary: Pin or unpin a chat
description: Pin or unpin a chat conversation to the top of the chat list
parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
- in: path
name: chat_jid
schema:
@@ -1640,6 +2138,7 @@ paths:
summary: Set disappearing messages timer
description: Set or disable disappearing messages for a chat. Valid timer values are 0 (off), 86400 (24h), 604800 (7d), 7776000 (90d).
parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
- in: path
name: chat_jid
schema:
@@ -1686,6 +2185,7 @@ paths:
- group
summary: Group Info
parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
- name: group_id
in: query
schema:
@@ -1717,6 +2217,8 @@ paths:
tags:
- group
summary: Create group and add participant
+ parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
requestBody:
content:
application/json:
@@ -1764,6 +2266,7 @@ paths:
- group
summary: Get list of participants in a group
parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
- name: group_id
in: query
required: true
@@ -1795,6 +2298,8 @@ paths:
tags:
- group
summary: Adding more participants to group
+ parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
requestBody:
content:
application/json:
@@ -1826,6 +2331,7 @@ paths:
- group
summary: Export group participants as CSV
parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
- name: group_id
in: query
required: true
@@ -1859,6 +2365,8 @@ paths:
tags:
- group
summary: Remove participants from group
+ parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
requestBody:
content:
application/json:
@@ -1889,6 +2397,8 @@ paths:
tags:
- group
summary: Promote participants to admin
+ parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
requestBody:
content:
application/json:
@@ -1919,6 +2429,8 @@ paths:
tags:
- group
summary: Demote participants to member
+ parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
requestBody:
content:
application/json:
@@ -1949,6 +2461,8 @@ paths:
tags:
- group
summary: Join group with link
+ parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
requestBody:
content:
application/json:
@@ -1985,6 +2499,7 @@ paths:
summary: Get group information from invitation link
description: Retrieve group information without joining the group using its invitation link
parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
- name: link
in: query
required: true
@@ -2018,6 +2533,7 @@ paths:
- group
summary: Get list of participant requests to join group
parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
- name: group_id
in: query
required: true
@@ -2050,6 +2566,8 @@ paths:
tags:
- group
summary: Approve participant request to join group
+ parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
requestBody:
content:
application/json:
@@ -2094,6 +2612,8 @@ paths:
tags:
- group
summary: Reject participant request to join group
+ parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
requestBody:
content:
application/json:
@@ -2138,6 +2658,8 @@ paths:
tags:
- group
summary: Leave group
+ parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
requestBody:
content:
application/json:
@@ -2172,6 +2694,8 @@ paths:
tags:
- group
summary: Set group photo
+ parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
requestBody:
content:
multipart/form-data:
@@ -2213,6 +2737,8 @@ paths:
tags:
- group
summary: Set group name
+ parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
requestBody:
content:
application/json:
@@ -2257,6 +2783,8 @@ paths:
- group
summary: Set group locked status
description: Lock/unlock group so only admins can modify group info
+ parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
requestBody:
content:
application/json:
@@ -2300,6 +2828,8 @@ paths:
- group
summary: Set group announce mode
description: Enable/disable announce mode so only admins can send messages
+ parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
requestBody:
content:
application/json:
@@ -2343,6 +2873,8 @@ paths:
- group
summary: Set group topic
description: Set or remove group topic/description
+ parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
requestBody:
content:
application/json:
@@ -2385,6 +2917,7 @@ paths:
- group
summary: Group Invite Link
parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
- name: group_id
in: query
schema:
@@ -2423,6 +2956,8 @@ paths:
tags:
- newsletter
summary: Unfollow newsletter
+ parameters:
+ - $ref: '#/components/parameters/DeviceIdHeader'
requestBody:
content:
application/json:
@@ -2453,6 +2988,19 @@ paths:
$ref: '#/components/schemas/ErrorInternalServer'
components:
+ parameters:
+ DeviceIdHeader:
+ name: X-Device-Id
+ in: header
+ required: false
+ description: |
+ Device identifier for multi-device support. Required when multiple devices are registered.
+ If only one device is registered, it will be used as the default.
+ Can also be provided as `device_id` query parameter.
+ schema:
+ type: string
+ example: 'my-device-id'
+
securitySchemes:
basicAuth:
type: http
@@ -2807,6 +3355,100 @@ components:
device:
type: string
example: '628960561XXX.0:[email protected]'
+
+ # Device Management Schemas (v8)
+ DeviceListResponse:
+ type: object
+ properties:
+ code:
+ type: string
+ example: SUCCESS
+ message:
+ type: string
+ example: List devices
+ status:
+ type: integer
+ example: 200
+ results:
+ type: array
+ items:
+ $ref: '#/components/schemas/DeviceInfo'
+ DeviceAddResponse:
+ type: object
+ properties:
+ code:
+ type: string
+ example: SUCCESS
+ message:
+ type: string
+ example: Device added
+ status:
+ type: integer
+ example: 200
+ results:
+ $ref: '#/components/schemas/DeviceInfo'
+ DeviceInfoResponse:
+ type: object
+ properties:
+ code:
+ type: string
+ example: SUCCESS
+ message:
+ type: string
+ example: Device info
+ status:
+ type: integer
+ example: 200
+ results:
+ $ref: '#/components/schemas/DeviceInfo'
+ DeviceStatusResponse:
+ type: object
+ properties:
+ code:
+ type: string
+ example: SUCCESS
+ message:
+ type: string
+ example: Device status
+ status:
+ type: integer
+ example: 200
+ results:
+ type: object
+ properties:
+ device_id:
+ type: string
+ example: 'my-device-id'
+ is_connected:
+ type: boolean
+ example: true
+ is_logged_in:
+ type: boolean
+ example: true
+ DeviceInfo:
+ type: object
+ properties:
+ id:
+ type: string
+ example: 'my-device-id'
+ phone_number:
+ type: string
+ example: '628123456789'
+ display_name:
+ type: string
+ example: 'John Doe'
+ state:
+ type: string
+ enum: [disconnected, connected, logged_in]
+ example: 'logged_in'
+ jid:
+ type: string
+ example: '[email protected]'
+ created_at:
+ type: string
+ format: date-time
+ example: '2024-01-01T00:00:00Z'
+
LoginWithCodeResponse:
type: object
properties:
diff --git a/docs/webhook-payload.md b/docs/webhook-payload.md
index 58dac242..80d0685b 100644
--- a/docs/webhook-payload.md
+++ b/docs/webhook-payload.md
@@ -55,17 +55,40 @@ def verify_webhook_signature(payload, signature, secret):
return hmac.compare_digest(expected_signature, received_signature)
```
-## Common Payload Fields
+## Payload Structure
-All webhook payloads share these common fields:
+All webhook payloads follow a consistent top-level structure:
-| **Field** | **Type** | **Description** |
-|-------------|----------|-------------------------------------------------------------------|
-| `sender_id` | string | User part of sender JID (phone number, without `@s.whatsapp.net`) |
-| `chat_id` | string | User part of chat JID |
-| `from` | string | Full JID of the sender (e.g., `[email protected]`) |
-| `timestamp` | string | RFC3339 formatted timestamp (e.g., `2023-10-15T10:30:00Z`) |
-| `pushname` | string | Display name of the sender |
+```json
+{
+ "event": "message",
+ "device_id": "[email protected]",
+ "payload": {
+ // Event-specific fields
+ }
+}
+```
+
+### Top-Level Fields
+
+| **Field** | **Type** | **Description** |
+|-------------|----------|---------------------------------------------------------------------------------|
+| `event` | string | Event type: `message`, `message.reaction`, `message.revoked`, `message.edited`, `message.ack`, `group.participants` |
+| `device_id` | string | JID of the device that received this event (e.g., `[email protected]`) |
+| `payload` | object | Event-specific payload data |
+
+### Common Payload Fields
+
+Fields commonly found inside the `payload` object:
+
+| **Field** | **Type** | **Description** |
+|---------------|----------|-------------------------------------------------------------------|
+| `id` | string | Message ID |
+| `chat_id` | string | Chat JID (e.g., `[email protected]` or `[email protected]` for groups) |
+| `from` | string | Full JID of the sender (e.g., `[email protected]`) |
+| `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`) |
## Message Events
@@ -73,16 +96,16 @@ All webhook payloads share these common fields:
```json
{
- "sender_id": "628123456789",
- "chat_id": "628987654321",
- "from": "[email protected]",
- "timestamp": "2023-10-15T10:30:00Z",
- "pushname": "John Doe",
- "message": {
- "text": "Hello, how are you?",
+ "event": "message",
+ "device_id": "[email protected]",
+ "payload": {
"id": "3EB0C127D7BACC83D6A1",
- "replied_id": "",
- "quoted_message": ""
+ "chat_id": "[email protected]",
+ "from": "[email protected]",
+ "from_lid": "251556368777322@lid",
+ "from_name": "John Doe",
+ "timestamp": "2023-10-15T10:30:00Z",
+ "body": "Hello, how are you?"
}
}
```
@@ -91,16 +114,17 @@ All webhook payloads share these common fields:
```json
{
- "sender_id": "628123456789",
- "chat_id": "628987654321",
- "from": "[email protected]",
- "timestamp": "2023-10-15T10:35:00Z",
- "pushname": "John Doe",
- "message": {
- "text": "I'm doing great, thanks!",
+ "event": "message",
+ "device_id": "[email protected]",
+ "payload": {
"id": "3EB0C127D7BACC83D6A2",
- "replied_id": "3EB0C127D7BACC83D6A1",
- "quoted_message": "Hello, how are you?"
+ "chat_id": "[email protected]",
+ "from": "[email protected]",
+ "from_name": "John Doe",
+ "timestamp": "2023-10-15T10:35:00Z",
+ "body": "I'm doing great, thanks!",
+ "replied_to_id": "3EB0C127D7BACC83D6A1",
+ "quoted_body": "Hello, how are you?"
}
}
```
@@ -109,20 +133,16 @@ All webhook payloads share these common fields:
```json
{
- "sender_id": "628123456789",
- "chat_id": "628987654321",
- "from": "[email protected]",
- "timestamp": "2023-10-15T10:40:00Z",
- "pushname": "John Doe",
- "reaction": {
- "message": "πŸ‘",
- "id": "3EB0C127D7BACC83D6A1"
- },
- "message": {
- "text": "",
+ "event": "message.reaction",
+ "device_id": "[email protected]",
+ "payload": {
"id": "88760C69D1F35FEB239102699AE9XXXX",
- "replied_id": "",
- "quoted_message": ""
+ "chat_id": "[email protected]",
+ "from": "[email protected]",
+ "from_name": "John Doe",
+ "timestamp": "2023-10-15T10:40:00Z",
+ "reaction": "πŸ‘",
+ "reacted_message_id": "3EB0C127D7BACC83D6A1"
}
}
```
@@ -139,17 +159,16 @@ Triggered when a message is successfully delivered to the recipient's device.
```json
{
"event": "message.ack",
+ "device_id": "[email protected]",
+ "timestamp": "2025-07-18T22:44:20Z",
"payload": {
+ "ids": ["3EB00106E8BE0F407E88EC"],
"chat_id": "[email protected]",
- "ids": [
- "3EB00106E8BE0F407E88EC"
- ],
+ "from": "[email protected]",
+ "from_lid": "251556368777322@lid",
"receipt_type": "delivered",
- "receipt_type_description": "means the message was delivered to the device (but the user might not have noticed).",
- "sender_id": "[email protected]"
- },
- "timestamp": "2025-07-18T22:44:20Z"
+ "receipt_type_description": "means the message was delivered to the device (but the user might not have noticed)."
+ }
}
```
@@ -160,17 +179,15 @@ Triggered when a message is read by the recipient (they opened the chat and saw
```json
{
"event": "message.ack",
+ "device_id": "[email protected]",
+ "timestamp": "2025-07-18T22:44:44Z",
"payload": {
+ "ids": ["3EB00106E8BE0F407E88EC"],
"chat_id": "[email protected]",
- "ids": [
- "3EB00106E8BE0F407E88EC"
- ],
+ "from": "[email protected]",
"receipt_type": "read",
- "receipt_type_description": "the user opened the chat and saw the message.",
- "sender_id": "[email protected]"
- },
- "timestamp": "2025-07-18T22:44:44Z"
+ "receipt_type_description": "the user opened the chat and saw the message."
+ }
}
```
@@ -179,13 +196,14 @@ Triggered when a message is read by the recipient (they opened the chat and saw
| **Field** | **Type** | **Description** |
|------------------------------------|----------|-----------------------------------------------------------|
| `event` | string | Always `"message.ack"` for receipt events |
-| `payload.chat_id` | string | Chat identifier (group or individual chat) |
-| `payload.from` | string | Sender information with chat context |
+| `device_id` | string | JID of the device that received this event |
+| `timestamp` | string | RFC3339 formatted timestamp when the receipt was received |
| `payload.ids` | array | Array of message IDs that received the acknowledgment |
+| `payload.chat_id` | string | Chat identifier (group or individual chat) |
+| `payload.from` | string | JID of the user who triggered the receipt |
+| `payload.from_lid` | string | LID of the user (if available) |
| `payload.receipt_type` | string | Type of receipt: `"delivered"`, `"read"`, etc. |
| `payload.receipt_type_description` | string | Human-readable description of the receipt type |
-| `payload.sender_id` | string | JID of the message sender |
-| `timestamp` | string | RFC3339 formatted timestamp when the receipt was received |
## Group Events
@@ -198,6 +216,8 @@ Triggered when users join or are added to a group.
```json
{
"event": "group.participants",
+ "device_id": "[email protected]",
+ "timestamp": "2025-07-28T10:30:00Z",
"payload": {
"chat_id": "[email protected]",
"type": "join",
@@ -205,8 +225,7 @@ Triggered when users join or are added to a group.
]
- },
- "timestamp": "2025-07-28T10:30:00Z"
+ }
}
```
@@ -217,14 +236,15 @@ Triggered when users leave or are removed from a group.
```json
{
"event": "group.participants",
+ "device_id": "[email protected]",
+ "timestamp": "2025-07-28T10:32:00Z",
"payload": {
"chat_id": "[email protected]",
"type": "leave",
"jids": [
]
- },
- "timestamp": "2025-07-28T10:32:00Z"
+ }
}
```
@@ -235,14 +255,15 @@ Triggered when users are promoted to admin.
```json
{
"event": "group.participants",
+ "device_id": "[email protected]",
+ "timestamp": "2025-07-28T10:33:00Z",
"payload": {
"chat_id": "[email protected]",
"type": "promote",
"jids": [
]
- },
- "timestamp": "2025-07-28T10:33:00Z"
+ }
}
```
@@ -253,14 +274,15 @@ Triggered when users are demoted from admin.
```json
{
"event": "group.participants",
+ "device_id": "[email protected]",
+ "timestamp": "2025-07-28T10:34:00Z",
"payload": {
"chat_id": "[email protected]",
"type": "demote",
"jids": [
]
- },
- "timestamp": "2025-07-28T10:34:00Z"
+ }
}
```
@@ -268,33 +290,51 @@ Triggered when users are demoted from admin.
| **Field** | **Type** | **Description** |
|-------------------|----------|--------------------------------------------------------------|
-| `event` | string | Always `"group.participants"` for group events |
-| `payload.chat_id` | string | Group identifier (e.g., `"[email protected]"`) |
+| `event` | string | Always `"group.participants"` for group events |
+| `device_id` | string | JID of the device that received this event |
+| `timestamp` | string | RFC3339 formatted timestamp when the group event occurred |
+| `payload.chat_id` | string | Group identifier (e.g., `"[email protected]"`) |
| `payload.type` | string | Action type: `"join"`, `"leave"`, `"promote"`, or `"demote"` |
-| `payload.jids` | array | Array of user JIDs affected by this action |
-| `timestamp` | string | RFC3339 formatted timestamp when the group event occurred |
+| `payload.jids` | array | Array of user JIDs affected by this action |
## Media Messages
### Image Message
+When `WHATSAPP_AUTO_DOWNLOAD_MEDIA` is enabled, media is downloaded and `image` contains the file path.
+When disabled, `image` contains an object with the URL.
+
```json
{
- "sender_id": "628123456789",
- "chat_id": "628123456789",
- "from": "[email protected]",
- "timestamp": "2025-07-13T11:05:51Z",
- "pushname": "John Doe",
- "message": {
- "text": "",
- "id": "********************",
- "replied_id": "",
- "quoted_message": ""
- },
- "image": {
- "media_path": "statics/media/1752404751-ad9e37ac-c658-4fe5-8d25-ba4a3f4d58fd.jpe",
- "mime_type": "image/jpeg",
- "caption": "gijg"
+ "event": "message",
+ "device_id": "[email protected]",
+ "payload": {
+ "id": "3EB0C127D7BACC83D6A3",
+ "chat_id": "[email protected]",
+ "from": "[email protected]",
+ "from_name": "John Doe",
+ "timestamp": "2025-07-13T11:05:51Z",
+ "image": "statics/media/1752404751-ad9e37ac-c658-4fe5-8d25-ba4a3f4d58fd.jpeg"
+ }
+}
+```
+
+With auto-download disabled:
+
+```json
+{
+ "event": "message",
+ "device_id": "[email protected]",
+ "payload": {
+ "id": "3EB0C127D7BACC83D6A3",
+ "chat_id": "[email protected]",
+ "from": "[email protected]",
+ "from_name": "John Doe",
+ "timestamp": "2025-07-13T11:05:51Z",
+ "image": {
+ "url": "https://mmg.whatsapp.net/...",
+ "caption": "Check this out!"
+ }
}
}
```
@@ -303,21 +343,15 @@ Triggered when users are demoted from admin.
```json
{
- "sender_id": "628123456789",
- "chat_id": "628123456789",
- "from": "[email protected]",
- "timestamp": "2025-07-13T11:07:24Z",
- "pushname": "Notification System",
- "message": {
- "text": "",
- "id": "********************",
- "replied_id": "",
- "quoted_message": ""
- },
- "video": {
- "media_path": "statics/media/1752404845-b9393cd1-8546-4df9-8a60-ee3276036aba.m4v",
- "mime_type": "video/mp4",
- "caption": "okk"
+ "event": "message",
+ "device_id": "[email protected]",
+ "payload": {
+ "id": "3EB0C127D7BACC83D6A4",
+ "chat_id": "[email protected]",
+ "from": "[email protected]",
+ "from_name": "John Doe",
+ "timestamp": "2025-07-13T11:07:24Z",
+ "video": "statics/media/1752404845-b9393cd1-8546-4df9-8a60-ee3276036aba.mp4"
}
}
```
@@ -326,21 +360,15 @@ Triggered when users are demoted from admin.
```json
{
- "sender_id": "628123456789",
- "chat_id": "628987654321",
- "from": "[email protected]",
- "timestamp": "2023-10-15T10:55:00Z",
- "pushname": "John Doe",
- "message": {
- "text": "",
+ "event": "message",
+ "device_id": "[email protected]",
+ "payload": {
"id": "3EB0C127D7BACC83D6A5",
- "replied_id": "",
- "quoted_message": ""
- },
- "audio": {
- "media_path": "statics/media/1752404905-b9393cd1-8546-4df9-8a60-ee3276036aba.m4v",
- "mime_type": "audio/ogg",
- "caption": "okk"
+ "chat_id": "[email protected]",
+ "from": "[email protected]",
+ "from_name": "John Doe",
+ "timestamp": "2023-10-15T10:55:00Z",
+ "audio": "statics/media/1752404905-b9393cd1-8546-4df9-8a60-ee3276036aba.ogg"
}
}
```
@@ -349,21 +377,35 @@ Triggered when users are demoted from admin.
```json
{
- "sender_id": "628123456789",
- "chat_id": "628987654321",
- "from": "[email protected]",
- "timestamp": "2023-10-15T11:00:00Z",
- "pushname": "John Doe",
- "message": {
- "text": "",
+ "event": "message",
+ "device_id": "[email protected]",
+ "payload": {
"id": "3EB0C127D7BACC83D6A6",
- "replied_id": "",
- "quoted_message": ""
- },
- "document": {
- "media_path": "statics/media/1752404965-b9393cd1-8546-4df9-8a60-ee3276036aba.m4v",
- "mime_type": "application/pdf",
- "caption": "okk"
+ "chat_id": "[email protected]",
+ "from": "[email protected]",
+ "from_name": "John Doe",
+ "timestamp": "2023-10-15T11:00:00Z",
+ "document": "statics/media/1752404965-document.pdf"
+ }
+}
+```
+
+With auto-download disabled:
+
+```json
+{
+ "event": "message",
+ "device_id": "[email protected]",
+ "payload": {
+ "id": "3EB0C127D7BACC83D6A6",
+ "chat_id": "[email protected]",
+ "from": "[email protected]",
+ "from_name": "John Doe",
+ "timestamp": "2023-10-15T11:00:00Z",
+ "document": {
+ "url": "https://mmg.whatsapp.net/...",
+ "filename": "report.pdf"
+ }
}
}
```
@@ -372,22 +414,33 @@ Triggered when users are demoted from admin.
```json
{
- "chat_id": "628968XXXXXXXX",
- "from": "[email protected]",
- "message": {
- "text": "",
+ "event": "message",
+ "device_id": "[email protected]",
+ "payload": {
"id": "446AC2BAF2061B53E24CA526DBDFBD4E",
- "replied_id": "",
- "quoted_message": ""
- },
- "pushname": "Aldino Kemal",
- "sender_id": "628968XXXXXXXX",
- "sticker": {
- "media_path": "statics/media/1752404986-ff2464a6-c54c-4e6c-afde-c4c925ce3573.webp",
- "mime_type": "image/webp",
- "caption": ""
- },
- "timestamp": "2025-07-13T11:09:45Z"
+ "chat_id": "[email protected]",
+ "from": "[email protected]",
+ "from_name": "John Doe",
+ "timestamp": "2025-07-13T11:09:45Z",
+ "sticker": "statics/media/1752404986-ff2464a6-c54c-4e6c-afde-c4c925ce3573.webp"
+ }
+}
+```
+
+### Video Note Message
+
+```json
+{
+ "event": "message",
+ "device_id": "[email protected]",
+ "payload": {
+ "id": "3EB0C127D7BACC83D6A7",
+ "chat_id": "[email protected]",
+ "from": "[email protected]",
+ "from_name": "John Doe",
+ "timestamp": "2023-10-15T11:02:00Z",
+ "video_note": "statics/media/1752404990-videonote.mp4"
+ }
}
```
@@ -397,30 +450,19 @@ Triggered when users are demoted from admin.
```json
{
- "chat_id": "6289XXXXXXXXX",
- "contact": {
- "displayName": "3Care",
- "vcard": "BEGIN:VCARD\nVERSION:3.0\nN:;3Care;;;\nFN:3Care\nTEL;type=Mobile:+62 132\nEND:VCARD",
- "contextInfo": {
- "expiration": 7776000,
- "ephemeralSettingTimestamp": 1751808692,
- "disappearingMode": {
- "initiator": 0,
- "trigger": 1,
- "initiatedByMe": true
- }
- }
- },
- "from": "[email protected]",
- "message": {
- "text": "",
+ "event": "message",
+ "device_id": "[email protected]",
+ "payload": {
"id": "56B3DFF4994284634E7AAFEEF6F1A0A2",
- "replied_id": "",
- "quoted_message": ""
- },
- "pushname": "Aldino Kemal",
- "sender_id": "6289XXXXXXXXX",
- "timestamp": "2025-07-13T11:10:19Z"
+ "chat_id": "[email protected]",
+ "from": "[email protected]",
+ "from_name": "John Doe",
+ "timestamp": "2025-07-13T11:10:19Z",
+ "contact": {
+ "displayName": "3Care",
+ "vcard": "BEGIN:VCARD\nVERSION:3.0\nN:;3Care;;;\nFN:3Care\nTEL;type=Mobile:+62 132\nEND:VCARD"
+ }
+ }
}
```
@@ -428,22 +470,20 @@ Triggered when users are demoted from admin.
```json
{
- "sender_id": "628123456789",
- "chat_id": "628987654321",
- "from": "John Doe",
- "timestamp": "2023-10-15T11:15:00Z",
- "pushname": "John Doe",
- "message": {
- "text": "",
+ "event": "message",
+ "device_id": "[email protected]",
+ "payload": {
"id": "3EB0C127D7BACC83D6A9",
- "replied_id": "",
- "quoted_message": ""
- },
- "location": {
- "degreesLatitude": -6.2088,
- "degreesLongitude": 106.8456,
- "name": "Jakarta, Indonesia",
- "address": "Central Jakarta, DKI Jakarta, Indonesia"
+ "chat_id": "[email protected]",
+ "from": "[email protected]",
+ "from_name": "John Doe",
+ "timestamp": "2023-10-15T11:15:00Z",
+ "location": {
+ "degreesLatitude": -6.2088,
+ "degreesLongitude": 106.8456,
+ "name": "Jakarta, Indonesia",
+ "address": "Central Jakarta, DKI Jakarta, Indonesia"
+ }
}
}
```
@@ -452,31 +492,19 @@ Triggered when users are demoted from admin.
```json
{
- "chat_id": "6289XXXXXXXXX",
- "from": "[email protected]",
- "location": {
- "degreesLatitude": -7.8050297,
- "degreesLongitude": 110.4549165,
- "JPEGThumbnail": "base64_image_thumbnail",
- "contextInfo": {
- "expiration": 7776000,
- "ephemeralSettingTimestamp": 1751808692,
- "disappearingMode": {
- "initiator": 0,
- "trigger": 1,
- "initiatedByMe": true
- }
- }
- },
- "message": {
- "text": "",
+ "event": "message",
+ "device_id": "[email protected]",
+ "payload": {
"id": "94D13237B4D7F33EE4A63228BBD79EC0",
- "replied_id": "",
- "quoted_message": ""
- },
- "pushname": "Aldino Kemal",
- "sender_id": "6289685XXXXXX",
- "timestamp": "2025-07-13T11:11:22Z"
+ "chat_id": "[email protected]",
+ "from": "[email protected]",
+ "from_name": "John Doe",
+ "timestamp": "2025-07-13T11:11:22Z",
+ "live_location": {
+ "degreesLatitude": -7.8050297,
+ "degreesLongitude": 110.4549165
+ }
+ }
}
```
@@ -486,21 +514,18 @@ Triggered when users are demoted from admin.
```json
{
- "action": "message_revoked",
- "chat_id": "6289XXXXXXXXX",
- "from": "[email protected]",
- "message": {
- "text": "",
+ "event": "message.revoked",
+ "device_id": "[email protected]",
+ "payload": {
"id": "F4062F2BBCB19B7432195AD7080DA4E2",
- "replied_id": "",
- "quoted_message": ""
- },
- "pushname": "Aldino Kemal",
- "revoked_chat": "[email protected]",
- "revoked_from_me": true,
- "revoked_message_id": "94D13237B4D7F33EE4A63228BBD79EC0",
- "sender_id": "6289XXXXXXXXX",
- "timestamp": "2025-07-13T11:13:30Z"
+ "chat_id": "[email protected]",
+ "from": "[email protected]",
+ "from_name": "John Doe",
+ "timestamp": "2025-07-13T11:13:30Z",
+ "revoked_message_id": "94D13237B4D7F33EE4A63228BBD79EC0",
+ "revoked_from_me": true,
+ "revoked_chat": "[email protected]"
+ }
}
```
@@ -510,27 +535,25 @@ When a message is edited, the webhook includes the original message ID to track
```json
{
- "action": "message_edited",
- "chat_id": "6289XXXXXXXXX",
- "original_message_id": "94D13237B4D7F33EE4A63228BBD79EC0",
- "edited_text": "hhhiawww",
- "from": "[email protected]",
- "message": {
- "text": "hhhiawww",
+ "event": "message.edited",
+ "device_id": "[email protected]",
+ "payload": {
"id": "D6271D8223A05B4DA6AE9FE3CD632543",
- "replied_id": "",
- "quoted_message": ""
- },
- "pushname": "Aldino Kemal",
- "sender_id": "6289XXXXXXXXX",
- "timestamp": "2025-07-13T11:14:19Z"
+ "chat_id": "[email protected]",
+ "from": "[email protected]",
+ "from_name": "John Doe",
+ "timestamp": "2025-07-13T11:14:19Z",
+ "original_message_id": "94D13237B4D7F33EE4A63228BBD79EC0",
+ "body": "Updated message text"
+ }
}
```
**Fields:**
+
- `original_message_id`: The ID of the message that was edited (use this to update the correct message in your database)
-- `edited_text`: The new text content after editing
-- `message.id`: The ID of the edit event itself (different from the original message ID)
+- `body`: The new text content after editing
+- `id`: The ID of the edit event itself (different from the original message ID)
## Special Flags
@@ -538,23 +561,17 @@ When a message is edited, the webhook includes the original message ID to track
```json
{
- "sender_id": "628123456789",
- "chat_id": "628987654321",
- "from": "John Doe",
- "timestamp": "2023-10-15T11:40:00Z",
- "pushname": "John Doe",
- "message": {
- "text": "",
+ "event": "message",
+ "device_id": "[email protected]",
+ "payload": {
"id": "3EB0C127D7BACC83D6B2",
- "replied_id": "",
- "quoted_message": ""
- },
- "image": {
- "media_path": "statics/media/1752405060-b9393cd1-8546-4df9-8a60-ee3276036aba.m4v",
- "mime_type": "image/jpeg",
- "caption": "okk"
- },
- "view_once": true
+ "chat_id": "[email protected]",
+ "from": "[email protected]",
+ "from_name": "John Doe",
+ "timestamp": "2023-10-15T11:40:00Z",
+ "image": "statics/media/1752405060-image.jpeg",
+ "view_once": true
+ }
}
```
@@ -562,18 +579,17 @@ When a message is edited, the webhook includes the original message ID to track
```json
{
- "sender_id": "628123456789",
- "chat_id": "628987654321",
- "from": "John Doe",
- "timestamp": "2023-10-15T11:45:00Z",
- "pushname": "John Doe",
- "message": {
- "text": "This is a forwarded message",
+ "event": "message",
+ "device_id": "[email protected]",
+ "payload": {
"id": "3EB0C127D7BACC83D6B3",
- "replied_id": "",
- "quoted_message": ""
- },
- "forwarded": true
+ "chat_id": "[email protected]",
+ "from": "[email protected]",
+ "from_name": "John Doe",
+ "timestamp": "2023-10-15T11:45:00Z",
+ "body": "This is a forwarded message",
+ "forwarded": true
+ }
}
```
@@ -622,48 +638,49 @@ app.post('/webhook', (req, res) => {
const data = JSON.parse(payload);
console.log('Received webhook:', data);
- // Handle different event types
- if (data.event === 'message.ack') {
- console.log(`Message ${data.payload.receipt_type}:`, {
- chat_id: data.payload.chat_id,
- message_ids: data.payload.ids,
- description: data.payload.receipt_type_description
- });
- } else if (data.event === 'group.participants') {
- console.log(`Group ${data.payload.type} event:`, {
- chat_id: data.payload.chat_id,
- type: data.payload.type,
- affected_users: data.payload.jids
- });
-
- // Handle specific group actions
- switch (data.payload.type) {
- case 'join':
- console.log(`${data.payload.jids.length} users joined group ${data.payload.chat_id}`);
- // Auto-greet new members
- data.payload.jids.forEach(jid => {
- console.log(`Welcome ${jid} to the group!`);
- });
- break;
- case 'leave':
- console.log(`${data.payload.jids.length} users left group ${data.payload.chat_id}`);
- // Update member database
- break;
- case 'promote':
- console.log(`${data.payload.jids.length} users promoted in group ${data.payload.chat_id}`);
- // Notify about new admins
- break;
- case 'demote':
- console.log(`${data.payload.jids.length} users demoted in group ${data.payload.chat_id}`);
- // Handle admin removal
- break;
- }
- } else if (data.action === 'message_deleted_for_me') {
- console.log('Message deleted:', data.deleted_message_id);
- } else if (data.action === 'message_revoked') {
- console.log('Message revoked:', data.revoked_message_id);
- } else if (data.message) {
- console.log('New message:', data.message.text);
+ // Handle different event types based on data.event
+ switch (data.event) {
+ case 'message':
+ console.log('New message:', {
+ id: data.payload.id,
+ from: data.payload.from,
+ body: data.payload.body,
+ chat_id: data.payload.chat_id
+ });
+ break;
+
+ case 'message.reaction':
+ console.log('Reaction:', {
+ reaction: data.payload.reaction,
+ reacted_message_id: data.payload.reacted_message_id
+ });
+ break;
+
+ case 'message.revoked':
+ console.log('Message revoked:', data.payload.revoked_message_id);
+ break;
+
+ case 'message.edited':
+ console.log('Message edited:', {
+ original_id: data.payload.original_message_id,
+ new_body: data.payload.body
+ });
+ break;
+
+ case 'message.ack':
+ console.log(`Message ${data.payload.receipt_type}:`, {
+ chat_id: data.payload.chat_id,
+ message_ids: data.payload.ids,
+ description: data.payload.receipt_type_description
+ });
+ break;
+
+ case 'group.participants':
+ console.log(`Group ${data.payload.type} event:`, {
+ chat_id: data.payload.chat_id,
+ affected_users: data.payload.jids
+ });
+ break;
}
res.status(200).send('OK');
diff --git a/gallery/homepage.png b/gallery/homepage.png
index 13d254e6..9b223aff 100644
Binary files a/gallery/homepage.png and b/gallery/homepage.png differ
diff --git a/readme.md b/readme.md
index ccb6e871..b58a431c 100644
--- a/readme.md
+++ b/readme.md
@@ -40,6 +40,23 @@ Download:
- `v7`
- Starting version 7.x we are using goreleaser to build the binary, so you can download the binary
from [release](https://github.com/aldinokemal/go-whatsapp-web-multidevice/releases/latest)
+- `v8`
+ - **Multi-device support**: You can now connect and manage multiple WhatsApp accounts simultaneously in a single server instance
+ - **New Device Management API**: New endpoints under `/devices` for managing multiple devices
+ - **Device scoping required**: All device-scoped REST API calls now require either:
+ - `X-Device-Id` header, or
+ - `device_id` query parameter
+ - If only one device is registered, it will be used as the default
+ - **WebSocket device scoping**: Connect to `/ws?device_id=<id>` to scope WebSocket to a specific device
+ - **Webhook payload changes**: All webhook payloads now include a top-level `device_id` field identifying which device received the event:
+
+ ```json
+ {
+ "event": "message",
+ "device_id": "[email protected]",
+ "payload": { ... }
+ }
+ ```
## Feature
@@ -86,6 +103,7 @@ Download:
- **Webhook TLS Configuration**
If you encounter TLS certificate verification errors when using webhooks (e.g., with Cloudflare tunnels or self-signed certificates):
+
```
tls: failed to verify certificate: x509: certificate signed by unknown authority
```
@@ -130,6 +148,7 @@ To use environment variables:
| Variable | Description | Default | Example |
|-------------------------------|---------------------------------------------|----------------------------------------------|---------------------------------------------|
| `APP_PORT` | Application port | `3000` | `APP_PORT=8080` |
+| `APP_HOST` | Host address to bind the server | `0.0.0.0` | `APP_HOST=127.0.0.1` |
| `APP_DEBUG` | Enable debug logging | `false` | `APP_DEBUG=true` |
| `APP_OS` | OS name (device name in WhatsApp) | `Chrome` | `APP_OS=MyApp` |
| `APP_BASIC_AUTH` | Basic authentication credentials | - | `APP_BASIC_AUTH=user1:pass1,user2:pass2` |
@@ -422,11 +441,21 @@ You can fork or edit this source code !
| Feature | Menu | Method | URL |
|---------|----------------------------------------|--------|-------------------------------------|
+| βœ… | List Devices | GET | /devices |
+| βœ… | Add Device | POST | /devices |
+| βœ… | Get Device Info | GET | /devices/:device_id |
+| βœ… | Remove Device | DELETE | /devices/:device_id |
+| βœ… | Login Device (QR) | GET | /devices/:device_id/login |
+| βœ… | Login Device (Code) | POST | /devices/:device_id/login/code |
+| βœ… | Logout Device | POST | /devices/:device_id/logout |
+| βœ… | Reconnect Device | POST | /devices/:device_id/reconnect |
+| βœ… | Get Device Status | GET | /devices/:device_id/status |
| βœ… | Login with Scan QR | GET | /app/login |
| βœ… | Login With Pair Code | GET | /app/login-with-code |
-| βœ… | Logout | GET | /app/logout |
+| βœ… | Logout | GET | /app/logout |
| βœ… | Reconnect | GET | /app/reconnect |
| βœ… | Devices | GET | /app/devices |
+| βœ… | Connection Status | GET | /app/status |
| βœ… | User Info | GET | /user/info |
| βœ… | User Avatar | GET | /user/avatar |
| βœ… | User Change Avatar | POST | /user/avatar |
@@ -456,6 +485,7 @@ You can fork or edit this source code !
| βœ… | Read Message (DM) | POST | /message/:message_id/read |
| βœ… | Star Message | POST | /message/:message_id/star |
| βœ… | Unstar Message | POST | /message/:message_id/unstar |
+| βœ… | Download Message Media | GET | /message/:message_id/download |
| βœ… | Join Group With Link | POST | /group/join-with-link |
| βœ… | Group Info From Link | GET | /group/info-from-link |
| βœ… | Group Info | GET | /group/info |
@@ -503,7 +533,7 @@ You can fork or edit this source code !
| Description | Image |
|----------------------|---------------------------------------------------------------|
-| Homepage | ![Homepage](./gallery/homepage.png) |
+| Homepage | ![Homepage](./gallery/homepage.png?v=1) |
| Login | ![Login](./gallery/login.png) |
| Login With Code | ![Login With Code](./gallery/login-with-code.png) |
| Send Message | ![Send Message](./gallery/send-message.png) |
diff --git a/src/.env.example b/src/.env.example
index 3476f43f..3e1344ae 100644
--- a/src/.env.example
+++ b/src/.env.example
@@ -1,5 +1,6 @@
# Application Settings
APP_PORT=3000
+APP_HOST=0.0.0.0
APP_DEBUG=false
APP_OS=Chrome
APP_BASIC_AUTH=user1:pass1,user2:pass2
diff --git a/src/cmd/rest.go b/src/cmd/rest.go
index 80d31168..7aa96ea3 100644
--- a/src/cmd/rest.go
+++ b/src/cmd/rest.go
@@ -6,6 +6,7 @@ import (
"strings"
"github.com/aldinokemal/go-whatsapp-web-multidevice/config"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/whatsapp"
"github.com/aldinokemal/go-whatsapp-web-multidevice/ui/rest"
"github.com/aldinokemal/go-whatsapp-web-multidevice/ui/rest/helpers"
"github.com/aldinokemal/go-whatsapp-web-multidevice/ui/rest/middleware"
@@ -95,14 +96,26 @@ func restServer(_ *cobra.Command, _ []string) {
apiGroup = app.Group(config.AppBasePath)
}
- // Rest
- rest.InitRestApp(apiGroup, appUsecase)
- rest.InitRestChat(apiGroup, chatUsecase)
- rest.InitRestSend(apiGroup, sendUsecase)
- rest.InitRestUser(apiGroup, userUsecase)
- rest.InitRestMessage(apiGroup, messageUsecase)
- rest.InitRestGroup(apiGroup, groupUsecase)
- rest.InitRestNewsletter(apiGroup, newsletterUsecase)
+ // Device manager aware routing
+ dm := whatsapp.GetDeviceManager()
+
+ registerDeviceScopedRoutes := func(r fiber.Router) {
+ rest.InitRestApp(r, appUsecase)
+ rest.InitRestChat(r, chatUsecase)
+ rest.InitRestSend(r, sendUsecase)
+ rest.InitRestUser(r, userUsecase)
+ rest.InitRestMessage(r, messageUsecase)
+ rest.InitRestGroup(r, groupUsecase)
+ rest.InitRestNewsletter(r, newsletterUsecase)
+ websocket.RegisterRoutes(r, appUsecase)
+ }
+
+ // Device management routes (no device_id required)
+ rest.InitRestDevice(apiGroup, deviceUsecase)
+
+ // Device-scoped operations (header-based)
+ headerDeviceGroup := apiGroup.Group("", middleware.DeviceMiddleware(dm))
+ registerDeviceScopedRoutes(headerDeviceGroup)
apiGroup.Get("/", func(c *fiber.Ctx) error {
return c.Render("views/index", fiber.Map{
@@ -115,7 +128,6 @@ func restServer(_ *cobra.Command, _ []string) {
})
})
- websocket.RegisterRoutes(apiGroup, appUsecase)
go websocket.RunHub()
// Set auto reconnect to whatsapp server after booting
@@ -124,7 +136,7 @@ func restServer(_ *cobra.Command, _ []string) {
// Set auto reconnect checking with a guaranteed client instance
startAutoReconnectCheckerIfClientAvailable()
- if err := app.Listen(":" + config.AppPort); err != nil {
+ if err := app.Listen(config.AppHost + ":" + config.AppPort); err != nil {
logrus.Fatalln("Failed to start: ", err.Error())
}
}
diff --git a/src/cmd/root.go b/src/cmd/root.go
index b358124a..07c356b9 100644
--- a/src/cmd/root.go
+++ b/src/cmd/root.go
@@ -5,15 +5,17 @@ import (
"database/sql"
"embed"
"fmt"
- "go.mau.fi/whatsmeow/store/sqlstore"
"os"
"strings"
"time"
+ "go.mau.fi/whatsmeow/store/sqlstore"
+
"github.com/aldinokemal/go-whatsapp-web-multidevice/config"
domainApp "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/app"
domainChat "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chat"
domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
+ domainDevice "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/device"
domainGroup "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/group"
domainMessage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/message"
domainNewsletter "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/newsletter"
@@ -50,6 +52,7 @@ var (
messageUsecase domainMessage.IMessageUsecase
groupUsecase domainGroup.IGroupUsecase
newsletterUsecase domainNewsletter.INewsletterUsecase
+ deviceUsecase domainDevice.IDeviceUsecase
)
// rootCmd represents the base command when called without any subcommands
@@ -81,6 +84,9 @@ func initEnvConfig() {
if envPort := viper.GetString("app_port"); envPort != "" {
config.AppPort = envPort
}
+ if envHost := viper.GetString("app_host"); envHost != "" {
+ config.AppHost = envHost
+ }
if envDebug := viper.GetBool("app_debug"); envDebug {
config.AppDebug = envDebug
}
@@ -141,6 +147,13 @@ func initFlags() {
"change port number with --port <number> | example: --port=8080",
)
+ rootCmd.PersistentFlags().StringVarP(
+ &config.AppHost,
+ "host", "H",
+ config.AppHost,
+ `host to bind the server --host <string> | example: --host="127.0.0.1"`,
+ )
+
rootCmd.PersistentFlags().BoolVarP(
&config.AppDebug,
"debug", "d",
@@ -286,14 +299,21 @@ func initApp() {
whatsappCli = whatsapp.InitWaCLI(ctx, whatsappDB, keysDB, chatStorageRepo)
+ // Initialize device manager and usecase for multi-device support
+ dm := whatsapp.GetDeviceManager()
+ if dm != nil {
+ _ = dm.LoadExistingDevices(ctx)
+ }
+
// Usecase
- appUsecase = usecase.NewAppService(chatStorageRepo)
+ appUsecase = usecase.NewAppService(chatStorageRepo, dm)
chatUsecase = usecase.NewChatService(chatStorageRepo)
sendUsecase = usecase.NewSendService(appUsecase, chatStorageRepo)
userUsecase = usecase.NewUserService()
messageUsecase = usecase.NewMessageService(chatStorageRepo)
groupUsecase = usecase.NewGroupService()
newsletterUsecase = usecase.NewNewsletterService()
+ deviceUsecase = usecase.NewDeviceService(dm)
}
// Execute adds all child commands to the root command and sets flags appropriately.
diff --git a/src/config/settings.go b/src/config/settings.go
index fbc726f8..b04ce9b4 100644
--- a/src/config/settings.go
+++ b/src/config/settings.go
@@ -5,8 +5,9 @@ import (
)
var (
- AppVersion = "v7.11.0"
+ AppVersion = "v8.0.0"
AppPort = "3000"
+ AppHost = "0.0.0.0"
AppDebug = false
AppOs = "AldinoKemal"
AppPlatform = waCompanionReg.DeviceProps_PlatformType(1)
diff --git a/src/domains/app/app.go b/src/domains/app/app.go
index 6325ed7c..41178fb1 100644
--- a/src/domains/app/app.go
+++ b/src/domains/app/app.go
@@ -6,10 +6,11 @@ import (
)
type IAppUsecase interface {
- Login(ctx context.Context) (response LoginResponse, err error)
- LoginWithCode(ctx context.Context, phoneNumber string) (loginCode string, err error)
- Logout(ctx context.Context) (err error)
- Reconnect(ctx context.Context) (err error)
+ Login(ctx context.Context, deviceID string) (response LoginResponse, err error)
+ LoginWithCode(ctx context.Context, deviceID string, phoneNumber string) (loginCode string, err error)
+ Logout(ctx context.Context, deviceID string) (err error)
+ Reconnect(ctx context.Context, deviceID string) (err error)
+ Status(ctx context.Context, deviceID string) (isConnected bool, isLoggedIn bool, err error)
FirstDevice(ctx context.Context) (response DevicesResponse, err error)
FetchDevices(ctx context.Context) (response []DevicesResponse, err error)
}
diff --git a/src/domains/chatstorage/chatstorage.go b/src/domains/chatstorage/chatstorage.go
index 08b481d6..633d2ad1 100644
--- a/src/domains/chatstorage/chatstorage.go
+++ b/src/domains/chatstorage/chatstorage.go
@@ -4,6 +4,7 @@ import "time"
// Chat represents a WhatsApp chat/conversation
type Chat struct {
+ DeviceID string `db:"device_id"`
JID string `db:"jid"`
Name string `db:"name"`
LastMessageTime time.Time `db:"last_message_time"`
@@ -16,6 +17,7 @@ type Chat struct {
type Message struct {
ID string `db:"id"`
ChatJID string `db:"chat_jid"`
+ DeviceID string `db:"device_id"`
Sender string `db:"sender"`
Content string `db:"content"`
Timestamp time.Time `db:"timestamp"`
@@ -44,6 +46,15 @@ type MediaInfo struct {
FileLength uint64
}
+// DeviceRecord tracks a registered device for persistence purposes.
+type DeviceRecord struct {
+ DeviceID string `db:"device_id"`
+ DisplayName string `db:"display_name"`
+ JID string `db:"jid"`
+ CreatedAt time.Time `db:"created_at"`
+ UpdatedAt time.Time `db:"updated_at"`
+}
+
// MessageFilter represents query filters for messages
type MessageFilter struct {
ChatJID string
@@ -57,6 +68,7 @@ type MessageFilter struct {
// ChatFilter represents query filters for chats
type ChatFilter struct {
+ DeviceID string
Limit int
Offset int
SearchName string
diff --git a/src/domains/chatstorage/interfaces.go b/src/domains/chatstorage/interfaces.go
index ba6534b9..c3183682 100644
--- a/src/domains/chatstorage/interfaces.go
+++ b/src/domains/chatstorage/interfaces.go
@@ -35,6 +35,13 @@ type IChatStorageRepository interface {
// Cleanup operations
TruncateAllChats() error
TruncateAllDataWithLogging(logPrefix string) error
+ DeleteDeviceData(deviceID string) error
+
+ // Device registry operations
+ SaveDeviceRecord(record *DeviceRecord) error
+ ListDeviceRecords() ([]*DeviceRecord, error)
+ GetDeviceRecord(deviceID string) (*DeviceRecord, error)
+ DeleteDeviceRecord(deviceID string) error
// Schema operations
InitializeSchema() error
diff --git a/src/domains/device/device.go b/src/domains/device/device.go
new file mode 100644
index 00000000..17257d0a
--- /dev/null
+++ b/src/domains/device/device.go
@@ -0,0 +1,24 @@
+package device
+
+import "time"
+
+// DeviceState represents the connection lifecycle of a WhatsApp device.
+// States are intentionally string-based for easy logging and JSON responses.
+type DeviceState string
+
+const (
+ DeviceStateDisconnected DeviceState = "disconnected"
+ DeviceStateConnecting DeviceState = "connecting"
+ DeviceStateConnected DeviceState = "connected"
+ DeviceStateLoggedIn DeviceState = "logged_in"
+)
+
+// Device describes a WhatsApp account/device tracked by the system.
+type Device struct {
+ ID string `json:"id"`
+ PhoneNumber string `json:"phone_number,omitempty"`
+ DisplayName string `json:"display_name,omitempty"`
+ State DeviceState `json:"state"`
+ JID string `json:"jid,omitempty"`
+ CreatedAt time.Time `json:"created_at"`
+}
diff --git a/src/domains/device/interfaces.go b/src/domains/device/interfaces.go
new file mode 100644
index 00000000..66b33e0a
--- /dev/null
+++ b/src/domains/device/interfaces.go
@@ -0,0 +1,16 @@
+package device
+
+import "context"
+
+// IDeviceUsecase defines device lifecycle operations.
+type IDeviceUsecase interface {
+ ListDevices(ctx context.Context) ([]Device, error)
+ GetDevice(ctx context.Context, deviceID string) (*Device, error)
+ AddDevice(ctx context.Context, deviceID string) (*Device, error)
+ RemoveDevice(ctx context.Context, deviceID string) error
+ LoginDevice(ctx context.Context, deviceID string) error
+ LoginDeviceWithCode(ctx context.Context, deviceID string, phone string) (string, error)
+ LogoutDevice(ctx context.Context, deviceID string) error
+ ReconnectDevice(ctx context.Context, deviceID string) error
+ GetStatus(ctx context.Context, deviceID string) (isConnected bool, isLoggedIn bool, err error)
+}
diff --git a/src/go.mod b/src/go.mod
index 2fe7284f..28683d83 100644
--- a/src/go.mod
+++ b/src/go.mod
@@ -21,9 +21,9 @@ require (
github.com/stretchr/testify v1.11.1
github.com/valyala/fasthttp v1.68.0
go.mau.fi/libsignal v0.2.1
- go.mau.fi/whatsmeow v0.0.0-20251205211405-fd6170ac96e5
+ go.mau.fi/whatsmeow v0.0.0-20251217143725-11cf47c62d32
golang.org/x/image v0.34.0
- google.golang.org/protobuf v1.36.10
+ google.golang.org/protobuf v1.36.11
)
require (
@@ -68,10 +68,10 @@ require (
github.com/wk8/go-ordered-map/v2 v2.1.8 // indirect
github.com/xyproto/randomstring v1.2.0 // indirect
github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
- go.mau.fi/util v0.9.3 // indirect
+ go.mau.fi/util v0.9.4 // indirect
go.yaml.in/yaml/v3 v3.0.4 // indirect
golang.org/x/crypto v0.46.0 // indirect
- golang.org/x/exp v0.0.0-20251209150349-8475f28825e9 // indirect
+ golang.org/x/exp v0.0.0-20251219203646-944ab1f22d93 // indirect
golang.org/x/net v0.48.0 // indirect
golang.org/x/sys v0.39.0 // indirect
golang.org/x/text v0.32.0 // indirect
diff --git a/src/go.sum b/src/go.sum
index 5d8ee708..ac7b486b 100644
--- a/src/go.sum
+++ b/src/go.sum
@@ -152,10 +152,10 @@ github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT0
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
go.mau.fi/libsignal v0.2.1 h1:vRZG4EzTn70XY6Oh/pVKrQGuMHBkAWlGRC22/85m9L0=
go.mau.fi/libsignal v0.2.1/go.mod h1:iVvjrHyfQqWajOUaMEsIfo3IqgVMrhWcPiiEzk7NgoU=
-go.mau.fi/util v0.9.3 h1:aqNF8KDIN8bFpFbybSk+mEBil7IHeBwlujfyTnvP0uU=
-go.mau.fi/util v0.9.3/go.mod h1:krWWfBM1jWTb5f8NCa2TLqWMQuM81X7TGQjhMjBeXmQ=
-go.mau.fi/whatsmeow v0.0.0-20251205211405-fd6170ac96e5 h1:ld9iMjQ2PxZtsrbq2vFsFPf6qDhiON3DiEipQEPI8hA=
-go.mau.fi/whatsmeow v0.0.0-20251205211405-fd6170ac96e5/go.mod h1:5aYaEa3FF5e5XWsA8Xa80ttUXZvb6HyaBGgo2SfzUkE=
+go.mau.fi/util v0.9.4 h1:gWdUff+K2rCynRPysXalqqQyr2ahkSWaestH6YhSpso=
+go.mau.fi/util v0.9.4/go.mod h1:647nVfwUvuhlZFOnro3aRNPmRd2y3iDha9USb8aKSmM=
+go.mau.fi/whatsmeow v0.0.0-20251217143725-11cf47c62d32 h1:NeE9eEYY4kEJVCfCXaAU27LgAPugPHRHJdC9IpXFPzI=
+go.mau.fi/whatsmeow v0.0.0-20251217143725-11cf47c62d32/go.mod h1:S4OWR9+hTx+54+jRzl+NfRBXnGpPm5IRPyhXB7haSd0=
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
@@ -166,8 +166,8 @@ golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v
golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU=
golang.org/x/crypto v0.46.0/go.mod h1:Evb/oLKmMraqjZ2iQTwDwvCtJkczlDuTmdJXoZVzqU0=
-golang.org/x/exp v0.0.0-20251209150349-8475f28825e9 h1:MDfG8Cvcqlt9XXrmEiD4epKn7VJHZO84hejP9Jmp0MM=
-golang.org/x/exp v0.0.0-20251209150349-8475f28825e9/go.mod h1:EPRbTFwzwjXj9NpYyyrvenVh9Y+GFeEvMNh7Xuz7xgU=
+golang.org/x/exp v0.0.0-20251219203646-944ab1f22d93 h1:fQsdNF2N+/YewlRZiricy4P1iimyPKZ/xwniHj8Q2a0=
+golang.org/x/exp v0.0.0-20251219203646-944ab1f22d93/go.mod h1:EPRbTFwzwjXj9NpYyyrvenVh9Y+GFeEvMNh7Xuz7xgU=
golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/image v0.34.0 h1:33gCkyw9hmwbZJeZkct8XyR11yH889EQt/QH4VmXMn8=
golang.org/x/image v0.34.0/go.mod h1:2RNFBZRB+vnwwFil8GkMdRvrJOFd1AzdZI6vOY+eJVU=
@@ -237,8 +237,8 @@ golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58=
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
-google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE=
-google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
+google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
+google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
diff --git a/src/infrastructure/chatstorage/device_repository.go b/src/infrastructure/chatstorage/device_repository.go
new file mode 100644
index 00000000..25b5cf9b
--- /dev/null
+++ b/src/infrastructure/chatstorage/device_repository.go
@@ -0,0 +1,164 @@
+package chatstorage
+
+import (
+ "context"
+ "strings"
+ "time"
+
+ domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
+ "go.mau.fi/whatsmeow/types"
+ "go.mau.fi/whatsmeow/types/events"
+)
+
+// DeviceRepository wraps a base repository and injects device_id into all operations.
+// This keeps the existing interface while making sure each device is logically separated.
+type DeviceRepository struct {
+ deviceID string
+ base domainChatStorage.IChatStorageRepository
+}
+
+func NewDeviceRepository(deviceID string, base domainChatStorage.IChatStorageRepository) domainChatStorage.IChatStorageRepository {
+ return &DeviceRepository{
+ deviceID: deviceID,
+ base: base,
+ }
+}
+
+func (r *DeviceRepository) withDeviceChat(chat *domainChatStorage.Chat) *domainChatStorage.Chat {
+ if chat == nil {
+ return nil
+ }
+
+ // Prefer a JID already set on the chat.
+ if chat.DeviceID != "" && strings.Contains(chat.DeviceID, "@") {
+ r.deviceID = chat.DeviceID
+ return chat
+ }
+
+ // Apply wrapper JID if already known.
+ if strings.Contains(r.deviceID, "@") {
+ chat.DeviceID = r.deviceID
+ return chat
+ }
+
+ // Fallback to wrapper device ID when chat is empty.
+ if chat.DeviceID == "" {
+ chat.DeviceID = r.deviceID
+ }
+ return chat
+}
+
+func (r *DeviceRepository) CreateMessage(ctx context.Context, evt *events.Message) error {
+ // Base repository will attempt to derive device id from client; keep call unchanged for now.
+ return r.base.CreateMessage(ctx, evt)
+}
+
+func (r *DeviceRepository) StoreChat(chat *domainChatStorage.Chat) error {
+ return r.base.StoreChat(r.withDeviceChat(chat))
+}
+
+func (r *DeviceRepository) GetChat(jid string) (*domainChatStorage.Chat, error) {
+ return r.base.GetChat(jid)
+}
+
+func (r *DeviceRepository) GetChats(filter *domainChatStorage.ChatFilter) ([]*domainChatStorage.Chat, error) {
+ if filter != nil {
+ switch {
+ case filter.DeviceID != "" && strings.Contains(filter.DeviceID, "@"):
+ r.deviceID = filter.DeviceID
+ case strings.Contains(r.deviceID, "@"):
+ filter.DeviceID = r.deviceID
+ case filter.DeviceID == "":
+ filter.DeviceID = r.deviceID
+ }
+ }
+ return r.base.GetChats(filter)
+}
+
+func (r *DeviceRepository) DeleteChat(jid string) error {
+ return r.base.DeleteChat(jid)
+}
+
+func (r *DeviceRepository) StoreMessage(message *domainChatStorage.Message) error {
+ return r.base.StoreMessage(message)
+}
+
+func (r *DeviceRepository) StoreMessagesBatch(messages []*domainChatStorage.Message) error {
+ return r.base.StoreMessagesBatch(messages)
+}
+
+func (r *DeviceRepository) GetMessageByID(id string) (*domainChatStorage.Message, error) {
+ return r.base.GetMessageByID(id)
+}
+
+func (r *DeviceRepository) GetMessages(filter *domainChatStorage.MessageFilter) ([]*domainChatStorage.Message, error) {
+ return r.base.GetMessages(filter)
+}
+
+func (r *DeviceRepository) SearchMessages(chatJID, searchText string, limit int) ([]*domainChatStorage.Message, error) {
+ return r.base.SearchMessages(chatJID, searchText, limit)
+}
+
+func (r *DeviceRepository) DeleteMessage(id, chatJID string) error {
+ return r.base.DeleteMessage(id, chatJID)
+}
+
+func (r *DeviceRepository) StoreSentMessageWithContext(ctx context.Context, messageID string, senderJID string, recipientJID string, content string, timestamp time.Time) error {
+ return r.base.StoreSentMessageWithContext(ctx, messageID, senderJID, recipientJID, content, timestamp)
+}
+
+func (r *DeviceRepository) GetChatMessageCount(chatJID string) (int64, error) {
+ return r.base.GetChatMessageCount(chatJID)
+}
+
+func (r *DeviceRepository) GetTotalMessageCount() (int64, error) {
+ return r.base.GetTotalMessageCount()
+}
+
+func (r *DeviceRepository) GetTotalChatCount() (int64, error) {
+ return r.base.GetTotalChatCount()
+}
+
+func (r *DeviceRepository) GetChatNameWithPushName(jid types.JID, chatJID string, senderUser string, pushName string) string {
+ return r.base.GetChatNameWithPushName(jid, chatJID, senderUser, pushName)
+}
+
+func (r *DeviceRepository) GetStorageStatistics() (chatCount int64, messageCount int64, err error) {
+ return r.base.GetStorageStatistics()
+}
+
+func (r *DeviceRepository) TruncateAllChats() error {
+ return r.base.TruncateAllChats()
+}
+
+func (r *DeviceRepository) TruncateAllDataWithLogging(logPrefix string) error {
+ return r.base.TruncateAllDataWithLogging(logPrefix)
+}
+
+func (r *DeviceRepository) InitializeSchema() error {
+ return r.base.InitializeSchema()
+}
+
+func (r *DeviceRepository) DeleteDeviceData(deviceID string) error {
+ target := deviceID
+ if target == "" {
+ target = r.deviceID
+ }
+ return r.base.DeleteDeviceData(target)
+}
+
+func (r *DeviceRepository) SaveDeviceRecord(record *domainChatStorage.DeviceRecord) error {
+ return r.base.SaveDeviceRecord(record)
+}
+
+func (r *DeviceRepository) ListDeviceRecords() ([]*domainChatStorage.DeviceRecord, error) {
+ return r.base.ListDeviceRecords()
+}
+
+func (r *DeviceRepository) GetDeviceRecord(deviceID string) (*domainChatStorage.DeviceRecord, error) {
+ return r.base.GetDeviceRecord(deviceID)
+}
+
+func (r *DeviceRepository) DeleteDeviceRecord(deviceID string) error {
+ return r.base.DeleteDeviceRecord(deviceID)
+}
diff --git a/src/infrastructure/chatstorage/sqlite_repository.go b/src/infrastructure/chatstorage/sqlite_repository.go
index f0679b80..6e328714 100644
--- a/src/infrastructure/chatstorage/sqlite_repository.go
+++ b/src/infrastructure/chatstorage/sqlite_repository.go
@@ -30,24 +30,29 @@ func (r *SQLiteRepository) StoreChat(chat *domainChatStorage.Chat) error {
now := time.Now()
chat.UpdatedAt = now
- query := `
- INSERT INTO chats (jid, name, last_message_time, ephemeral_expiration, created_at, updated_at)
- VALUES (?, ?, ?, ?, ?, ?)
- ON CONFLICT(jid) DO UPDATE SET
- name = excluded.name,
- last_message_time = excluded.last_message_time,
- ephemeral_expiration = excluded.ephemeral_expiration,
- updated_at = excluded.updated_at
- `
+ // Try update first, then insert if no rows affected (cross-db compatible)
+ result, err := r.db.Exec(`
+ UPDATE chats SET name = ?, last_message_time = ?, ephemeral_expiration = ?, updated_at = ?
+ WHERE jid = ? AND device_id = ?
+ `, chat.Name, chat.LastMessageTime, chat.EphemeralExpiration, chat.UpdatedAt, chat.JID, chat.DeviceID)
+ if err != nil {
+ return err
+ }
- _, err := r.db.Exec(query, chat.JID, chat.Name, chat.LastMessageTime, chat.EphemeralExpiration, now, chat.UpdatedAt)
+ rowsAffected, _ := result.RowsAffected()
+ if rowsAffected == 0 {
+ _, err = r.db.Exec(`
+ INSERT INTO chats (jid, device_id, name, last_message_time, ephemeral_expiration, created_at, updated_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?)
+ `, chat.JID, chat.DeviceID, chat.Name, chat.LastMessageTime, chat.EphemeralExpiration, now, chat.UpdatedAt)
+ }
return err
}
// GetChat retrieves a chat by JID
func (r *SQLiteRepository) GetChat(jid string) (*domainChatStorage.Chat, error) {
query := `
- SELECT jid, name, last_message_time, ephemeral_expiration, created_at, updated_at
+ SELECT device_id, jid, name, last_message_time, ephemeral_expiration, created_at, updated_at
FROM chats
WHERE jid = ?
`
@@ -64,7 +69,7 @@ func (r *SQLiteRepository) GetChat(jid string) (*domainChatStorage.Chat, error)
// This is more efficient than searching through all chats
func (r *SQLiteRepository) GetMessageByID(id string) (*domainChatStorage.Message, error) {
query := `
- SELECT id, chat_jid, sender, content, timestamp, is_from_me,
+ SELECT id, chat_jid, device_id, sender, content, timestamp, is_from_me,
media_type, filename, url, media_key, file_sha256,
file_enc_sha256, file_length, created_at, updated_at
FROM messages
@@ -86,7 +91,7 @@ func (r *SQLiteRepository) GetChats(filter *domainChatStorage.ChatFilter) ([]*do
var args []any
query := `
- SELECT c.jid, c.name, c.last_message_time, c.ephemeral_expiration, c.created_at, c.updated_at
+ SELECT c.device_id, c.jid, c.name, c.last_message_time, c.ephemeral_expiration, c.created_at, c.updated_at
FROM chats c
`
@@ -96,10 +101,15 @@ func (r *SQLiteRepository) GetChats(filter *domainChatStorage.ChatFilter) ([]*do
}
if filter.HasMedia {
- query += " INNER JOIN messages m ON c.jid = m.chat_jid"
+ query += " INNER JOIN messages m ON c.jid = m.chat_jid AND c.device_id = m.device_id"
conditions = append(conditions, "m.media_type != ''")
}
+ if filter.DeviceID != "" {
+ conditions = append(conditions, "c.device_id = ?")
+ args = append(args, filter.DeviceID)
+ }
+
if len(conditions) > 0 {
query += " WHERE " + strings.Join(conditions, " AND ")
}
@@ -170,38 +180,36 @@ func (r *SQLiteRepository) StoreMessage(message *domainChatStorage.Message) erro
// Skip empty messages
if message.Content == "" && message.MediaType == "" {
- // This is not an error, just skip storing empty messages
return nil
}
- query := `
- INSERT INTO messages (
- id, chat_jid, sender, content, timestamp, is_from_me,
- media_type, filename, url, media_key, file_sha256,
- file_enc_sha256, file_length, created_at, updated_at
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
- ON CONFLICT(id, chat_jid) DO UPDATE SET
- sender = excluded.sender,
- content = excluded.content,
- timestamp = excluded.timestamp,
- is_from_me = excluded.is_from_me,
- media_type = excluded.media_type,
- filename = excluded.filename,
- url = excluded.url,
- media_key = excluded.media_key,
- file_sha256 = excluded.file_sha256,
- file_enc_sha256 = excluded.file_enc_sha256,
- file_length = excluded.file_length,
- updated_at = excluded.updated_at
- `
-
- _, err := r.db.Exec(query,
- message.ID, message.ChatJID, message.Sender, message.Content,
- message.Timestamp, message.IsFromMe, message.MediaType, message.Filename,
- message.URL, message.MediaKey, message.FileSHA256, message.FileEncSHA256,
- message.FileLength, message.CreatedAt, message.UpdatedAt,
- )
+ // Try update first, then insert if no rows affected (cross-db compatible)
+ result, err := r.db.Exec(`
+ UPDATE messages SET sender = ?, content = ?, timestamp = ?, is_from_me = ?,
+ media_type = ?, filename = ?, url = ?, media_key = ?, file_sha256 = ?,
+ file_enc_sha256 = ?, file_length = ?, updated_at = ?
+ WHERE id = ? AND chat_jid = ? AND device_id = ?
+ `, message.Sender, message.Content, message.Timestamp, message.IsFromMe,
+ message.MediaType, message.Filename, message.URL, message.MediaKey, message.FileSHA256,
+ message.FileEncSHA256, message.FileLength, message.UpdatedAt,
+ message.ID, message.ChatJID, message.DeviceID)
+ if err != nil {
+ return err
+ }
+ rowsAffected, _ := result.RowsAffected()
+ if rowsAffected == 0 {
+ _, err = r.db.Exec(`
+ INSERT INTO messages (
+ id, chat_jid, device_id, sender, content, timestamp, is_from_me,
+ media_type, filename, url, media_key, file_sha256,
+ file_enc_sha256, file_length, created_at, updated_at
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ `, message.ID, message.ChatJID, message.DeviceID, message.Sender, message.Content,
+ message.Timestamp, message.IsFromMe, message.MediaType, message.Filename,
+ message.URL, message.MediaKey, message.FileSHA256, message.FileEncSHA256,
+ message.FileLength, message.CreatedAt, message.UpdatedAt)
+ }
return err
}
@@ -217,35 +225,32 @@ func (r *SQLiteRepository) StoreMessagesBatch(messages []*domainChatStorage.Mess
}
defer tx.Rollback()
- // Prepare the statement once for better performance
- stmt, err := tx.Prepare(`
+ // Prepare statements for update and insert
+ updateStmt, err := tx.Prepare(`
+ UPDATE messages SET sender = ?, content = ?, timestamp = ?, is_from_me = ?,
+ media_type = ?, filename = ?, url = ?, media_key = ?, file_sha256 = ?,
+ file_enc_sha256 = ?, file_length = ?, updated_at = ?
+ WHERE id = ? AND chat_jid = ? AND device_id = ?
+ `)
+ if err != nil {
+ return fmt.Errorf("failed to prepare update statement: %w", err)
+ }
+ defer updateStmt.Close()
+
+ insertStmt, err := tx.Prepare(`
INSERT INTO messages (
- id, chat_jid, sender, content, timestamp, is_from_me,
- media_type, filename, url, media_key, file_sha256,
+ id, chat_jid, device_id, sender, content, timestamp, is_from_me,
+ media_type, filename, url, media_key, file_sha256,
file_enc_sha256, file_length, created_at, updated_at
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
- ON CONFLICT(id, chat_jid) DO UPDATE SET
- sender = excluded.sender,
- content = excluded.content,
- timestamp = excluded.timestamp,
- is_from_me = excluded.is_from_me,
- media_type = excluded.media_type,
- filename = excluded.filename,
- url = excluded.url,
- media_key = excluded.media_key,
- file_sha256 = excluded.file_sha256,
- file_enc_sha256 = excluded.file_enc_sha256,
- file_length = excluded.file_length,
- updated_at = excluded.updated_at
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`)
if err != nil {
- return fmt.Errorf("failed to prepare statement: %w", err)
+ return fmt.Errorf("failed to prepare insert statement: %w", err)
}
- defer stmt.Close()
+ defer insertStmt.Close()
now := time.Now()
for _, message := range messages {
- // Skip empty messages
if message.Content == "" && message.MediaType == "" {
continue
}
@@ -253,14 +258,27 @@ func (r *SQLiteRepository) StoreMessagesBatch(messages []*domainChatStorage.Mess
message.CreatedAt = now
message.UpdatedAt = now
- _, err = stmt.Exec(
- message.ID, message.ChatJID, message.Sender, message.Content,
- message.Timestamp, message.IsFromMe, message.MediaType, message.Filename,
- message.URL, message.MediaKey, message.FileSHA256, message.FileEncSHA256,
- message.FileLength, message.CreatedAt, message.UpdatedAt,
+ result, err := updateStmt.Exec(
+ message.Sender, message.Content, message.Timestamp, message.IsFromMe,
+ message.MediaType, message.Filename, message.URL, message.MediaKey, message.FileSHA256,
+ message.FileEncSHA256, message.FileLength, message.UpdatedAt,
+ message.ID, message.ChatJID, message.DeviceID,
)
if err != nil {
- return fmt.Errorf("failed to store message %s: %w", message.ID, err)
+ return fmt.Errorf("failed to update message %s: %w", message.ID, err)
+ }
+
+ rowsAffected, _ := result.RowsAffected()
+ if rowsAffected == 0 {
+ _, err = insertStmt.Exec(
+ message.ID, message.ChatJID, message.DeviceID, message.Sender, message.Content,
+ message.Timestamp, message.IsFromMe, message.MediaType, message.Filename,
+ message.URL, message.MediaKey, message.FileSHA256, message.FileEncSHA256,
+ message.FileLength, message.CreatedAt, message.UpdatedAt,
+ )
+ if err != nil {
+ return fmt.Errorf("failed to insert message %s: %w", message.ID, err)
+ }
}
}
@@ -295,7 +313,7 @@ func (r *SQLiteRepository) GetMessages(filter *domainChatStorage.MessageFilter)
}
query := `
- SELECT id, chat_jid, sender, content, timestamp, is_from_me,
+ SELECT id, chat_jid, device_id, sender, content, timestamp, is_from_me,
media_type, filename, url, media_key, file_sha256,
file_enc_sha256, file_length, created_at, updated_at
FROM messages
@@ -355,7 +373,7 @@ func (r *SQLiteRepository) SearchMessages(chatJID, searchText string, limit int)
args = append(args, "%"+strings.ToLower(searchText)+"%")
query := `
- SELECT id, chat_jid, sender, content, timestamp, is_from_me,
+ SELECT id, chat_jid, device_id, sender, content, timestamp, is_from_me,
media_type, filename, url, media_key, file_sha256,
file_enc_sha256, file_length, created_at, updated_at
FROM messages
@@ -412,7 +430,7 @@ func (r *SQLiteRepository) getCount(query string, args ...any) (int64, error) {
func (r *SQLiteRepository) scanMessage(scanner interface{ Scan(...any) error }) (*domainChatStorage.Message, error) {
message := &domainChatStorage.Message{}
err := scanner.Scan(
- &message.ID, &message.ChatJID, &message.Sender, &message.Content,
+ &message.ID, &message.ChatJID, &message.DeviceID, &message.Sender, &message.Content,
&message.Timestamp, &message.IsFromMe, &message.MediaType, &message.Filename,
&message.URL, &message.MediaKey, &message.FileSHA256, &message.FileEncSHA256,
&message.FileLength, &message.CreatedAt, &message.UpdatedAt,
@@ -424,7 +442,7 @@ func (r *SQLiteRepository) scanMessage(scanner interface{ Scan(...any) error })
func (r *SQLiteRepository) scanChat(scanner interface{ Scan(...any) error }) (*domainChatStorage.Chat, error) {
chat := &domainChatStorage.Chat{}
err := scanner.Scan(
- &chat.JID, &chat.Name, &chat.LastMessageTime, &chat.EphemeralExpiration,
+ &chat.DeviceID, &chat.JID, &chat.Name, &chat.LastMessageTime, &chat.EphemeralExpiration,
&chat.CreatedAt, &chat.UpdatedAt,
)
return chat, err
@@ -469,6 +487,117 @@ func (r *SQLiteRepository) TruncateAllChats() error {
return tx.Commit()
}
+// DeleteDeviceData deletes all chats and messages for a specific device_id.
+// Messages are deleted via foreign key cascade from chats.
+func (r *SQLiteRepository) DeleteDeviceData(deviceID string) error {
+ if deviceID == "" {
+ return fmt.Errorf("device id is required")
+ }
+
+ tx, err := r.db.Begin()
+ if err != nil {
+ return fmt.Errorf("failed to begin transaction: %w", err)
+ }
+ defer tx.Rollback()
+
+ // Delete messages first via direct device_id filter
+ if _, err := tx.Exec(`DELETE FROM messages WHERE device_id = ?`, deviceID); err != nil {
+ return fmt.Errorf("failed to delete device messages: %w", err)
+ }
+
+ if _, err := tx.Exec("DELETE FROM chats WHERE device_id = ?", deviceID); err != nil {
+ return fmt.Errorf("failed to delete device chats: %w", err)
+ }
+
+ return tx.Commit()
+}
+
+// SaveDeviceRecord upserts a device registration for persistence across restarts.
+func (r *SQLiteRepository) SaveDeviceRecord(record *domainChatStorage.DeviceRecord) error {
+ if record == nil || strings.TrimSpace(record.DeviceID) == "" {
+ return fmt.Errorf("device record with id is required")
+ }
+
+ now := time.Now()
+ if record.CreatedAt.IsZero() {
+ record.CreatedAt = now
+ }
+ record.UpdatedAt = now
+
+ // Try update first, then insert if no rows affected (cross-db compatible)
+ result, err := r.db.Exec(`
+ UPDATE devices SET display_name = ?, jid = ?, updated_at = ?
+ WHERE device_id = ?
+ `, record.DisplayName, record.JID, record.UpdatedAt, record.DeviceID)
+ if err != nil {
+ return err
+ }
+
+ rowsAffected, _ := result.RowsAffected()
+ if rowsAffected == 0 {
+ _, err = r.db.Exec(`
+ INSERT INTO devices (device_id, display_name, jid, created_at, updated_at)
+ VALUES (?, ?, ?, ?, ?)
+ `, record.DeviceID, record.DisplayName, record.JID, record.CreatedAt, record.UpdatedAt)
+ }
+ return err
+}
+
+// ListDeviceRecords returns all registered devices.
+func (r *SQLiteRepository) ListDeviceRecords() ([]*domainChatStorage.DeviceRecord, error) {
+ rows, err := r.db.Query(`
+ SELECT device_id, display_name, jid, created_at, updated_at
+ FROM devices
+ ORDER BY created_at ASC
+ `)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+
+ var records []*domainChatStorage.DeviceRecord
+ for rows.Next() {
+ var rec domainChatStorage.DeviceRecord
+ if err := rows.Scan(&rec.DeviceID, &rec.DisplayName, &rec.JID, &rec.CreatedAt, &rec.UpdatedAt); err != nil {
+ return nil, err
+ }
+ records = append(records, &rec)
+ }
+
+ return records, rows.Err()
+}
+
+// GetDeviceRecord fetches a device registration by id.
+func (r *SQLiteRepository) GetDeviceRecord(deviceID string) (*domainChatStorage.DeviceRecord, error) {
+ if strings.TrimSpace(deviceID) == "" {
+ return nil, fmt.Errorf("device id is required")
+ }
+
+ rec := &domainChatStorage.DeviceRecord{}
+ err := r.db.QueryRow(`
+ SELECT device_id, display_name, jid, created_at, updated_at
+ FROM devices
+ WHERE device_id = ?
+ LIMIT 1
+ `, deviceID).Scan(&rec.DeviceID, &rec.DisplayName, &rec.JID, &rec.CreatedAt, &rec.UpdatedAt)
+ if err == sql.ErrNoRows {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, err
+ }
+ return rec, nil
+}
+
+// DeleteDeviceRecord removes a device registration entry.
+func (r *SQLiteRepository) DeleteDeviceRecord(deviceID string) error {
+ if strings.TrimSpace(deviceID) == "" {
+ return fmt.Errorf("device id is required")
+ }
+ _, err := r.db.Exec("DELETE FROM devices WHERE device_id = ?", deviceID)
+ return err
+}
+
// GetChatNameWithPushName determines the appropriate name for a chat with pushname support
func (r *SQLiteRepository) GetChatNameWithPushName(jid types.JID, chatJID string, senderUser string, pushName string) string {
// First, check if chat already exists with a name
@@ -512,8 +641,18 @@ func (r *SQLiteRepository) CreateMessage(ctx context.Context, evt *events.Messag
return nil
}
- // Get WhatsApp client for LID resolution
- client := whatsapp.GetClient()
+ // Get WhatsApp client for LID resolution (device-scoped if present in context)
+ client := whatsapp.ClientFromContext(ctx)
+ deviceID := ""
+ if inst, ok := whatsapp.DeviceFromContext(ctx); ok && inst != nil {
+ deviceID = inst.JID()
+ if deviceID == "" {
+ deviceID = inst.ID()
+ }
+ }
+ if deviceID == "" && client != nil && client.Store != nil && client.Store.ID != nil {
+ deviceID = client.Store.ID.ToNonAD().String()
+ }
// Normalize chat and sender JIDs (convert @lid to @s.whatsapp.net)
normalizedChatJID := whatsapp.NormalizeJIDFromLID(ctx, evt.Info.Chat, client)
@@ -521,7 +660,7 @@ func (r *SQLiteRepository) CreateMessage(ctx context.Context, evt *events.Messag
chatJID := normalizedChatJID.String()
// Store the full sender JID (user@server) to ensure consistency between received and sent messages
- sender := normalizedSender.String()
+ sender := normalizedSender.ToNonAD().String()
// Get appropriate chat name using pushname if available
chatName := r.GetChatNameWithPushName(normalizedChatJID, chatJID, normalizedSender.User, evt.Info.PushName)
@@ -537,6 +676,7 @@ func (r *SQLiteRepository) CreateMessage(ctx context.Context, evt *events.Messag
// Create or update chat
chat := &domainChatStorage.Chat{
+ DeviceID: deviceID,
JID: chatJID,
Name: chatName,
LastMessageTime: evt.Info.Timestamp,
@@ -569,6 +709,7 @@ func (r *SQLiteRepository) CreateMessage(ctx context.Context, evt *events.Messag
message := &domainChatStorage.Message{
ID: evt.Info.ID,
ChatJID: chatJID,
+ DeviceID: deviceID,
Sender: sender,
Content: content,
Timestamp: evt.Info.Timestamp,
@@ -649,8 +790,18 @@ func (r *SQLiteRepository) StoreSentMessageWithContext(ctx context.Context, mess
return fmt.Errorf("invalid JID format: %w", err)
}
- // Get WhatsApp client for LID resolution
- client := whatsapp.GetClient()
+ // Get WhatsApp client for LID resolution (device-scoped if present in context)
+ client := whatsapp.ClientFromContext(ctx)
+ deviceID := ""
+ if inst, ok := whatsapp.DeviceFromContext(ctx); ok && inst != nil {
+ deviceID = inst.JID()
+ if deviceID == "" {
+ deviceID = inst.ID()
+ }
+ }
+ if deviceID == "" && client != nil && client.Store != nil && client.Store.ID != nil {
+ deviceID = client.Store.ID.ToNonAD().String()
+ }
// Normalize recipient JID (convert @lid to @s.whatsapp.net)
normalizedJID := whatsapp.NormalizeJIDFromLID(ctx, jid, client)
@@ -674,6 +825,7 @@ func (r *SQLiteRepository) StoreSentMessageWithContext(ctx context.Context, mess
// Store or update chat, preserving existing ephemeral_expiration
chat := &domainChatStorage.Chat{
+ DeviceID: deviceID,
JID: chatJID,
Name: chatName,
LastMessageTime: timestamp,
@@ -699,6 +851,7 @@ func (r *SQLiteRepository) StoreSentMessageWithContext(ctx context.Context, mess
message := &domainChatStorage.Message{
ID: messageID,
ChatJID: chatJID,
+ DeviceID: deviceID,
Sender: senderJID,
Content: content,
Timestamp: timestamp,
@@ -734,7 +887,7 @@ func (r *SQLiteRepository) getSchemaVersion() (int, error) {
// Create schema_info table if it doesn't exist
_, err := r.db.Exec(`
CREATE TABLE IF NOT EXISTS schema_info (
- version INTEGER PRIMARY KEY DEFAULT 0,
+ version INTEGER PRIMARY KEY,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`)
@@ -754,50 +907,47 @@ func (r *SQLiteRepository) getSchemaVersion() (int, error) {
// runMigration executes a migration
func (r *SQLiteRepository) runMigration(migration string, version int) error {
- tx, err := r.db.Begin()
- if err != nil {
+ // Execute migration (single statement)
+ if _, err := r.db.Exec(migration); err != nil {
return err
}
- defer tx.Rollback()
- // Execute migration
- if _, err := tx.Exec(migration); err != nil {
+ // Update schema version - delete then insert for cross-db compatibility
+ _, _ = r.db.Exec("DELETE FROM schema_info WHERE version = ?", version)
+ if _, err := r.db.Exec("INSERT INTO schema_info (version) VALUES (?)", version); err != nil {
return err
}
- // Update schema version
- if _, err := tx.Exec("INSERT OR REPLACE INTO schema_info (version) VALUES (?)", version); err != nil {
- return err
- }
-
- return tx.Commit()
+ return nil
}
// getMigrations returns all database migrations
+// Compatible with SQLite, MySQL, and PostgreSQL
func (r *SQLiteRepository) getMigrations() []string {
return []string{
- // Migration 1: Initial schema with only chats and messages tables
- `
- -- Create chats table
- CREATE TABLE IF NOT EXISTS chats (
- jid TEXT PRIMARY KEY,
- name TEXT NOT NULL,
+ // Migration 1: Create chats table
+ `CREATE TABLE IF NOT EXISTS chats (
+ jid VARCHAR(255) NOT NULL,
+ device_id VARCHAR(255) NOT NULL DEFAULT '',
+ name VARCHAR(255) NOT NULL,
last_message_time TIMESTAMP NOT NULL,
ephemeral_expiration INTEGER DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
- );
-
- -- Create messages table
- CREATE TABLE IF NOT EXISTS messages (
- id TEXT NOT NULL,
- chat_jid TEXT NOT NULL,
- sender TEXT NOT NULL,
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (jid, device_id)
+ )`,
+
+ // Migration 2: Create messages table
+ `CREATE TABLE IF NOT EXISTS messages (
+ id VARCHAR(255) NOT NULL,
+ chat_jid VARCHAR(255) NOT NULL,
+ device_id VARCHAR(255) NOT NULL DEFAULT '',
+ sender VARCHAR(255) NOT NULL,
content TEXT,
timestamp TIMESTAMP NOT NULL,
is_from_me BOOLEAN DEFAULT FALSE,
- media_type TEXT,
- filename TEXT,
+ media_type VARCHAR(50),
+ filename VARCHAR(255),
url TEXT,
media_key BLOB,
file_sha256 BLOB,
@@ -805,22 +955,43 @@ func (r *SQLiteRepository) getMigrations() []string {
file_length INTEGER DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- PRIMARY KEY (id, chat_jid),
- FOREIGN KEY (chat_jid) REFERENCES chats(jid) ON DELETE CASCADE
- );
-
- -- Create indexes for performance
- CREATE INDEX IF NOT EXISTS idx_messages_chat_jid ON messages(chat_jid);
- CREATE INDEX IF NOT EXISTS idx_messages_timestamp ON messages(timestamp);
- CREATE INDEX IF NOT EXISTS idx_messages_media_type ON messages(media_type);
- CREATE INDEX IF NOT EXISTS idx_messages_sender ON messages(sender);
- CREATE INDEX IF NOT EXISTS idx_chats_last_message ON chats(last_message_time);
- CREATE INDEX IF NOT EXISTS idx_chats_name ON chats(name);
- `,
-
- // Migration 2: Add index for message ID lookups (performance optimization)
- `
- CREATE INDEX IF NOT EXISTS idx_messages_id ON messages(id);
- `,
+ PRIMARY KEY (id, chat_jid, device_id)
+ )`,
+
+ // Migration 3: Create devices table
+ `CREATE TABLE IF NOT EXISTS devices (
+ device_id VARCHAR(255) PRIMARY KEY,
+ display_name VARCHAR(255) DEFAULT '',
+ jid VARCHAR(255) DEFAULT '',
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+ )`,
+
+ // Migration 4: Create indexes for messages
+ `CREATE INDEX IF NOT EXISTS idx_messages_chat_jid ON messages(chat_jid)`,
+
+ // Migration 5
+ `CREATE INDEX IF NOT EXISTS idx_messages_device ON messages(device_id)`,
+
+ // Migration 6
+ `CREATE INDEX IF NOT EXISTS idx_messages_timestamp ON messages(timestamp)`,
+
+ // Migration 7
+ `CREATE INDEX IF NOT EXISTS idx_messages_media_type ON messages(media_type)`,
+
+ // Migration 8
+ `CREATE INDEX IF NOT EXISTS idx_messages_sender ON messages(sender)`,
+
+ // Migration 9: Create indexes for chats
+ `CREATE INDEX IF NOT EXISTS idx_chats_last_message ON chats(last_message_time)`,
+
+ // Migration 10
+ `CREATE INDEX IF NOT EXISTS idx_chats_name ON chats(name)`,
+
+ // Migration 11
+ `CREATE INDEX IF NOT EXISTS idx_chats_device ON chats(device_id)`,
+
+ // Migration 12: Create index for devices
+ `CREATE INDEX IF NOT EXISTS idx_devices_created_at ON devices(created_at)`,
}
}
diff --git a/src/infrastructure/whatsapp/auto_reply.go b/src/infrastructure/whatsapp/auto_reply.go
new file mode 100644
index 00000000..76d0d633
--- /dev/null
+++ b/src/infrastructure/whatsapp/auto_reply.go
@@ -0,0 +1,125 @@
+package whatsapp
+
+import (
+ "context"
+ "strings"
+
+ "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"
+ "go.mau.fi/whatsmeow"
+ "go.mau.fi/whatsmeow/proto/waE2E"
+ "go.mau.fi/whatsmeow/types"
+ "go.mau.fi/whatsmeow/types/events"
+ "google.golang.org/protobuf/proto"
+)
+
+func handleAutoReply(ctx context.Context, evt *events.Message, chatStorageRepo domainChatStorage.IChatStorageRepository, client *whatsmeow.Client) {
+ if config.WhatsappAutoReplyMessage == "" {
+ return
+ }
+
+ if client == nil {
+ return
+ }
+
+ // Skip groups, broadcasts, and self messages
+ if utils.IsGroupJID(evt.Info.Chat.String()) || evt.Info.IsIncomingBroadcast() || evt.Info.IsFromMe {
+ return
+ }
+
+ // Only reply to direct 1:1 chats (e.g., *@s.whatsapp.net)
+ if evt.Info.Chat.Server != types.DefaultUserServer {
+ return
+ }
+
+ // Extra safety: skip any broadcast/status contexts
+ source := evt.Info.SourceString()
+ if strings.Contains(source, "broadcast") ||
+ strings.HasSuffix(evt.Info.Chat.String(), "@broadcast") ||
+ strings.HasPrefix(evt.Info.Chat.String(), "status@") {
+ return
+ }
+
+ // 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
+ }
+
+ // Check for genuine typed text on the unwrapped content
+ if conv := innerMsg.GetConversation(); conv != "" {
+ hasText = true
+ } else if ext := innerMsg.GetExtendedTextMessage(); ext != nil && ext.GetText() != "" {
+ hasText = true
+ } else if protoMsg := innerMsg.GetProtocolMessage(); protoMsg != nil {
+ if edited := protoMsg.GetEditedMessage(); edited != nil {
+ if ext := edited.GetExtendedTextMessage(); ext != nil && ext.GetText() != "" {
+ hasText = true
+ } else if conv := edited.GetConversation(); conv != "" {
+ hasText = true
+ }
+ }
+ }
+ if !hasText {
+ return
+ }
+
+ // Format recipient JID
+ recipientJID := utils.FormatJID(evt.Info.Sender.String())
+
+ // Send the auto-reply message
+ response, err := client.SendMessage(
+ ctx,
+ recipientJID,
+ &waE2E.Message{Conversation: proto.String(config.WhatsappAutoReplyMessage)},
+ )
+
+ if err != nil {
+ log.Errorf("Failed to send auto-reply message: %v", err)
+ return
+ }
+
+ // Store the auto-reply message in chat storage if send was successful
+ if chatStorageRepo != nil {
+ // Get our own JID as sender
+ senderJID := ""
+ if client.Store.ID != nil {
+ senderJID = client.Store.ID.String()
+ }
+
+ // Store the sent auto-reply message
+ if err := chatStorageRepo.StoreSentMessageWithContext(
+ ctx,
+ response.ID, // Message ID from WhatsApp response
+ senderJID, // Our JID as sender
+ recipientJID.String(), // Recipient JID
+ config.WhatsappAutoReplyMessage, // Auto-reply content
+ response.Timestamp, // Timestamp from response
+ ); err != nil {
+ // Log storage error but don't fail the auto-reply
+ log.Errorf("Failed to store auto-reply message in chat storage: %v", err)
+ } else {
+ log.Debugf("Auto-reply message %s stored successfully in chat storage", response.ID)
+ }
+ }
+}
diff --git a/src/infrastructure/whatsapp/chatstorage_wrapper.go b/src/infrastructure/whatsapp/chatstorage_wrapper.go
new file mode 100644
index 00000000..3c2112ec
--- /dev/null
+++ b/src/infrastructure/whatsapp/chatstorage_wrapper.go
@@ -0,0 +1,172 @@
+package whatsapp
+
+import (
+ "context"
+ "strings"
+ "time"
+
+ domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
+ "go.mau.fi/whatsmeow/types"
+ "go.mau.fi/whatsmeow/types/events"
+)
+
+// deviceChatStorage wraps a base repository and injects device_id into operations
+// to keep chat/message separation per device without importing chatstorage to avoid cycles.
+type deviceChatStorage struct {
+ deviceID string
+ base domainChatStorage.IChatStorageRepository
+}
+
+func newDeviceChatStorage(deviceID string, base domainChatStorage.IChatStorageRepository) domainChatStorage.IChatStorageRepository {
+ if base == nil {
+ return nil
+ }
+ return &deviceChatStorage{
+ deviceID: deviceID,
+ base: base,
+ }
+}
+
+func (r *deviceChatStorage) withDeviceChat(chat *domainChatStorage.Chat) *domainChatStorage.Chat {
+ if chat == nil {
+ return nil
+ }
+
+ // Prefer an explicit JID already set on the chat.
+ if chat.DeviceID != "" && strings.Contains(chat.DeviceID, "@") {
+ // Upgrade the wrapper device ID so future filters use the JID as well.
+ r.deviceID = chat.DeviceID
+ return chat
+ }
+
+ // If wrapper already holds a JID, apply it.
+ if strings.Contains(r.deviceID, "@") {
+ chat.DeviceID = r.deviceID
+ return chat
+ }
+
+ // Fallback to existing value or wrapper device ID (likely a placeholder).
+ if chat.DeviceID == "" {
+ chat.DeviceID = r.deviceID
+ }
+ return chat
+}
+
+func (r *deviceChatStorage) CreateMessage(ctx context.Context, evt *events.Message) error {
+ return r.base.CreateMessage(ctx, evt)
+}
+
+func (r *deviceChatStorage) StoreChat(chat *domainChatStorage.Chat) error {
+ return r.base.StoreChat(r.withDeviceChat(chat))
+}
+
+func (r *deviceChatStorage) GetChat(jid string) (*domainChatStorage.Chat, error) {
+ return r.base.GetChat(jid)
+}
+
+func (r *deviceChatStorage) GetChats(filter *domainChatStorage.ChatFilter) ([]*domainChatStorage.Chat, error) {
+ if filter != nil {
+ switch {
+ case filter.DeviceID != "" && strings.Contains(filter.DeviceID, "@"):
+ // Respect caller-provided JID and upgrade wrapper for future calls.
+ r.deviceID = filter.DeviceID
+ case strings.Contains(r.deviceID, "@"):
+ filter.DeviceID = r.deviceID
+ case filter.DeviceID == "":
+ // Fall back to wrapper device ID (likely placeholder) if caller didn't set one.
+ filter.DeviceID = r.deviceID
+ }
+ }
+ return r.base.GetChats(filter)
+}
+
+func (r *deviceChatStorage) DeleteChat(jid string) error {
+ return r.base.DeleteChat(jid)
+}
+
+func (r *deviceChatStorage) StoreMessage(message *domainChatStorage.Message) error {
+ return r.base.StoreMessage(message)
+}
+
+func (r *deviceChatStorage) StoreMessagesBatch(messages []*domainChatStorage.Message) error {
+ return r.base.StoreMessagesBatch(messages)
+}
+
+func (r *deviceChatStorage) GetMessageByID(id string) (*domainChatStorage.Message, error) {
+ return r.base.GetMessageByID(id)
+}
+
+func (r *deviceChatStorage) GetMessages(filter *domainChatStorage.MessageFilter) ([]*domainChatStorage.Message, error) {
+ return r.base.GetMessages(filter)
+}
+
+func (r *deviceChatStorage) SearchMessages(chatJID, searchText string, limit int) ([]*domainChatStorage.Message, error) {
+ return r.base.SearchMessages(chatJID, searchText, limit)
+}
+
+func (r *deviceChatStorage) DeleteMessage(id, chatJID string) error {
+ return r.base.DeleteMessage(id, chatJID)
+}
+
+func (r *deviceChatStorage) StoreSentMessageWithContext(ctx context.Context, messageID string, senderJID string, recipientJID string, content string, timestamp time.Time) error {
+ return r.base.StoreSentMessageWithContext(ctx, messageID, senderJID, recipientJID, content, timestamp)
+}
+
+func (r *deviceChatStorage) GetChatMessageCount(chatJID string) (int64, error) {
+ return r.base.GetChatMessageCount(chatJID)
+}
+
+func (r *deviceChatStorage) GetTotalMessageCount() (int64, error) {
+ return r.base.GetTotalMessageCount()
+}
+
+func (r *deviceChatStorage) GetTotalChatCount() (int64, error) {
+ return r.base.GetTotalChatCount()
+}
+
+func (r *deviceChatStorage) GetChatNameWithPushName(jid types.JID, chatJID string, senderUser string, pushName string) string {
+ return r.base.GetChatNameWithPushName(jid, chatJID, senderUser, pushName)
+}
+
+func (r *deviceChatStorage) GetStorageStatistics() (chatCount int64, messageCount int64, err error) {
+ return r.base.GetStorageStatistics()
+}
+
+func (r *deviceChatStorage) TruncateAllChats() error {
+ return r.base.TruncateAllChats()
+}
+
+func (r *deviceChatStorage) TruncateAllDataWithLogging(logPrefix string) error {
+ return r.base.TruncateAllDataWithLogging(logPrefix)
+}
+
+func (r *deviceChatStorage) InitializeSchema() error {
+ return r.base.InitializeSchema()
+}
+
+func (r *deviceChatStorage) DeleteDeviceData(deviceID string) error {
+ if r.base == nil {
+ return nil
+ }
+ target := deviceID
+ if target == "" {
+ target = r.deviceID
+ }
+ return r.base.DeleteDeviceData(target)
+}
+
+func (r *deviceChatStorage) SaveDeviceRecord(record *domainChatStorage.DeviceRecord) error {
+ return r.base.SaveDeviceRecord(record)
+}
+
+func (r *deviceChatStorage) ListDeviceRecords() ([]*domainChatStorage.DeviceRecord, error) {
+ return r.base.ListDeviceRecords()
+}
+
+func (r *deviceChatStorage) GetDeviceRecord(deviceID string) (*domainChatStorage.DeviceRecord, error) {
+ return r.base.GetDeviceRecord(deviceID)
+}
+
+func (r *deviceChatStorage) DeleteDeviceRecord(deviceID string) error {
+ return r.base.DeleteDeviceRecord(deviceID)
+}
diff --git a/src/infrastructure/whatsapp/cleanup.go b/src/infrastructure/whatsapp/cleanup.go
new file mode 100644
index 00000000..93cc852d
--- /dev/null
+++ b/src/infrastructure/whatsapp/cleanup.go
@@ -0,0 +1,261 @@
+package whatsapp
+
+import (
+ "context"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/config"
+ domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
+ "github.com/sirupsen/logrus"
+ "go.mau.fi/whatsmeow"
+ "go.mau.fi/whatsmeow/store/sqlstore"
+)
+
+// CleanupDatabase removes the database file (SQLite) or deletes all devices (PostgreSQL) to prevent foreign key constraint issues
+func CleanupDatabase() error {
+ // Check if using PostgreSQL - for PostgreSQL we can use RLock since we're not closing connections
+ if strings.HasPrefix(config.DBURI, "postgres:") {
+ globalStateMu.RLock()
+ currentDB := db
+ currentKeysDB := keysDB
+ globalStateMu.RUnlock()
+
+ logrus.Info("[CLEANUP] PostgreSQL detected - deleting all devices from database")
+
+ // Check if database is initialized
+ if currentDB == nil {
+ logrus.Warn("[CLEANUP] Database is nil, skipping device deletion")
+ return nil
+ }
+
+ ctx := context.Background()
+
+ // Get all devices
+ devices, err := currentDB.GetAllDevices(ctx)
+ if err != nil {
+ logrus.Errorf("[CLEANUP] Error getting devices: %v", err)
+ return fmt.Errorf("failed to get devices: %v", err)
+ }
+
+ logrus.Infof("[CLEANUP] Found %d devices to delete", len(devices))
+
+ // Delete each device (this will cascade delete related records like identity keys, sessions, etc.)
+ for _, device := range devices {
+ logrus.Infof("[CLEANUP] Deleting device: %s", device.ID)
+ if err := currentDB.DeleteDevice(ctx, device); err != nil {
+ logrus.Errorf("[CLEANUP] Error deleting device %s: %v", device.ID, err)
+ return fmt.Errorf("failed to delete device %s: %v", device.ID, err)
+ }
+ }
+
+ // Also clean up keysDB if it exists and is separate
+ if currentKeysDB != nil && currentKeysDB != currentDB {
+ keysDevices, err := currentKeysDB.GetAllDevices(ctx)
+ if err != nil {
+ logrus.Errorf("[CLEANUP] Error getting devices from keysDB: %v", err)
+ return fmt.Errorf("failed to get devices from keysDB: %v", err)
+ }
+
+ logrus.Infof("[CLEANUP] Found %d devices in keysDB to delete", len(keysDevices))
+
+ for _, device := range keysDevices {
+ logrus.Infof("[CLEANUP] Deleting device from keysDB: %s", device.ID)
+ if err := currentKeysDB.DeleteDevice(ctx, device); err != nil {
+ logrus.Errorf("[CLEANUP] Error deleting device %s from keysDB: %v", device.ID, err)
+ return fmt.Errorf("failed to delete device %s from keysDB: %v", device.ID, err)
+ }
+ }
+ }
+
+ logrus.Info("[CLEANUP] All devices deleted successfully from PostgreSQL")
+ return nil
+ }
+
+ // SQLite: Hold write lock for entire cleanup to prevent race conditions
+ // Other goroutines must not access db/keysDB while we're closing and removing files
+ globalStateMu.Lock()
+ defer globalStateMu.Unlock()
+
+ logrus.Info("[CLEANUP] SQLite detected - closing database connections before file removal")
+
+ // Store references and clear globals immediately to prevent use-after-close
+ currentDB := db
+ currentKeysDB := keysDB
+ db = nil
+ keysDB = nil
+ cli = nil // Also clear client since it depends on db
+
+ // Close the main database connection
+ if currentDB != nil {
+ logrus.Info("[CLEANUP] Closing main database connection")
+ if err := currentDB.Close(); err != nil {
+ logrus.Errorf("[CLEANUP] Error closing main database: %v", err)
+ return fmt.Errorf("failed to close main database: %v", err)
+ }
+ logrus.Info("[CLEANUP] Main database connection closed successfully")
+ }
+
+ // Close keysDB if it exists and is separate from main db
+ if currentKeysDB != nil && currentKeysDB != currentDB {
+ logrus.Info("[CLEANUP] Closing keysDB database connection")
+ if err := currentKeysDB.Close(); err != nil {
+ logrus.Errorf("[CLEANUP] Error closing keysDB: %v", err)
+ return fmt.Errorf("failed to close keysDB: %v", err)
+ }
+ logrus.Info("[CLEANUP] KeysDB connection closed successfully")
+
+ // Remove keysDB file if it's also SQLite
+ if config.DBKeysURI != "" && strings.HasPrefix(config.DBKeysURI, "file:") {
+ keysDBPath := strings.TrimPrefix(config.DBKeysURI, "file:")
+ if strings.Contains(keysDBPath, "?") {
+ keysDBPath = strings.Split(keysDBPath, "?")[0]
+ }
+
+ logrus.Infof("[CLEANUP] Removing keysDB file: %s", keysDBPath)
+ if err := os.Remove(keysDBPath); err != nil {
+ if !os.IsNotExist(err) {
+ logrus.Errorf("[CLEANUP] Error removing keysDB file: %v", err)
+ return fmt.Errorf("failed to remove keysDB file: %v", err)
+ } else {
+ logrus.Info("[CLEANUP] KeysDB file already removed")
+ }
+ } else {
+ logrus.Info("[CLEANUP] KeysDB file removed successfully")
+ }
+ }
+ }
+
+ // Now remove the main database file
+ dbPath := strings.TrimPrefix(config.DBURI, "file:")
+ if strings.Contains(dbPath, "?") {
+ dbPath = strings.Split(dbPath, "?")[0]
+ }
+
+ logrus.Infof("[CLEANUP] Removing main database file: %s", dbPath)
+ if err := os.Remove(dbPath); err != nil {
+ if !os.IsNotExist(err) {
+ logrus.Errorf("[CLEANUP] Error removing database file: %v", err)
+ return err
+ } else {
+ logrus.Info("[CLEANUP] Database file already removed")
+ }
+ } else {
+ logrus.Info("[CLEANUP] Database file removed successfully")
+ }
+ return nil
+}
+
+// CleanupTemporaryFiles removes history files, QR images, and send items
+func CleanupTemporaryFiles() error {
+ // Clean up history files
+ if files, err := filepath.Glob(fmt.Sprintf("./%s/history-*", config.PathStorages)); err == nil {
+ for _, f := range files {
+ if err := os.Remove(f); err != nil {
+ logrus.Errorf("[CLEANUP] Error removing history file %s: %v", f, err)
+ return err
+ }
+ }
+ logrus.Info("[CLEANUP] History files cleaned up")
+ }
+
+ // Clean up QR images
+ if qrImages, err := filepath.Glob(fmt.Sprintf("./%s/scan-*", config.PathQrCode)); err == nil {
+ for _, f := range qrImages {
+ if err := os.Remove(f); err != nil {
+ logrus.Errorf("[CLEANUP] Error removing QR image %s: %v", f, err)
+ return err
+ }
+ }
+ logrus.Info("[CLEANUP] QR images cleaned up")
+ }
+
+ // Clean up send items
+ if qrItems, err := filepath.Glob(fmt.Sprintf("./%s/*", config.PathSendItems)); err == nil {
+ for _, f := range qrItems {
+ if !strings.Contains(f, ".gitignore") {
+ if err := os.Remove(f); err != nil {
+ logrus.Errorf("[CLEANUP] Error removing send item %s: %v", f, err)
+ return err
+ }
+ }
+ }
+ logrus.Info("[CLEANUP] Send items cleaned up")
+ }
+
+ return nil
+}
+
+// ReinitializeWhatsAppComponents reinitializes database and client components
+func ReinitializeWhatsAppComponents(ctx context.Context, chatStorageRepo domainChatStorage.IChatStorageRepository) (*sqlstore.Container, *whatsmeow.Client, error) {
+ logrus.Info("[CLEANUP] Reinitializing database and client...")
+
+ newDB := InitWaDB(ctx, config.DBURI)
+ var newKeysDB *sqlstore.Container
+ if config.DBKeysURI != "" {
+ newKeysDB = InitWaDB(ctx, config.DBKeysURI)
+ }
+ newCli := InitWaCLI(ctx, newDB, newKeysDB, chatStorageRepo)
+
+ logrus.Info("[CLEANUP] Database and client reinitialized successfully")
+
+ return newDB, newCli, nil
+}
+
+// PerformCompleteCleanup performs all cleanup operations in the correct order
+func PerformCompleteCleanup(ctx context.Context, logPrefix string, chatStorageRepo domainChatStorage.IChatStorageRepository) (*sqlstore.Container, *whatsmeow.Client, error) {
+ logrus.Infof("[%s] Starting complete cleanup process...", logPrefix)
+
+ // Disconnect current client if it exists
+ if current := GetClient(); current != nil {
+ current.Disconnect()
+ logrus.Infof("[%s] Client disconnected", logPrefix)
+ }
+
+ // Truncate all chatstorage data before other cleanup
+ if chatStorageRepo != nil {
+ logrus.Infof("[%s] Truncating chatstorage data...", logPrefix)
+ if err := chatStorageRepo.TruncateAllDataWithLogging(logPrefix); err != nil {
+ logrus.Errorf("[%s] Failed to truncate chatstorage data: %v", logPrefix, err)
+ // Continue with cleanup even if chatstorage truncation fails
+ }
+ }
+
+ // Clean up database
+ if err := CleanupDatabase(); err != nil {
+ return nil, nil, fmt.Errorf("database cleanup failed: %v", err)
+ }
+
+ // Reinitialize components
+ newDB, newCli, err := ReinitializeWhatsAppComponents(ctx, chatStorageRepo)
+ if err != nil {
+ return nil, nil, fmt.Errorf("reinitialization failed: %v", err)
+ }
+
+ // Clean up temporary files
+ if err := CleanupTemporaryFiles(); err != nil {
+ logrus.Errorf("[%s] Temporary file cleanup failed (non-critical): %v", logPrefix, err)
+ // Don't return error for file cleanup as it's non-critical
+ }
+
+ logrus.Infof("[%s] Complete cleanup process finished successfully", logPrefix)
+ logrus.Infof("[%s] Application is ready for next login without restart", logPrefix)
+
+ return newDB, newCli, nil
+}
+
+// PerformCleanupAndUpdateGlobals is a convenience function that performs cleanup
+// and ensures global client synchronization
+func PerformCleanupAndUpdateGlobals(ctx context.Context, logPrefix string, chatStorageRepo domainChatStorage.IChatStorageRepository) (*sqlstore.Container, *whatsmeow.Client, error) {
+ newDB, newCli, err := PerformCompleteCleanup(ctx, logPrefix, chatStorageRepo)
+ if err != nil {
+ return nil, nil, err
+ }
+
+ // Ensure global client is properly synchronized
+ UpdateGlobalClient(newCli, newDB)
+
+ return newDB, newCli, nil
+}
diff --git a/src/infrastructure/whatsapp/client_lifecycle.go b/src/infrastructure/whatsapp/client_lifecycle.go
new file mode 100644
index 00000000..2b71d497
--- /dev/null
+++ b/src/infrastructure/whatsapp/client_lifecycle.go
@@ -0,0 +1,55 @@
+package whatsapp
+
+import (
+ domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
+ "go.mau.fi/whatsmeow"
+ "go.mau.fi/whatsmeow/store/sqlstore"
+)
+
+// UpdateGlobalClient updates the global cli variable with a new client instance
+// This is needed when reinitializing the client after logout to ensure all
+// infrastructure code uses the new client instance
+func UpdateGlobalClient(newCli *whatsmeow.Client, newDB *sqlstore.Container) {
+ globalStateMu.Lock()
+ cli = newCli
+ db = newDB
+ globalStateMu.Unlock()
+ log.Infof("Global WhatsApp client updated successfully")
+}
+
+// GetClient returns the current global client instance (alias for GetGlobalClient)
+func GetClient() *whatsmeow.Client {
+ globalStateMu.RLock()
+ defer globalStateMu.RUnlock()
+ return cli
+}
+
+// Get DB instance
+func GetDB() *sqlstore.Container {
+ globalStateMu.RLock()
+ defer globalStateMu.RUnlock()
+ return db
+}
+
+func getStoreContainers() (*sqlstore.Container, *sqlstore.Container) {
+ globalStateMu.RLock()
+ defer globalStateMu.RUnlock()
+ return db, keysDB
+}
+
+// InitializeDeviceManager creates the global DeviceManager if it doesn't exist.
+func InitializeDeviceManager(storeContainer, keysStoreContainer *sqlstore.Container, chatStorageRepo domainChatStorage.IChatStorageRepository) *DeviceManager {
+ globalStateMu.Lock()
+ defer globalStateMu.Unlock()
+ if deviceManager == nil {
+ deviceManager = NewDeviceManager(storeContainer, keysStoreContainer, chatStorageRepo)
+ }
+ return deviceManager
+}
+
+// GetDeviceManager returns the global DeviceManager.
+func GetDeviceManager() *DeviceManager {
+ globalStateMu.RLock()
+ defer globalStateMu.RUnlock()
+ return deviceManager
+}
diff --git a/src/infrastructure/whatsapp/context_device.go b/src/infrastructure/whatsapp/context_device.go
new file mode 100644
index 00000000..b238fa38
--- /dev/null
+++ b/src/infrastructure/whatsapp/context_device.go
@@ -0,0 +1,42 @@
+package whatsapp
+
+import (
+ "context"
+
+ "go.mau.fi/whatsmeow"
+)
+
+type deviceContextKey struct{}
+
+// ContextWithDevice stores a device instance into the provided context for per-request scoping.
+func ContextWithDevice(ctx context.Context, device *DeviceInstance) context.Context {
+ if ctx == nil {
+ return context.Background()
+ }
+ return context.WithValue(ctx, deviceContextKey{}, device)
+}
+
+// DeviceFromContext retrieves a device instance from context if present.
+func DeviceFromContext(ctx context.Context) (*DeviceInstance, bool) {
+ if ctx == nil {
+ return nil, false
+ }
+ if value := ctx.Value(deviceContextKey{}); value != nil {
+ if inst, ok := value.(*DeviceInstance); ok {
+ return inst, true
+ }
+ }
+ return nil, false
+}
+
+// ClientFromContext returns the client stored in the device context.
+// If a device was explicitly set in context but has no client (not logged in), returns nil.
+// Only falls back to global client when no device was set in context (backward compatibility).
+func ClientFromContext(ctx context.Context) *whatsmeow.Client {
+ if inst, ok := DeviceFromContext(ctx); ok && inst != nil {
+ // Device was explicitly set - return its client (may be nil if not logged in)
+ return inst.GetClient()
+ }
+ // No device in context - fall back to global client for backward compatibility
+ return GetClient()
+}
diff --git a/src/infrastructure/whatsapp/database.go b/src/infrastructure/whatsapp/database.go
new file mode 100644
index 00000000..77063c78
--- /dev/null
+++ b/src/infrastructure/whatsapp/database.go
@@ -0,0 +1,56 @@
+package whatsapp
+
+import (
+ "context"
+ "fmt"
+ "strings"
+
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/config"
+ pkgError "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/error"
+ "go.mau.fi/whatsmeow/store/sqlstore"
+ waLog "go.mau.fi/whatsmeow/util/log"
+)
+
+// InitWaDB initializes the WhatsApp database connection
+func InitWaDB(ctx context.Context, DBURI string) *sqlstore.Container {
+ log = waLog.Stdout("Main", config.WhatsappLogLevel, true)
+ dbLog := waLog.Stdout("Database", config.WhatsappLogLevel, true)
+
+ storeContainer, err := initDatabase(ctx, dbLog, DBURI)
+ if err != nil {
+ log.Errorf("Database initialization error: %v", err)
+ panic(pkgError.InternalServerError(fmt.Sprintf("Database initialization error: %v", err)))
+ }
+
+ return storeContainer
+}
+
+// initDatabase creates and returns a database store container based on the configured URI
+func initDatabase(ctx context.Context, dbLog waLog.Logger, DBURI string) (*sqlstore.Container, error) {
+ if strings.HasPrefix(DBURI, "file:") {
+ return sqlstore.New(ctx, "sqlite3", DBURI, dbLog)
+ } else if strings.HasPrefix(DBURI, "postgres:") {
+ return sqlstore.New(ctx, "postgres", DBURI, dbLog)
+ }
+
+ return nil, fmt.Errorf("unknown database type: %s. Currently only sqlite3(file:) and postgres are supported", DBURI)
+}
+
+// GetConnectionStatus returns the current connection status of the global client
+func GetConnectionStatus() (isConnected bool, isLoggedIn bool, deviceID string) {
+ globalStateMu.RLock()
+ currentClient := cli
+ globalStateMu.RUnlock()
+ if currentClient == nil {
+ return false, false, ""
+ }
+
+ isConnected = currentClient.IsConnected()
+ isLoggedIn = currentClient.IsLoggedIn()
+
+ if currentClient.Store != nil && currentClient.Store.ID != nil {
+ deviceID = currentClient.Store.ID.String()
+ }
+
+ return isConnected, isLoggedIn, deviceID
+}
diff --git a/src/infrastructure/whatsapp/device_instance.go b/src/infrastructure/whatsapp/device_instance.go
new file mode 100644
index 00000000..29545dcc
--- /dev/null
+++ b/src/infrastructure/whatsapp/device_instance.go
@@ -0,0 +1,155 @@
+package whatsapp
+
+import (
+ "sync"
+ "time"
+
+ domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
+ domainDevice "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/device"
+ "go.mau.fi/whatsmeow"
+)
+
+// DeviceInstance bundles a WhatsApp client with device metadata and scoped storage.
+type DeviceInstance struct {
+ mu sync.RWMutex
+ id string
+ client *whatsmeow.Client
+ chatStorageRepo domainChatStorage.IChatStorageRepository
+ state domainDevice.DeviceState
+ displayName string
+ phoneNumber string
+ jid string
+ createdAt time.Time
+}
+
+func NewDeviceInstance(deviceID string, client *whatsmeow.Client, chatStorageRepo domainChatStorage.IChatStorageRepository) *DeviceInstance {
+ jid := ""
+ display := ""
+ if client != nil && client.Store != nil && client.Store.ID != nil {
+ jid = client.Store.ID.ToNonAD().String()
+ display = client.Store.PushName
+ }
+
+ return &DeviceInstance{
+ id: deviceID,
+ client: client,
+ chatStorageRepo: chatStorageRepo,
+ state: domainDevice.DeviceStateDisconnected,
+ displayName: display,
+ jid: jid,
+ createdAt: time.Now(),
+ }
+}
+
+func (d *DeviceInstance) ID() string {
+ return d.id
+}
+
+func (d *DeviceInstance) GetClient() *whatsmeow.Client {
+ d.mu.RLock()
+ defer d.mu.RUnlock()
+ return d.client
+}
+
+func (d *DeviceInstance) GetChatStorage() domainChatStorage.IChatStorageRepository {
+ d.mu.RLock()
+ defer d.mu.RUnlock()
+ return d.chatStorageRepo
+}
+
+func (d *DeviceInstance) SetState(state domainDevice.DeviceState) {
+ d.mu.Lock()
+ d.state = state
+ d.mu.Unlock()
+}
+
+func (d *DeviceInstance) State() domainDevice.DeviceState {
+ d.mu.RLock()
+ defer d.mu.RUnlock()
+ return d.state
+}
+
+func (d *DeviceInstance) DisplayName() string {
+ d.mu.RLock()
+ defer d.mu.RUnlock()
+ return d.displayName
+}
+
+func (d *DeviceInstance) PhoneNumber() string {
+ d.mu.RLock()
+ defer d.mu.RUnlock()
+ return d.phoneNumber
+}
+
+func (d *DeviceInstance) JID() string {
+ d.mu.RLock()
+ defer d.mu.RUnlock()
+ return d.jid
+}
+
+func (d *DeviceInstance) CreatedAt() time.Time {
+ return d.createdAt
+}
+
+// SetClient attaches a WhatsApp client to this instance and updates metadata.
+func (d *DeviceInstance) SetClient(client *whatsmeow.Client) {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ d.client = client
+ d.refreshIdentityLocked()
+ d.state = domainDevice.DeviceStateDisconnected
+}
+
+// SetChatStorage swaps the chat storage repository for this device.
+func (d *DeviceInstance) SetChatStorage(repo domainChatStorage.IChatStorageRepository) {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ d.chatStorageRepo = repo
+}
+
+// IsConnected returns the live connection flag if a client exists.
+func (d *DeviceInstance) IsConnected() bool {
+ d.mu.RLock()
+ client := d.client
+ d.mu.RUnlock()
+ if client == nil {
+ return false
+ }
+ return client.IsConnected()
+}
+
+// IsLoggedIn returns the login status if a client exists.
+func (d *DeviceInstance) IsLoggedIn() bool {
+ d.mu.RLock()
+ client := d.client
+ d.mu.RUnlock()
+ if client == nil {
+ return false
+ }
+ return client.IsLoggedIn()
+}
+
+// UpdateStateFromClient refreshes the snapshot state based on the client flags.
+func (d *DeviceInstance) UpdateStateFromClient() domainDevice.DeviceState {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+
+ switch {
+ case d.client != nil && d.client.IsLoggedIn():
+ d.state = domainDevice.DeviceStateLoggedIn
+ case d.client != nil && d.client.IsConnected():
+ d.state = domainDevice.DeviceStateConnected
+ default:
+ d.state = domainDevice.DeviceStateDisconnected
+ }
+
+ d.refreshIdentityLocked()
+ return d.state
+}
+
+func (d *DeviceInstance) refreshIdentityLocked() {
+ if d.client != nil && d.client.Store != nil && d.client.Store.ID != nil {
+ d.jid = d.client.Store.ID.ToNonAD().String()
+ d.displayName = d.client.Store.PushName
+ }
+}
diff --git a/src/infrastructure/whatsapp/device_manager.go b/src/infrastructure/whatsapp/device_manager.go
new file mode 100644
index 00000000..dfc9c145
--- /dev/null
+++ b/src/infrastructure/whatsapp/device_manager.go
@@ -0,0 +1,587 @@
+package whatsapp
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/config"
+ domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
+ domainDevice "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/device"
+ fiberUtils "github.com/gofiber/fiber/v2/utils"
+ "github.com/sirupsen/logrus"
+ "go.mau.fi/whatsmeow"
+ "go.mau.fi/whatsmeow/store"
+ "go.mau.fi/whatsmeow/store/sqlstore"
+ "go.mau.fi/whatsmeow/types"
+ waLog "go.mau.fi/whatsmeow/util/log"
+)
+
+// DeviceManager keeps a registry of active device instances.
+type DeviceManager struct {
+ mu sync.RWMutex
+ devices map[string]*DeviceInstance
+ store *sqlstore.Container
+ keys *sqlstore.Container
+ storage domainChatStorage.IChatStorageRepository
+ initted bool
+ initOnce sync.Once
+}
+
+func NewDeviceManager(store *sqlstore.Container, keys *sqlstore.Container, chatStorageRepo domainChatStorage.IChatStorageRepository) *DeviceManager {
+ return &DeviceManager{
+ devices: make(map[string]*DeviceInstance),
+ store: store,
+ keys: keys,
+ storage: chatStorageRepo,
+ }
+}
+
+func (m *DeviceManager) AddDevice(instance *DeviceInstance) {
+ if instance == nil || instance.ID() == "" {
+ return
+ }
+
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ m.devices[instance.ID()] = instance
+
+ // Persist registry entry if available
+ if m.storage != nil {
+ _ = m.storage.SaveDeviceRecord(&domainChatStorage.DeviceRecord{
+ DeviceID: instance.ID(),
+ DisplayName: instance.DisplayName(),
+ JID: instance.JID(),
+ CreatedAt: instance.CreatedAt(),
+ UpdatedAt: time.Now(),
+ })
+ }
+}
+
+func (m *DeviceManager) GetDevice(id string) (*DeviceInstance, bool) {
+ m.mu.RLock()
+ defer m.mu.RUnlock()
+ instance, ok := m.devices[id]
+ return instance, ok
+}
+
+// DefaultDevice returns the only registered device when running in single-device mode.
+func (m *DeviceManager) DefaultDevice() *DeviceInstance {
+ if m == nil {
+ return nil
+ }
+
+ m.mu.RLock()
+ defer m.mu.RUnlock()
+
+ if len(m.devices) != 1 {
+ return nil
+ }
+
+ for _, inst := range m.devices {
+ return inst
+ }
+
+ return nil
+}
+
+// ResolveDevice attempts to locate a device by ID or falls back to the default/only device.
+// It returns the resolved instance, the ID used, or an error when no suitable device is found.
+func (m *DeviceManager) ResolveDevice(deviceID string) (*DeviceInstance, string, error) {
+ if m == nil {
+ return nil, "", fmt.Errorf("device manager not initialized")
+ }
+
+ trimmedID := strings.TrimSpace(deviceID)
+ if trimmedID != "" {
+ if inst, ok := m.GetDevice(trimmedID); ok && inst != nil {
+ return inst, trimmedID, nil
+ }
+ return nil, trimmedID, fmt.Errorf("device %s not found", trimmedID)
+ }
+
+ if inst := m.DefaultDevice(); inst != nil {
+ return inst, inst.ID(), nil
+ }
+
+ return nil, "", fmt.Errorf("device id is required")
+}
+
+func (m *DeviceManager) RemoveDevice(id string) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ delete(m.devices, id)
+
+ if m.storage != nil && strings.TrimSpace(id) != "" {
+ _ = m.storage.DeleteDeviceRecord(id)
+ }
+}
+
+// PurgeDevice cleanly logs out a device, removes its persisted records (store/keys),
+// deletes its chatstorage data, and removes it from the in-memory registry.
+func (m *DeviceManager) PurgeDevice(ctx context.Context, deviceID string) error {
+ if deviceID == "" {
+ return fmt.Errorf("device id is required")
+ }
+
+ var firstErr error
+ recordErr := func(err error) {
+ if err != nil {
+ firstErr = errors.Join(firstErr, err)
+ }
+ }
+
+ // Attempt logout/disconnect if a client exists
+ if inst, ok := m.GetDevice(deviceID); ok && inst != nil {
+ if cli := inst.GetClient(); cli != nil {
+ if err := cli.Logout(ctx); err != nil {
+ logrus.WithError(err).Warnf("[DEVICE_MANAGER] logout failed for device %s", deviceID)
+ recordErr(err)
+ }
+ cli.Disconnect()
+ }
+ }
+
+ // Delete chatstorage data for this device
+ if m.storage != nil {
+ if err := m.storage.DeleteDeviceData(deviceID); err != nil {
+ logrus.WithError(err).Warnf("[DEVICE_MANAGER] failed to delete chatstorage for device %s", deviceID)
+ recordErr(err)
+ }
+ }
+
+ // Remove device records from primary store
+ if m.store != nil {
+ if devices, err := m.store.GetAllDevices(ctx); err != nil {
+ logrus.WithError(err).Warn("[DEVICE_MANAGER] failed to enumerate devices for purge")
+ recordErr(err)
+ } else {
+ for _, dev := range devices {
+ if dev != nil && dev.ID != nil && dev.ID.String() == deviceID {
+ if err := m.store.DeleteDevice(ctx, dev); err != nil {
+ logrus.WithError(err).Warnf("[DEVICE_MANAGER] failed to delete device %s from store", deviceID)
+ recordErr(err)
+ }
+ break
+ }
+ }
+ }
+ }
+
+ // Remove device records from keys store if separate
+ if m.keys != nil && m.keys != m.store {
+ if devices, err := m.keys.GetAllDevices(ctx); err != nil {
+ logrus.WithError(err).Warn("[DEVICE_MANAGER] failed to enumerate keys devices for purge")
+ recordErr(err)
+ } else {
+ for _, dev := range devices {
+ if dev != nil && dev.ID != nil && dev.ID.String() == deviceID {
+ if err := m.keys.DeleteDevice(ctx, dev); err != nil {
+ logrus.WithError(err).Warnf("[DEVICE_MANAGER] failed to delete device %s from keys store", deviceID)
+ recordErr(err)
+ }
+ break
+ }
+ }
+ }
+ }
+
+ // Remove from registry last
+ m.RemoveDevice(deviceID)
+ return firstErr
+}
+
+// CreateDevice registers a new device placeholder so routes can be scoped strictly by device_id.
+func (m *DeviceManager) CreateDevice(ctx context.Context, requestedID string) (*DeviceInstance, error) {
+ if m == nil {
+ return nil, fmt.Errorf("device manager not initialized")
+ }
+
+ id := requestedID
+ if id == "" {
+ id = fiberUtils.UUID()
+ }
+
+ m.mu.Lock()
+ defer m.mu.Unlock()
+
+ if _, exists := m.devices[id]; exists {
+ return nil, fmt.Errorf("device %s already exists", id)
+ }
+
+ instance := NewDeviceInstance(id, nil, newDeviceChatStorage(id, m.storage))
+ m.devices[id] = instance
+
+ if m.storage != nil {
+ if err := m.storage.SaveDeviceRecord(&domainChatStorage.DeviceRecord{
+ DeviceID: id,
+ DisplayName: instance.DisplayName(),
+ JID: instance.JID(),
+ CreatedAt: instance.CreatedAt(),
+ UpdatedAt: instance.CreatedAt(),
+ }); err != nil {
+ logrus.WithError(err).Warnf("[DEVICE_MANAGER] failed to persist device %s", id)
+ }
+ }
+
+ logrus.WithContext(ctx).Infof("[DEVICE_MANAGER] created device placeholder %s", id)
+ return instance, nil
+}
+
+func (m *DeviceManager) ListDevices() []*DeviceInstance {
+ m.mu.RLock()
+ defer m.mu.RUnlock()
+
+ var result []*DeviceInstance
+ for _, instance := range m.devices {
+ result = append(result, instance)
+ }
+ return result
+}
+
+// LoadExistingDevices registers existing device records in the store container without connecting them.
+// This keeps the registry aware of all device IDs even before their clients are initialized.
+func (m *DeviceManager) LoadExistingDevices(ctx context.Context) error {
+ if m == nil || m.store == nil {
+ return fmt.Errorf("device manager not initialized")
+ }
+
+ m.initOnce.Do(func() {
+ m.initted = true
+ })
+
+ // Load from persisted registry
+ if m.storage != nil {
+ records, err := m.storage.ListDeviceRecords()
+ if err != nil {
+ logrus.WithError(err).Warn("[DEVICE_MANAGER] failed to load device registry")
+ } else {
+ logrus.Infof("[DEVICE_MANAGER] discovered %d device records in registry", len(records))
+ m.loadFromRegistry(records)
+ }
+ }
+
+ // Load from WhatsMeow store
+ devices, err := m.store.GetAllDevices(ctx)
+ if err != nil {
+ return err
+ }
+
+ logrus.Infof("[DEVICE_MANAGER] discovered %d device records in store", len(devices))
+ for _, dev := range devices {
+ if dev == nil || dev.ID == nil {
+ continue
+ }
+ // Use NonAD JID to match with devices table which stores NonAD format
+ jid := dev.ID.ToNonAD().String()
+
+ // Check if device already exists by ID or JID
+ m.mu.RLock()
+ _, existsByID := m.devices[jid]
+ var matchedDevice *DeviceInstance
+ var orphanDevice *DeviceInstance
+ for _, inst := range m.devices {
+ if inst.JID() == jid {
+ matchedDevice = inst
+ break
+ }
+ if inst.JID() == "" && orphanDevice == nil {
+ orphanDevice = inst
+ }
+ }
+ m.mu.RUnlock()
+
+ // Skip if already matched
+ if existsByID || matchedDevice != nil {
+ continue
+ }
+
+ // Match orphaned device with this JID
+ if orphanDevice != nil {
+ logrus.Infof("[DEVICE_MANAGER] matching orphaned device %s with JID %s", orphanDevice.ID(), jid)
+ orphanDevice.mu.Lock()
+ orphanDevice.jid = jid
+ orphanDevice.mu.Unlock()
+ if m.storage != nil {
+ _ = m.storage.SaveDeviceRecord(&domainChatStorage.DeviceRecord{
+ DeviceID: orphanDevice.ID(),
+ JID: jid,
+ })
+ }
+ continue
+ }
+
+ // Create new device instance
+ instance := NewDeviceInstance(jid, nil, newDeviceChatStorage(jid, m.storage))
+ instance.SetState(domainDevice.DeviceStateDisconnected)
+ m.AddDevice(instance)
+ }
+
+ return nil
+}
+
+// loadFromRegistry loads devices from the registry, handling deduplication.
+func (m *DeviceManager) loadFromRegistry(records []*domainChatStorage.DeviceRecord) {
+ // Collect JIDs from manual devices (device_id doesn't contain @)
+ manualDeviceJIDs := make(map[string]bool)
+ for _, rec := range records {
+ if rec == nil || strings.TrimSpace(rec.DeviceID) == "" {
+ continue
+ }
+ if !strings.Contains(rec.DeviceID, "@") && rec.JID != "" {
+ manualDeviceJIDs[rec.JID] = true
+ }
+ }
+
+ // Load devices, removing auto-created duplicates
+ seenJIDs := make(map[string]bool)
+ for _, rec := range records {
+ if rec == nil || strings.TrimSpace(rec.DeviceID) == "" {
+ continue
+ }
+
+ // Skip auto-created devices if manual device with same JID exists
+ isAutoCreated := strings.Contains(rec.DeviceID, "@")
+ if isAutoCreated && manualDeviceJIDs[rec.DeviceID] {
+ logrus.Warnf("[DEVICE_MANAGER] removing auto-created device %s", rec.DeviceID)
+ _ = m.storage.DeleteDeviceRecord(rec.DeviceID)
+ continue
+ }
+
+ // Skip duplicate JIDs
+ if rec.JID != "" {
+ if seenJIDs[rec.JID] {
+ logrus.Warnf("[DEVICE_MANAGER] removing duplicate JID device %s", rec.DeviceID)
+ _ = m.storage.DeleteDeviceRecord(rec.DeviceID)
+ continue
+ }
+ seenJIDs[rec.JID] = true
+ }
+
+ // Check if a device with this JID already exists in memory (from InitWaCLI)
+ m.mu.RLock()
+ var existingByJID *DeviceInstance
+ for id, inst := range m.devices {
+ if rec.JID != "" && inst.JID() == rec.JID && id != rec.DeviceID {
+ existingByJID = inst
+ break
+ }
+ }
+ m.mu.RUnlock()
+
+ // If device with matching JID exists, remove it and use the registry device
+ if existingByJID != nil {
+ m.mu.Lock()
+ delete(m.devices, existingByJID.ID())
+ m.mu.Unlock()
+ logrus.Infof("[DEVICE_MANAGER] replacing in-memory device %s with registry device %s", existingByJID.ID(), rec.DeviceID)
+ }
+
+ // Create device instance
+ storageDeviceID := rec.DeviceID
+ if rec.JID != "" {
+ storageDeviceID = rec.JID
+ }
+ instance := NewDeviceInstance(rec.DeviceID, nil, newDeviceChatStorage(storageDeviceID, m.storage))
+ instance.SetState(domainDevice.DeviceStateDisconnected)
+ instance.displayName = rec.DisplayName
+ instance.jid = rec.JID
+
+ // If we had an existing device with client, transfer the client
+ if existingByJID != nil {
+ if client := existingByJID.GetClient(); client != nil {
+ instance.SetClient(client)
+ instance.UpdateStateFromClient()
+ }
+ }
+
+ m.AddDevice(instance)
+ }
+}
+
+// EnsureDefault registers the current global client as the default device if present.
+// It checks both by device ID and by JID to avoid creating duplicates.
+func (m *DeviceManager) EnsureDefault(client *DeviceInstance) {
+ if client == nil || client.ID() == "" {
+ return
+ }
+
+ m.mu.Lock()
+ defer m.mu.Unlock()
+
+ // Check if device exists by ID
+ if _, ok := m.devices[client.ID()]; ok {
+ return
+ }
+
+ // Check if any existing device has matching JID
+ clientJID := client.JID()
+ if clientJID != "" {
+ for _, inst := range m.devices {
+ if inst.JID() == clientJID {
+ // Update existing device with the new client
+ inst.SetClient(client.GetClient())
+ return
+ }
+ }
+ }
+
+ m.devices[client.ID()] = client
+}
+
+// EnsureClient returns a device instance with an initialized WhatsApp client.
+// It lazily creates the underlying store device and registers event handlers.
+func (m *DeviceManager) EnsureClient(ctx context.Context, deviceID string) (*DeviceInstance, error) {
+ if m == nil {
+ return nil, fmt.Errorf("device manager not initialized")
+ }
+
+ inst := m.ensureInstance(deviceID)
+ if existing := inst.GetClient(); existing != nil {
+ inst.UpdateStateFromClient()
+ return inst, nil
+ }
+
+ storeDevice, err := m.getOrCreateStoreDevice(ctx, deviceID)
+ if err != nil {
+ return nil, err
+ }
+
+ configureDeviceProps()
+
+ if err := m.configureKeysStore(ctx, storeDevice); err != nil {
+ return nil, fmt.Errorf("failed to configure keys store: %w", err)
+ }
+
+ baseLogger := waLog.Stdout(fmt.Sprintf("Client-%s", deviceID), config.WhatsappLogLevel, true)
+ client := whatsmeow.NewClient(storeDevice, newFilteredLogger(baseLogger))
+ client.EnableAutoReconnect = true
+ client.AutoTrustIdentity = true
+
+ repo := inst.GetChatStorage()
+ if repo == nil {
+ repo = newDeviceChatStorage(deviceID, m.storage)
+ inst.SetChatStorage(repo)
+ }
+
+ client.AddEventHandler(func(rawEvt interface{}) {
+ handler(ctx, inst, rawEvt)
+ })
+
+ inst.SetClient(client)
+ inst.UpdateStateFromClient()
+
+ return inst, nil
+}
+
+func (m *DeviceManager) ensureInstance(deviceID string) *DeviceInstance {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+
+ // Check by device ID first
+ if inst, ok := m.devices[deviceID]; ok {
+ if inst.GetChatStorage() == nil {
+ storageDeviceID := inst.JID()
+ if storageDeviceID == "" {
+ storageDeviceID = deviceID
+ }
+ inst.SetChatStorage(newDeviceChatStorage(storageDeviceID, m.storage))
+ }
+ return inst
+ }
+
+ // Check if any existing device has this as its JID (deviceID might be a JID)
+ for _, inst := range m.devices {
+ if inst.JID() == deviceID {
+ if inst.GetChatStorage() == nil {
+ storageDeviceID := inst.JID()
+ if storageDeviceID == "" {
+ storageDeviceID = inst.ID()
+ }
+ inst.SetChatStorage(newDeviceChatStorage(storageDeviceID, m.storage))
+ }
+ return inst
+ }
+ }
+
+ inst := NewDeviceInstance(deviceID, nil, newDeviceChatStorage(deviceID, m.storage))
+ m.devices[deviceID] = inst
+ return inst
+}
+
+func (m *DeviceManager) getOrCreateStoreDevice(ctx context.Context, deviceID string) (*store.Device, error) {
+ if m.store == nil {
+ return nil, fmt.Errorf("store container is nil")
+ }
+
+ // Try to reuse an existing device record if the ID maps to a JID.
+ if deviceID != "" {
+ if jid, err := types.ParseJID(deviceID); err == nil {
+ if dev, err := m.store.GetDevice(ctx, jid); err == nil && dev != nil {
+ return dev, nil
+ }
+ }
+
+ // If deviceID is not a valid JID, look up the device instance and use its JID
+ m.mu.RLock()
+ var instJID string
+ if inst, ok := m.devices[deviceID]; ok && inst.JID() != "" {
+ instJID = inst.JID()
+ }
+ m.mu.RUnlock()
+
+ if instJID != "" {
+ if jid, err := types.ParseJID(instJID); err == nil {
+ if dev, err := m.store.GetDevice(ctx, jid); err == nil && dev != nil {
+ return dev, nil
+ }
+ // Fallback: iterate all devices to find one with matching User (ignoring AD-ID)
+ // This handles cases where registry has Non-AD JID but store has full JID
+ if allDevices, err := m.store.GetAllDevices(ctx); err == nil {
+ targetUser := jid.User
+ for _, d := range allDevices {
+ if d != nil && d.ID != nil && d.ID.User == targetUser {
+ return d, nil
+ }
+ }
+ }
+ }
+ }
+ }
+
+ return m.store.NewDevice(), nil
+}
+
+func (m *DeviceManager) configureKeysStore(ctx context.Context, device *store.Device) error {
+ if m.keys == nil || device == nil || device.ID == nil {
+ return nil
+ }
+
+ innerStore := sqlstore.NewSQLStore(m.keys, *device.ID)
+ syncKeysDevice(ctx, m.store, m.keys)
+
+ device.Identities = innerStore
+ device.Sessions = innerStore
+ device.PreKeys = innerStore
+ device.SenderKeys = innerStore
+ device.MsgSecrets = innerStore
+ device.PrivacyTokens = innerStore
+ return nil
+}
+
+func configureDeviceProps() {
+ osName := fmt.Sprintf("%s %s", config.AppOs, config.AppVersion)
+ store.DeviceProps.PlatformType = &config.AppPlatform
+ store.DeviceProps.Os = &osName
+}
+
+// StoreInfo returns configured store URIs for observability.
+func (m *DeviceManager) StoreInfo() (dbURI, keysURI string) {
+ if m == nil {
+ return "", ""
+ }
+ return config.DBURI, config.DBKeysURI
+}
diff --git a/src/infrastructure/whatsapp/event_delete.go b/src/infrastructure/whatsapp/event_delete.go
index 06860273..f398671a 100644
--- a/src/infrastructure/whatsapp/event_delete.go
+++ b/src/infrastructure/whatsapp/event_delete.go
@@ -5,12 +5,13 @@ import (
"time"
domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
+ "go.mau.fi/whatsmeow"
"go.mau.fi/whatsmeow/types/events"
)
// forwardDeleteToWebhook sends a delete event to webhook
-func forwardDeleteToWebhook(ctx context.Context, evt *events.DeleteForMe, message *domainChatStorage.Message) error {
- payload, err := createDeletePayload(ctx, evt, message)
+func forwardDeleteToWebhook(ctx context.Context, evt *events.DeleteForMe, message *domainChatStorage.Message, deviceID string, client *whatsmeow.Client) error {
+ payload, err := createDeletePayload(ctx, evt, message, deviceID, client)
if err != nil {
return err
}
@@ -19,14 +20,21 @@ func forwardDeleteToWebhook(ctx context.Context, evt *events.DeleteForMe, messag
}
// createDeletePayload creates a webhook payload for delete events
-func createDeletePayload(_ context.Context, evt *events.DeleteForMe, message *domainChatStorage.Message) (map[string]any, error) {
+func createDeletePayload(ctx context.Context, evt *events.DeleteForMe, message *domainChatStorage.Message, deviceID string, client *whatsmeow.Client) (map[string]any, error) {
body := make(map[string]any)
// Basic delete event information
body["action"] = "event.delete_for_me"
body["deleted_message_id"] = evt.MessageID
- body["sender_id"] = evt.SenderJID.User
body["timestamp"] = time.Now().Format(time.RFC3339)
+ if deviceID != "" {
+ body["device_id"] = deviceID
+ }
+
+ // Resolve sender JID (convert LID to phone number if needed)
+ normalizedSenderJID := NormalizeJIDFromLID(ctx, evt.SenderJID, client)
+ body["from"] = normalizedSenderJID.ToNonAD().String()
+ body["sender_id"] = normalizedSenderJID.User
// Include original message information if available
if message != nil {
@@ -42,10 +50,5 @@ func createDeletePayload(_ context.Context, evt *events.DeleteForMe, message *do
}
}
- // Parse sender JID for proper formatting
- if evt.SenderJID.Server != "" {
- body["from"] = evt.SenderJID.String()
- }
-
return body, nil
}
diff --git a/src/infrastructure/whatsapp/event_group.go b/src/infrastructure/whatsapp/event_group.go
index 1a812704..c14302d2 100644
--- a/src/infrastructure/whatsapp/event_group.go
+++ b/src/infrastructure/whatsapp/event_group.go
@@ -8,23 +8,24 @@ import (
"github.com/aldinokemal/go-whatsapp-web-multidevice/config"
"github.com/sirupsen/logrus"
+ "go.mau.fi/whatsmeow"
"go.mau.fi/whatsmeow/types"
"go.mau.fi/whatsmeow/types/events"
)
// createGroupInfoPayload creates a webhook payload for group information events
-func createGroupInfoPayload(evt *events.GroupInfo, actionType string, jids []types.JID) map[string]any {
+func createGroupInfoPayload(ctx context.Context, evt *events.GroupInfo, actionType string, jids []types.JID, deviceID string, client *whatsmeow.Client) map[string]any {
body := make(map[string]any)
// Create payload structure matching the expected format
payload := make(map[string]any)
- // Add group chat ID
- payload["chat_id"] = evt.JID.String()
+ // Add group chat ID (groups use @g.us, not @lid, so no LID resolution needed)
+ payload["chat_id"] = evt.JID.ToNonAD().String()
- // Add action type and affected users
+ // Add action type and affected users (with LID resolution)
payload["type"] = actionType
- payload["jids"] = jidsToStrings(jids)
+ payload["jids"] = jidsToStrings(ctx, jids, client)
// Wrap in payload structure
body["payload"] = payload
@@ -32,25 +33,30 @@ func createGroupInfoPayload(evt *events.GroupInfo, actionType string, jids []typ
// Add metadata for webhook processing
body["event"] = "group.participants"
body["timestamp"] = evt.Timestamp.Format(time.RFC3339)
+ if deviceID != "" {
+ body["device_id"] = deviceID
+ }
return body
}
-// jidsToStrings converts a slice of JIDs to a slice of strings
-func jidsToStrings(jids []types.JID) []string {
+// jidsToStrings converts a slice of JIDs to a slice of strings, resolving LIDs to phone numbers
+func jidsToStrings(ctx context.Context, jids []types.JID, client *whatsmeow.Client) []string {
if len(jids) == 0 {
return []string{} // Return empty array instead of nil for consistent JSON
}
result := make([]string, len(jids))
for i, jid := range jids {
- result[i] = jid.String()
+ // Resolve LID to phone number if possible
+ normalizedJID := NormalizeJIDFromLID(ctx, jid, client)
+ result[i] = normalizedJID.ToNonAD().String()
}
return result
}
// forwardGroupInfoToWebhook forwards group information events to the configured webhook URLs
-func forwardGroupInfoToWebhook(ctx context.Context, evt *events.GroupInfo) error {
+func forwardGroupInfoToWebhook(ctx context.Context, evt *events.GroupInfo, deviceID string, client *whatsmeow.Client) error {
logrus.Infof("Forwarding group info event to %d configured webhook(s)", len(config.WhatsappWebhook))
// Send separate webhook events for each action type
@@ -66,7 +72,7 @@ func forwardGroupInfoToWebhook(ctx context.Context, evt *events.GroupInfo) error
for _, action := range actions {
if len(action.jids) > 0 {
- payload := createGroupInfoPayload(evt, action.actionType, action.jids)
+ payload := createGroupInfoPayload(ctx, evt, action.actionType, action.jids, deviceID, client)
// Collect errors from all webhook URLs instead of failing fast
var errors []error
diff --git a/src/infrastructure/whatsapp/event_handler.go b/src/infrastructure/whatsapp/event_handler.go
new file mode 100644
index 00000000..bc4e9cee
--- /dev/null
+++ b/src/infrastructure/whatsapp/event_handler.go
@@ -0,0 +1,254 @@
+package whatsapp
+
+import (
+ "context"
+ "fmt"
+ "os"
+ "strings"
+ "time"
+
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/config"
+ domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
+ domainDevice "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/device"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/ui/websocket"
+ "github.com/sirupsen/logrus"
+ "go.mau.fi/whatsmeow"
+ "go.mau.fi/whatsmeow/appstate"
+ "go.mau.fi/whatsmeow/types"
+ "go.mau.fi/whatsmeow/types/events"
+)
+
+// handler is the main event handler for WhatsApp events, scoped to a device instance.
+func handler(ctx context.Context, instance *DeviceInstance, rawEvt any) {
+ if instance == nil {
+ return
+ }
+
+ // Ensure downstream handlers see the device context (used for device-scoped storage).
+ ctx = ContextWithDevice(ctx, instance)
+
+ chatStorageRepo := instance.GetChatStorage()
+ client := instance.GetClient()
+
+ switch evt := rawEvt.(type) {
+ case *events.DeleteForMe:
+ handleDeleteForMe(ctx, evt, chatStorageRepo, instance.JID(), client)
+ case *events.AppStateSyncComplete:
+ handleAppStateSyncComplete(ctx, client, evt)
+ case *events.PairSuccess:
+ handlePairSuccess(ctx, evt)
+ case *events.LoggedOut:
+ handleLoggedOut(ctx, instance, chatStorageRepo)
+ case *events.Connected, *events.PushNameSetting:
+ handleConnectionEvents(ctx, client, instance)
+ case *events.StreamReplaced:
+ handleStreamReplaced(ctx)
+ case *events.Message:
+ handleMessage(ctx, evt, chatStorageRepo, client)
+ case *events.Receipt:
+ handleReceipt(ctx, evt, instance.JID(), client)
+ case *events.Presence:
+ handlePresence(ctx, evt)
+ case *events.HistorySync:
+ handleHistorySync(ctx, evt, chatStorageRepo, client)
+ case *events.AppState:
+ handleAppState(ctx, evt)
+ case *events.GroupInfo:
+ handleGroupInfo(ctx, evt, instance.JID(), client)
+ }
+
+ instance.UpdateStateFromClient()
+}
+
+func handleDeleteForMe(ctx context.Context, evt *events.DeleteForMe, chatStorageRepo domainChatStorage.IChatStorageRepository, deviceID string, client *whatsmeow.Client) {
+ log.Infof("Deleted message %s for %s", evt.MessageID, evt.SenderJID.String())
+
+ // Find the message to get its chat JID
+ message, err := chatStorageRepo.GetMessageByID(evt.MessageID)
+ if err != nil {
+ log.Errorf("Failed to find message %s for deletion: %v", evt.MessageID, err)
+ return
+ }
+
+ if message == nil {
+ log.Warnf("Message %s not found in database, skipping deletion", evt.MessageID)
+ return
+ }
+
+ // Delete the message from database
+ if err := chatStorageRepo.DeleteMessage(evt.MessageID, message.ChatJID); err != nil {
+ log.Errorf("Failed to delete message %s from database: %v", evt.MessageID, err)
+ } else {
+ log.Infof("Successfully deleted message %s from database", evt.MessageID)
+ }
+
+ // Send webhook notification for delete event
+ if len(config.WhatsappWebhook) > 0 {
+ go func(c *whatsmeow.Client) {
+ webhookCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+ if err := forwardDeleteToWebhook(webhookCtx, evt, message, deviceID, c); err != nil {
+ log.Errorf("Failed to forward delete event to webhook: %v", err)
+ }
+ }(client)
+ }
+}
+
+func handleAppStateSyncComplete(_ context.Context, client *whatsmeow.Client, evt *events.AppStateSyncComplete) {
+ if client == nil {
+ return
+ }
+ if len(client.Store.PushName) > 0 && evt.Name == appstate.WAPatchCriticalBlock {
+ if err := client.SendPresence(context.Background(), types.PresenceAvailable); err != nil {
+ log.Warnf("Failed to send available presence: %v", err)
+ } else {
+ log.Infof("Marked self as available")
+ }
+ }
+}
+
+func handlePairSuccess(ctx context.Context, evt *events.PairSuccess) {
+ websocket.Broadcast <- websocket.BroadcastMessage{
+ Code: "LOGIN_SUCCESS",
+ Message: fmt.Sprintf("Successfully pair with %s", evt.ID.String()),
+ }
+ primaryDB, secondaryDB := getStoreContainers()
+ syncKeysDevice(ctx, primaryDB, secondaryDB)
+}
+
+func handleLoggedOut(ctx context.Context, instance *DeviceInstance, chatStorageRepo domainChatStorage.IChatStorageRepository) {
+ logrus.Warnf("[REMOTE_LOGOUT] Received LoggedOut event for device %s - user logged out from phone", instance.ID())
+
+ if client := instance.GetClient(); client != nil {
+ client.Disconnect()
+ }
+ instance.SetState(domainDevice.DeviceStateDisconnected)
+
+ if chatStorageRepo != nil {
+ if err := chatStorageRepo.TruncateAllDataWithLogging("REMOTE_LOGOUT"); err != nil {
+ logrus.Errorf("[REMOTE_LOGOUT] Failed to truncate chat storage: %v", err)
+ }
+ }
+
+ websocket.Broadcast <- websocket.BroadcastMessage{
+ Code: "LOGOUT_COMPLETE",
+ Message: "Remote logout cleanup completed - ready for new login",
+ Result: map[string]string{"device_id": instance.ID()},
+ }
+}
+
+func handleConnectionEvents(_ context.Context, client *whatsmeow.Client, instance *DeviceInstance) {
+ if client == nil {
+ return
+ }
+ if instance != nil {
+ instance.UpdateStateFromClient()
+
+ // Persist updated JID/DisplayName to database after successful connection
+ // Skip if instance.ID looks like a JID (auto-created device) to avoid recreating deleted duplicates
+ if repo := instance.GetChatStorage(); repo != nil && !strings.Contains(instance.ID(), "@") {
+ jid := instance.JID()
+ displayName := instance.DisplayName()
+ if jid != "" {
+ if err := repo.SaveDeviceRecord(&domainChatStorage.DeviceRecord{
+ DeviceID: instance.ID(),
+ DisplayName: displayName,
+ JID: jid,
+ CreatedAt: instance.CreatedAt(),
+ }); err != nil {
+ log.Warnf("Failed to persist device record for %s: %v", instance.ID(), err)
+ }
+ }
+ }
+ }
+ if len(client.Store.PushName) == 0 {
+ return
+ }
+
+ // Send presence available when connecting and when the pushname is changed.
+ // This makes sure that outgoing messages always have the right pushname.
+ if err := client.SendPresence(context.Background(), types.PresenceAvailable); err != nil {
+ log.Warnf("Failed to send available presence: %v", err)
+ } else {
+ log.Infof("Marked self as available")
+ }
+}
+
+func handleStreamReplaced(_ context.Context) {
+ os.Exit(0)
+}
+
+func handleReceipt(ctx context.Context, evt *events.Receipt, deviceID string, client *whatsmeow.Client) {
+ sendReceipt := false
+ switch evt.Type {
+ case types.ReceiptTypeRead, types.ReceiptTypeReadSelf:
+ sendReceipt = true
+ log.Infof("%v was read by %s at %s: %+v", evt.MessageIDs, evt.SourceString(), evt.Timestamp, evt)
+ case types.ReceiptTypeDelivered:
+ sendReceipt = true
+ log.Infof("%s was delivered to %s at %s: %+v", evt.MessageIDs[0], evt.SourceString(), evt.Timestamp, evt)
+ }
+
+ // Forward receipt (ack) event to webhook if configured
+ // Note: Receipt events are not rate limited as they are critical for message delivery status
+ if len(config.WhatsappWebhook) > 0 && sendReceipt {
+ go func(e *events.Receipt, c *whatsmeow.Client) {
+ webhookCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+ if err := forwardReceiptToWebhook(webhookCtx, e, deviceID, c); err != nil {
+ logrus.Errorf("Failed to forward ack event to webhook: %v", err)
+ }
+ }(evt, client)
+ }
+}
+
+func handlePresence(_ context.Context, evt *events.Presence) {
+ if evt.Unavailable {
+ if evt.LastSeen.IsZero() {
+ log.Infof("%s is now offline", evt.From)
+ } else {
+ log.Infof("%s is now offline (last seen: %s)", evt.From, evt.LastSeen)
+ }
+ } else {
+ log.Infof("%s is now online", evt.From)
+ }
+}
+
+func handleAppState(_ context.Context, evt *events.AppState) {
+ log.Debugf("App state event: %+v / %+v", evt.Index, evt.SyncActionValue)
+}
+
+func handleGroupInfo(ctx context.Context, evt *events.GroupInfo, deviceID string, client *whatsmeow.Client) {
+ // Only process events that have actual changes
+ hasChanges := len(evt.Join) > 0 || len(evt.Leave) > 0 || len(evt.Promote) > 0 || len(evt.Demote) > 0 ||
+ evt.Name != nil || evt.Topic != nil || evt.Locked != nil || evt.Announce != nil
+
+ if !hasChanges {
+ return
+ }
+
+ // Log group events for debugging
+ if len(evt.Join) > 0 {
+ log.Infof("Group %s: %d users joined at %s", evt.JID, len(evt.Join), evt.Timestamp)
+ }
+ if len(evt.Leave) > 0 {
+ log.Infof("Group %s: %d users left at %s", evt.JID, len(evt.Leave), evt.Timestamp)
+ }
+ if len(evt.Promote) > 0 {
+ log.Infof("Group %s: %d users promoted at %s", evt.JID, len(evt.Promote), evt.Timestamp)
+ }
+ if len(evt.Demote) > 0 {
+ log.Infof("Group %s: %d users demoted at %s", evt.JID, len(evt.Demote), evt.Timestamp)
+ }
+
+ // Forward group info event to webhook if configured
+ if len(config.WhatsappWebhook) > 0 {
+ go func(e *events.GroupInfo, c *whatsmeow.Client) {
+ webhookCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+ if err := forwardGroupInfoToWebhook(webhookCtx, e, deviceID, c); err != nil {
+ logrus.Errorf("Failed to forward group info event to webhook: %v", err)
+ }
+ }(evt, client)
+ }
+}
diff --git a/src/infrastructure/whatsapp/event_message.go b/src/infrastructure/whatsapp/event_message.go
index baa3e366..c11d221f 100644
--- a/src/infrastructure/whatsapp/event_message.go
+++ b/src/infrastructure/whatsapp/event_message.go
@@ -7,6 +7,7 @@ import (
"strings"
"time"
+ "go.mau.fi/whatsmeow"
"go.mau.fi/whatsmeow/types"
"github.com/aldinokemal/go-whatsapp-web-multidevice/config"
@@ -16,56 +17,148 @@ import (
"go.mau.fi/whatsmeow/types/events"
)
+// Event types for webhook payload
+const (
+ EventTypeMessage = "message"
+ EventTypeMessageReaction = "message.reaction"
+ EventTypeMessageRevoked = "message.revoked"
+ EventTypeMessageEdited = "message.edited"
+)
+
+// WebhookEvent is the top-level structure for webhook payloads
+type WebhookEvent struct {
+ Event string `json:"event"`
+ DeviceID string `json:"device_id"`
+ Payload map[string]any `json:"payload"`
+}
+
// forwardMessageToWebhook is a helper function to forward message event to webhook url
-func forwardMessageToWebhook(ctx context.Context, evt *events.Message) error {
- payload, err := createMessagePayload(ctx, evt)
+func forwardMessageToWebhook(ctx context.Context, client *whatsmeow.Client, evt *events.Message) error {
+ webhookEvent, err := createWebhookEvent(ctx, client, evt)
if err != nil {
return err
}
+ payload := map[string]any{
+ "event": webhookEvent.Event,
+ "device_id": webhookEvent.DeviceID,
+ "payload": webhookEvent.Payload,
+ }
+
return forwardPayloadToConfiguredWebhooks(ctx, payload, "message event")
}
-func createMessagePayload(ctx context.Context, evt *events.Message) (map[string]any, error) {
- message := utils.BuildEventMessage(evt)
- waReaction := utils.BuildEventReaction(evt)
- forwarded := utils.BuildForwarded(evt)
+func createWebhookEvent(ctx context.Context, client *whatsmeow.Client, evt *events.Message) (*WebhookEvent, error) {
+ webhookEvent := &WebhookEvent{
+ Event: EventTypeMessage,
+ Payload: make(map[string]any),
+ }
- body := make(map[string]any)
+ // Set device_id
+ if client != nil && client.Store != nil && client.Store.ID != nil {
+ deviceJID := NormalizeJIDFromLID(ctx, client.Store.ID.ToNonAD(), client)
+ webhookEvent.DeviceID = deviceJID.ToNonAD().String()
+ }
- body["sender_id"] = evt.Info.Sender.User
- body["chat_id"] = evt.Info.Chat.User
+ // Determine event type and build payload
+ eventType, payload, err := buildEventPayload(ctx, client, evt)
+ if err != nil {
+ return nil, err
+ }
- if from := evt.Info.SourceString(); from != "" {
- body["from"] = from
+ webhookEvent.Event = eventType
+ webhookEvent.Payload = payload
- from_user, from_group := from, ""
- if strings.Contains(from, " in ") {
- from_user = strings.Split(from, " in ")[0]
- from_group = strings.Split(from, " in ")[1]
- }
+ return webhookEvent, nil
+}
- if strings.HasSuffix(from_user, "@lid") {
- body["from_lid"] = from_user
- lid, err := types.ParseJID(from_user)
- if err != nil {
- logrus.Errorf("Error when parse jid: %v", err)
- } else {
- pn, err := cli.Store.LIDs.GetPNForLID(ctx, lid)
- if err != nil {
- logrus.Errorf("Error when get pn for lid %s: %v", lid.String(), err)
+func buildEventPayload(ctx context.Context, client *whatsmeow.Client, evt *events.Message) (string, map[string]any, error) {
+ payload := make(map[string]any)
+
+ // Common fields for all message types
+ payload["id"] = evt.Info.ID
+ payload["timestamp"] = evt.Info.Timestamp.Format(time.RFC3339)
+
+ // Build from/from_lid fields
+ buildFromFields(ctx, client, evt, payload)
+
+ // Set from_name (pushname)
+ if pushname := evt.Info.PushName; pushname != "" {
+ payload["from_name"] = pushname
+ }
+
+ // Check for protocol messages (revoke, edit)
+ if protocolMessage := evt.Message.GetProtocolMessage(); protocolMessage != nil {
+ protocolType := protocolMessage.GetType().String()
+
+ switch protocolType {
+ case "REVOKE":
+ if key := protocolMessage.GetKey(); key != nil {
+ payload["revoked_message_id"] = key.GetID()
+ payload["revoked_from_me"] = key.GetFromMe()
+ if key.GetRemoteJID() != "" {
+ payload["revoked_chat"] = key.GetRemoteJID()
}
- if !pn.IsEmpty() {
- if from_group != "" {
- body["from"] = fmt.Sprintf("%s in %s", pn.String(), from_group)
- } else {
- body["from"] = pn.String()
- }
+ }
+ return EventTypeMessageRevoked, payload, nil
+
+ case "MESSAGE_EDIT":
+ if key := protocolMessage.GetKey(); key != nil {
+ payload["original_message_id"] = key.GetID()
+ }
+ if editedMessage := protocolMessage.GetEditedMessage(); editedMessage != nil {
+ if editedText := editedMessage.GetExtendedTextMessage(); editedText != nil {
+ payload["body"] = editedText.GetText()
+ } else if editedConv := editedMessage.GetConversation(); editedConv != "" {
+ payload["body"] = editedConv
}
}
+ return EventTypeMessageEdited, payload, nil
}
}
- if message.ID != "" {
+
+ // Check for reaction message
+ if reactionMessage := evt.Message.GetReactionMessage(); reactionMessage != nil {
+ payload["reaction"] = reactionMessage.GetText()
+ if key := reactionMessage.GetKey(); key != nil {
+ payload["reacted_message_id"] = key.GetID()
+ }
+ return EventTypeMessageReaction, payload, nil
+ }
+
+ // Regular message - build body and media fields
+ if err := buildMessageBody(ctx, client, evt, payload); err != nil {
+ return "", nil, err
+ }
+
+ // Add optional fields
+ if err := buildOptionalFields(ctx, client, evt, payload); err != nil {
+ return "", nil, err
+ }
+
+ return EventTypeMessage, payload, nil
+}
+
+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()
+
+ // 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()
+}
+
+func buildMessageBody(ctx context.Context, client *whatsmeow.Client, evt *events.Message, payload map[string]any) error {
+ message := utils.BuildEventMessage(evt)
+
+ // Replace LID mentions with phone numbers in text
+ if message.Text != "" && client != nil && client.Store != nil && client.Store.LIDs != nil {
tags := regexp.MustCompile(`\B@\w+`).FindAllString(message.Text, -1)
tagsMap := make(map[string]bool)
for _, tag := range tags {
@@ -76,92 +169,77 @@ func createMessagePayload(ctx context.Context, evt *events.Message) (map[string]
if err != nil {
logrus.Errorf("Error when parse jid: %v", err)
} else {
- pn, err := cli.Store.LIDs.GetPNForLID(ctx, lid)
+ pn, err := client.Store.LIDs.GetPNForLID(ctx, lid)
if err != nil {
- logrus.Errorf("Error when get pn for lid %s: %v", lid.String(), err)
+ logrus.Errorf("Error when get pn for lid %s: %v", lid.ToNonAD().String(), err)
}
if !pn.IsEmpty() {
message.Text = strings.Replace(message.Text, tag, fmt.Sprintf("@%s", pn.User), -1)
}
}
}
- body["message"] = message
+ payload["body"] = message.Text
+ } else if message.Text != "" {
+ payload["body"] = message.Text
}
- if pushname := evt.Info.PushName; pushname != "" {
- body["pushname"] = pushname
+
+ // Add reply context if present
+ if message.RepliedId != "" {
+ payload["replied_to_id"] = message.RepliedId
}
- if waReaction.Message != "" {
- body["reaction"] = waReaction
+ if message.QuotedMessage != "" {
+ payload["quoted_body"] = message.QuotedMessage
}
+
+ return nil
+}
+
+func buildOptionalFields(ctx context.Context, client *whatsmeow.Client, evt *events.Message, payload map[string]any) error {
if evt.IsViewOnce {
- body["view_once"] = evt.IsViewOnce
+ payload["view_once"] = true
}
- if forwarded {
- body["forwarded"] = forwarded
+
+ if utils.BuildForwarded(evt) {
+ payload["forwarded"] = true
}
- if timestamp := evt.Info.Timestamp.Format(time.RFC3339); timestamp != "" {
- body["timestamp"] = timestamp
+
+ // Handle media types
+ if err := buildMediaFields(ctx, client, evt, payload); err != nil {
+ return err
}
- // Handle protocol messages (revoke, etc.)
- if protocolMessage := evt.Message.GetProtocolMessage(); protocolMessage != nil {
- protocolType := protocolMessage.GetType().String()
+ // Handle other message types
+ buildOtherMessageTypes(evt, payload)
- switch protocolType {
- case "REVOKE":
- body["action"] = "message_revoked"
- if key := protocolMessage.GetKey(); key != nil {
- body["revoked_message_id"] = key.GetID()
- body["revoked_from_me"] = key.GetFromMe()
- if key.GetRemoteJID() != "" {
- body["revoked_chat"] = key.GetRemoteJID()
- }
- }
- case "MESSAGE_EDIT":
- body["action"] = "message_edited"
- // Extract the original message ID from the protocol message key
- if key := protocolMessage.GetKey(); key != nil {
- body["original_message_id"] = key.GetID()
- }
- if editedMessage := protocolMessage.GetEditedMessage(); editedMessage != nil {
- if editedText := editedMessage.GetExtendedTextMessage(); editedText != nil {
- body["edited_text"] = editedText.GetText()
- } else if editedConv := editedMessage.GetConversation(); editedConv != "" {
- body["edited_text"] = editedConv
- }
- }
- }
- }
+ 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 {
if config.WhatsappAutoDownloadMedia {
- path, err := utils.ExtractMedia(ctx, cli, config.PathMedia, audioMedia)
+ path, 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 nil, pkgError.WebhookError(fmt.Sprintf("Failed to download audio: %v", err))
+ return pkgError.WebhookError(fmt.Sprintf("Failed to download audio: %v", err))
}
- body["audio"] = path
+ payload["audio"] = path
} else {
- body["audio"] = map[string]any{
+ payload["audio"] = map[string]any{
"url": audioMedia.GetURL(),
}
}
}
- if contactMessage := evt.Message.GetContactMessage(); contactMessage != nil {
- body["contact"] = contactMessage
- }
-
if documentMedia := evt.Message.GetDocumentMessage(); documentMedia != nil {
if config.WhatsappAutoDownloadMedia {
- path, err := utils.ExtractMedia(ctx, cli, config.PathMedia, documentMedia)
+ path, 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 nil, pkgError.WebhookError(fmt.Sprintf("Failed to download document: %v", err))
+ return pkgError.WebhookError(fmt.Sprintf("Failed to download document: %v", err))
}
- body["document"] = path
+ payload["document"] = path
} else {
- body["document"] = map[string]any{
+ payload["document"] = map[string]any{
"url": documentMedia.GetURL(),
"filename": documentMedia.GetFileName(),
}
@@ -170,46 +248,30 @@ func createMessagePayload(ctx context.Context, evt *events.Message) (map[string]
if imageMedia := evt.Message.GetImageMessage(); imageMedia != nil {
if config.WhatsappAutoDownloadMedia {
- path, err := utils.ExtractMedia(ctx, cli, config.PathMedia, imageMedia)
+ path, 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 nil, pkgError.WebhookError(fmt.Sprintf("Failed to download image: %v", err))
+ return pkgError.WebhookError(fmt.Sprintf("Failed to download image: %v", err))
}
- body["image"] = path
+ payload["image"] = path
} else {
- body["image"] = map[string]any{
+ payload["image"] = map[string]any{
"url": imageMedia.GetURL(),
"caption": imageMedia.GetCaption(),
}
}
}
- if listMessage := evt.Message.GetListMessage(); listMessage != nil {
- body["list"] = listMessage
- }
-
- if liveLocationMessage := evt.Message.GetLiveLocationMessage(); liveLocationMessage != nil {
- body["live_location"] = liveLocationMessage
- }
-
- if locationMessage := evt.Message.GetLocationMessage(); locationMessage != nil {
- body["location"] = locationMessage
- }
-
- if orderMessage := evt.Message.GetOrderMessage(); orderMessage != nil {
- body["order"] = orderMessage
- }
-
if stickerMedia := evt.Message.GetStickerMessage(); stickerMedia != nil {
if config.WhatsappAutoDownloadMedia {
- path, err := utils.ExtractMedia(ctx, cli, config.PathMedia, stickerMedia)
+ path, 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 nil, pkgError.WebhookError(fmt.Sprintf("Failed to download sticker: %v", err))
+ return pkgError.WebhookError(fmt.Sprintf("Failed to download sticker: %v", err))
}
- body["sticker"] = path
+ payload["sticker"] = path
} else {
- body["sticker"] = map[string]any{
+ payload["sticker"] = map[string]any{
"url": stickerMedia.GetURL(),
}
}
@@ -217,36 +279,57 @@ func createMessagePayload(ctx context.Context, evt *events.Message) (map[string]
if videoMedia := evt.Message.GetVideoMessage(); videoMedia != nil {
if config.WhatsappAutoDownloadMedia {
- path, err := utils.ExtractMedia(ctx, cli, config.PathMedia, videoMedia)
+ path, 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 nil, pkgError.WebhookError(fmt.Sprintf("Failed to download video: %v", err))
+ return pkgError.WebhookError(fmt.Sprintf("Failed to download video: %v", err))
}
- body["video"] = path
+ payload["video"] = path
} else {
- body["video"] = map[string]any{
+ payload["video"] = map[string]any{
"url": videoMedia.GetURL(),
"caption": videoMedia.GetCaption(),
}
}
}
- // Handle PTV (Push-To-Video) messages - also known as "video notes" (circular video messages)
if ptvMedia := evt.Message.GetPtvMessage(); ptvMedia != nil {
if config.WhatsappAutoDownloadMedia {
- path, err := utils.ExtractMedia(ctx, cli, config.PathMedia, ptvMedia)
+ path, 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 nil, pkgError.WebhookError(fmt.Sprintf("Failed to download video note: %v", err))
+ return pkgError.WebhookError(fmt.Sprintf("Failed to download video note: %v", err))
}
- body["video_note"] = path
+ payload["video_note"] = path
} else {
- body["video_note"] = map[string]any{
+ payload["video_note"] = map[string]any{
"url": ptvMedia.GetURL(),
"caption": ptvMedia.GetCaption(),
}
}
}
- return body, nil
+ return nil
+}
+
+func buildOtherMessageTypes(evt *events.Message, payload map[string]any) {
+ if contactMessage := evt.Message.GetContactMessage(); contactMessage != nil {
+ payload["contact"] = contactMessage
+ }
+
+ if listMessage := evt.Message.GetListMessage(); listMessage != nil {
+ payload["list"] = listMessage
+ }
+
+ if liveLocationMessage := evt.Message.GetLiveLocationMessage(); liveLocationMessage != nil {
+ payload["live_location"] = liveLocationMessage
+ }
+
+ if locationMessage := evt.Message.GetLocationMessage(); locationMessage != nil {
+ payload["location"] = locationMessage
+ }
+
+ if orderMessage := evt.Message.GetOrderMessage(); orderMessage != nil {
+ payload["order"] = orderMessage
+ }
}
diff --git a/src/infrastructure/whatsapp/event_message_handler.go b/src/infrastructure/whatsapp/event_message_handler.go
new file mode 100644
index 00000000..43b06d5c
--- /dev/null
+++ b/src/infrastructure/whatsapp/event_message_handler.go
@@ -0,0 +1,136 @@
+package whatsapp
+
+import (
+ "context"
+ "fmt"
+ "strings"
+ "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/types"
+ "go.mau.fi/whatsmeow/types/events"
+)
+
+func handleMessage(ctx context.Context, evt *events.Message, chatStorageRepo domainChatStorage.IChatStorageRepository, client *whatsmeow.Client) {
+ // Log message metadata
+ metaParts := buildMessageMetaParts(evt)
+ log.Infof("Received message %s from %s (%s): %+v",
+ evt.Info.ID,
+ evt.Info.SourceString(),
+ strings.Join(metaParts, ", "),
+ evt.Message,
+ )
+
+ if err := chatStorageRepo.CreateMessage(ctx, evt); err != nil {
+ // Log storage errors to avoid silent failures that could lead to data loss
+ log.Errorf("Failed to store incoming message %s: %v", evt.Info.ID, err)
+ }
+
+ // Handle image message if present
+ handleImageMessage(ctx, evt, client)
+
+ // Auto-mark message as read if configured
+ handleAutoMarkRead(ctx, evt, client)
+
+ // Handle auto-reply if configured
+ handleAutoReply(ctx, evt, chatStorageRepo, client)
+
+ // Forward to webhook if configured
+ handleWebhookForward(ctx, evt, client)
+}
+
+func buildMessageMetaParts(evt *events.Message) []string {
+ metaParts := []string{
+ fmt.Sprintf("pushname: %s", evt.Info.PushName),
+ fmt.Sprintf("timestamp: %s", evt.Info.Timestamp),
+ }
+ if evt.Info.Type != "" {
+ metaParts = append(metaParts, fmt.Sprintf("type: %s", evt.Info.Type))
+ }
+ if evt.Info.Category != "" {
+ metaParts = append(metaParts, fmt.Sprintf("category: %s", evt.Info.Category))
+ }
+ if evt.IsViewOnce {
+ metaParts = append(metaParts, "view once")
+ }
+ return metaParts
+}
+
+func handleImageMessage(ctx context.Context, evt *events.Message, client *whatsmeow.Client) {
+ if !config.WhatsappAutoDownloadMedia {
+ return
+ }
+ if client == nil {
+ return
+ }
+ if img := evt.Message.GetImageMessage(); img != nil {
+ if path, 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)
+ }
+ }
+}
+
+func handleAutoMarkRead(ctx context.Context, evt *events.Message, client *whatsmeow.Client) {
+ // Only mark read if auto-mark read is enabled and message is incoming
+ if !config.WhatsappAutoMarkRead || evt.Info.IsFromMe {
+ return
+ }
+
+ if client == nil {
+ return
+ }
+
+ // Mark the message as read
+ messageIDs := []types.MessageID{evt.Info.ID}
+ timestamp := time.Now()
+ chat := evt.Info.Chat
+ sender := evt.Info.Sender
+
+ if err := client.MarkRead(ctx, messageIDs, timestamp, chat, sender); err != nil {
+ log.Warnf("Failed to mark message %s as read: %v", evt.Info.ID, err)
+ } else {
+ log.Debugf("Marked message %s as read", evt.Info.ID)
+ }
+}
+
+func handleWebhookForward(ctx context.Context, evt *events.Message, client *whatsmeow.Client) {
+ // Skip webhook for protocol messages that are internal sync messages
+ if protocolMessage := evt.Message.GetProtocolMessage(); protocolMessage != nil {
+ protocolType := protocolMessage.GetType().String()
+ // Only allow REVOKE and MESSAGE_EDIT through - skip all other protocol messages
+ // (HISTORY_SYNC_NOTIFICATION, APP_STATE_SYNC_KEY_SHARE, EPHEMERAL_SYNC_RESPONSE, etc.)
+ switch protocolType {
+ case "REVOKE", "MESSAGE_EDIT":
+ // These are meaningful user actions, allow webhook
+ default:
+ log.Debugf("Skipping webhook for protocol message type: %s", protocolType)
+ return
+ }
+ }
+
+ // Skip webhook for outgoing messages (IsFromMe) to avoid duplicate webhooks
+ // when multiple devices are connected. The sender's device receives an echo
+ // of the sent message, but we only want the recipient's device to trigger webhook.
+ // Note: Protocol messages (REVOKE, MESSAGE_EDIT) are allowed through above.
+ if evt.Info.IsFromMe {
+ log.Debugf("Skipping webhook for outgoing message %s (IsFromMe=true)", evt.Info.ID)
+ return
+ }
+
+ if len(config.WhatsappWebhook) > 0 &&
+ !strings.Contains(evt.Info.SourceString(), "broadcast") {
+ go func(e *events.Message, c *whatsmeow.Client) {
+ webhookCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+ if err := forwardMessageToWebhook(webhookCtx, c, e); err != nil {
+ logrus.Error("Failed forward to webhook: ", err)
+ }
+ }(evt, client)
+ }
+}
diff --git a/src/infrastructure/whatsapp/event_receipt.go b/src/infrastructure/whatsapp/event_receipt.go
index ee0cb947..2d22ebf1 100644
--- a/src/infrastructure/whatsapp/event_receipt.go
+++ b/src/infrastructure/whatsapp/event_receipt.go
@@ -4,6 +4,8 @@ import (
"context"
"time"
+ "github.com/sirupsen/logrus"
+ "go.mau.fi/whatsmeow"
"go.mau.fi/whatsmeow/types"
"go.mau.fi/whatsmeow/types/events"
)
@@ -33,41 +35,65 @@ func getReceiptTypeDescription(evt types.ReceiptType) string {
}
// createReceiptPayload creates a webhook payload for message acknowledgement (receipt) events
-func createReceiptPayload(evt *events.Receipt) map[string]any {
+func createReceiptPayload(ctx context.Context, evt *events.Receipt, deviceID string, client *whatsmeow.Client) map[string]any {
body := make(map[string]any)
-
- // Create payload structure matching the expected format
payload := make(map[string]any)
- // Add message ID (use first message ID if multiple)
+ // Add message IDs
if len(evt.MessageIDs) > 0 {
payload["ids"] = evt.MessageIDs
}
- // Add from field (the chat where the message was sent)
- payload["chat_id"] = evt.Chat
- payload["sender_id"] = evt.Sender
- payload["from"] = evt.SourceString()
+ // Add chat_id
+ payload["chat_id"] = evt.Chat.ToNonAD().String()
+
+ // Build from/from_lid fields from sender
+ senderJID := evt.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()
+ // Receipt type
if evt.Type == types.ReceiptTypeDelivered {
payload["receipt_type"] = "delivered"
} else {
- payload["receipt_type"] = evt.Type
+ payload["receipt_type"] = string(evt.Type)
}
payload["receipt_type_description"] = getReceiptTypeDescription(evt.Type)
- // Wrap in payload structure
- body["payload"] = payload
-
- // Add metadata for webhook processing
+ // Wrap in body structure
body["event"] = "message.ack"
body["timestamp"] = evt.Timestamp.Format(time.RFC3339)
+ if deviceID != "" {
+ body["device_id"] = deviceID
+ }
+ body["payload"] = payload
return body
}
-// forwardReceiptToWebhook forwards message acknowledgement events to the configured webhook URLs
-func forwardReceiptToWebhook(ctx context.Context, evt *events.Receipt) error {
- payload := createReceiptPayload(evt)
+// forwardReceiptToWebhook forwards message acknowledgement events to the configured webhook URLs.
+//
+// IMPORTANT: We only forward receipts from the primary device (Device == 0).
+// WhatsApp sends separate receipt events for each linked device (phone, web, desktop, etc.)
+// of a user. For example, if a user has 3 devices, you would receive 3 "delivered" receipts
+// for the same message. To avoid duplicate webhooks and simplify downstream processing,
+// we only send the receipt from the primary device (Device == 0).
+//
+// If you need receipts from all devices in the future, remove the Device == 0 check below.
+func forwardReceiptToWebhook(ctx context.Context, evt *events.Receipt, deviceID string, client *whatsmeow.Client) error {
+ // Only forward receipts from the primary device to avoid duplicates.
+ // See function comment above for detailed explanation.
+ if evt.Sender.Device != 0 {
+ logrus.Debugf("Skipping receipt webhook for linked device %d (only primary device receipts are forwarded)", evt.Sender.Device)
+ return nil
+ }
+
+ payload := createReceiptPayload(ctx, evt, deviceID, client)
return forwardPayloadToConfiguredWebhooks(ctx, payload, "message ack event")
}
diff --git a/src/infrastructure/whatsapp/history_sync.go b/src/infrastructure/whatsapp/history_sync.go
new file mode 100644
index 00000000..631d7f97
--- /dev/null
+++ b/src/infrastructure/whatsapp/history_sync.go
@@ -0,0 +1,294 @@
+package whatsapp
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "os"
+ "sync/atomic"
+ "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"
+ "go.mau.fi/whatsmeow"
+ "go.mau.fi/whatsmeow/proto/waHistorySync"
+ "go.mau.fi/whatsmeow/types"
+ "go.mau.fi/whatsmeow/types/events"
+)
+
+var historySyncID int32
+
+func handleHistorySync(ctx context.Context, evt *events.HistorySync, chatStorageRepo domainChatStorage.IChatStorageRepository, client *whatsmeow.Client) {
+ if client == nil || client.Store == nil || client.Store.ID == nil {
+ log.Warnf("Skipping history sync handling: WhatsApp client not initialized")
+ return
+ }
+ id := atomic.AddInt32(&historySyncID, 1)
+ fileName := fmt.Sprintf("%s/history-%d-%s-%d-%s.json",
+ config.PathStorages,
+ startupTime,
+ client.Store.ID.String(),
+ id,
+ evt.Data.SyncType.String(),
+ )
+
+ file, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE, 0600)
+ if err != nil {
+ log.Errorf("Failed to open file to write history sync: %v", err)
+ return
+ }
+ defer file.Close()
+
+ enc := json.NewEncoder(file)
+ enc.SetIndent("", " ")
+ if err = enc.Encode(evt.Data); err != nil {
+ log.Errorf("Failed to write history sync: %v", err)
+ return
+ }
+
+ log.Infof("Wrote history sync to %s", fileName)
+
+ // Process history sync data to database
+ if chatStorageRepo != nil {
+ if err := processHistorySync(ctx, evt.Data, chatStorageRepo, client); err != nil {
+ log.Errorf("Failed to process history sync to database: %v", err)
+ }
+ }
+}
+
+// processHistorySync processes history sync data and stores messages in the database
+func processHistorySync(ctx context.Context, data *waHistorySync.HistorySync, chatStorageRepo domainChatStorage.IChatStorageRepository, client *whatsmeow.Client) error {
+ if data == nil {
+ return nil
+ }
+
+ syncType := data.GetSyncType()
+ log.Infof("Processing history sync type: %s", syncType.String())
+
+ switch syncType {
+ case waHistorySync.HistorySync_INITIAL_BOOTSTRAP, waHistorySync.HistorySync_RECENT:
+ // Process conversation messages
+ return processConversationMessages(ctx, data, chatStorageRepo, client)
+ case waHistorySync.HistorySync_PUSH_NAME:
+ // Process push names to update chat names
+ return processPushNames(ctx, data, chatStorageRepo, client)
+ default:
+ // Other sync types are not needed for message storage
+ log.Debugf("Skipping history sync type: %s", syncType.String())
+ return nil
+ }
+}
+
+// processConversationMessages processes and stores conversation messages from history sync
+func processConversationMessages(ctx context.Context, data *waHistorySync.HistorySync, chatStorageRepo domainChatStorage.IChatStorageRepository, client *whatsmeow.Client) error {
+ conversations := data.GetConversations()
+ log.Infof("Processing %d conversations from history sync", len(conversations))
+
+ // Prioritize device JID from context (set by event handler with correct device instance)
+ // over client.Store.ID which may point to a different device in multi-device scenarios
+ deviceID := ""
+ if inst, ok := DeviceFromContext(ctx); ok && inst != nil {
+ deviceID = inst.JID()
+ if deviceID == "" {
+ deviceID = inst.ID()
+ }
+ }
+ if deviceID == "" && client != nil && client.Store != nil && client.Store.ID != nil {
+ deviceID = client.Store.ID.ToNonAD().String()
+ }
+
+ for _, conv := range conversations {
+ rawChatJID := conv.GetID()
+ if rawChatJID == "" {
+ continue
+ }
+
+ // Parse JID to get proper format
+ jid, err := types.ParseJID(rawChatJID)
+ if err != nil {
+ log.Warnf("Failed to parse JID %s: %v", rawChatJID, err)
+ continue
+ }
+
+ // Normalize JID (convert @lid to @s.whatsapp.net if possible)
+ jid = NormalizeJIDFromLID(ctx, jid, client)
+ chatJID := jid.String()
+
+ displayName := conv.GetDisplayName()
+
+ // Get or create chat
+ chatName := chatStorageRepo.GetChatNameWithPushName(jid, chatJID, "", displayName)
+
+ // Extract ephemeral expiration from conversation
+ ephemeralExpiration := conv.GetEphemeralExpiration()
+
+ // Process messages in the conversation
+ messages := conv.GetMessages()
+ log.Debugf("Processing %d messages for chat %s", len(messages), chatJID)
+
+ // Collect messages for batch processing
+ var messageBatch []*domainChatStorage.Message
+ var latestTimestamp time.Time
+
+ for _, histMsg := range messages {
+ if histMsg == nil || histMsg.Message == nil {
+ continue
+ }
+
+ msg := histMsg.Message
+ msgKey := msg.GetKey()
+ if msgKey == nil {
+ continue
+ }
+
+ // Skip messages without ID
+ messageID := msgKey.GetID()
+ if messageID == "" {
+ continue
+ }
+
+ // Extract message content and media info
+ content := utils.ExtractMessageTextFromProto(msg.GetMessage())
+ mediaType, filename, url, mediaKey, fileSHA256, fileEncSHA256, fileLength := utils.ExtractMediaInfo(msg.GetMessage())
+
+ // Skip if there's no content and no media
+ if content == "" && mediaType == "" {
+ continue
+ }
+
+ // Determine sender
+ sender := ""
+ isFromMe := msgKey.GetFromMe()
+ if isFromMe {
+ // For self-messages, use the full JID format to match regular message processing
+ if client != nil && client.Store.ID != nil {
+ sender = client.Store.ID.ToNonAD().String() // Use full JID instead of just User part
+ } else {
+ // Skip messages where we can't determine the sender to avoid NOT NULL violations
+ log.Warnf("Skipping self-message %s: client ID unavailable", messageID)
+ continue
+ }
+ } else {
+ participant := msgKey.GetParticipant()
+ if participant != "" {
+ // For group messages, participant contains the actual sender
+ if senderJID, err := types.ParseJID(participant); err == nil {
+ // Normalize sender JID (convert @lid to @s.whatsapp.net if possible)
+ senderJID = NormalizeJIDFromLID(ctx, senderJID, client)
+ sender = senderJID.ToNonAD().String() // Use full JID format for consistency
+ } else {
+ // Fallback to participant string, but ensure it's not empty
+ if participant != "" {
+ sender = participant
+ } else {
+ log.Warnf("Skipping message %s: empty participant", messageID)
+ continue
+ }
+ }
+ } else {
+ // For individual chats, use the chat JID as sender with full format
+ sender = jid.String() // Use full JID format for consistency
+ }
+ }
+
+ // Convert timestamp from Unix seconds to time.Time
+ // WhatsApp history sync timestamps are in seconds, not milliseconds
+ timestamp := time.Unix(int64(msg.GetMessageTimestamp()), 0)
+
+ // Track latest timestamp
+ if timestamp.After(latestTimestamp) {
+ latestTimestamp = timestamp
+ }
+
+ // Create message object and add to batch
+ message := &domainChatStorage.Message{
+ ID: messageID,
+ ChatJID: chatJID,
+ DeviceID: deviceID,
+ Sender: sender,
+ Content: content,
+ Timestamp: timestamp,
+ IsFromMe: isFromMe,
+ MediaType: mediaType,
+ Filename: filename,
+ URL: url,
+ MediaKey: mediaKey,
+ FileSHA256: fileSHA256,
+ FileEncSHA256: fileEncSHA256,
+ FileLength: fileLength,
+ }
+
+ messageBatch = append(messageBatch, message)
+ }
+
+ // Store or update the chat with latest message time
+ if len(messageBatch) > 0 {
+ chat := &domainChatStorage.Chat{
+ DeviceID: deviceID,
+ JID: chatJID,
+ Name: chatName,
+ LastMessageTime: latestTimestamp,
+ EphemeralExpiration: ephemeralExpiration,
+ }
+
+ // Store or update the chat
+ if err := chatStorageRepo.StoreChat(chat); err != nil {
+ log.Warnf("Failed to store chat %s: %v", chatJID, err)
+ continue
+ }
+
+ // Store messages in batch
+ if err := chatStorageRepo.StoreMessagesBatch(messageBatch); err != nil {
+ log.Warnf("Failed to store messages batch for chat %s: %v", chatJID, err)
+ } else {
+ log.Debugf("Stored %d messages for chat %s", len(messageBatch), chatJID)
+ }
+ }
+ }
+
+ return nil
+}
+
+// processPushNames processes push names from history sync to update chat names
+func processPushNames(ctx context.Context, data *waHistorySync.HistorySync, chatStorageRepo domainChatStorage.IChatStorageRepository, client *whatsmeow.Client) error {
+ pushnames := data.GetPushnames()
+ log.Infof("Processing %d push names from history sync", len(pushnames))
+
+ for _, pushname := range pushnames {
+ rawJIDStr := pushname.GetID()
+ name := pushname.GetPushname()
+
+ if rawJIDStr == "" || name == "" {
+ continue
+ }
+
+ // Parse and normalize JID (convert @lid to @s.whatsapp.net if possible)
+ jid, err := types.ParseJID(rawJIDStr)
+ if err != nil {
+ log.Warnf("Failed to parse JID %s in push names: %v", rawJIDStr, err)
+ continue
+ }
+ jid = NormalizeJIDFromLID(ctx, jid, client)
+ jidStr := jid.String()
+
+ // Check if chat exists
+ existingChat, err := chatStorageRepo.GetChat(jidStr)
+ if err != nil || existingChat == nil {
+ // Chat doesn't exist yet, skip
+ continue
+ }
+
+ // Update chat name if it's different
+ if existingChat.Name != name {
+ existingChat.Name = name
+ if err := chatStorageRepo.StoreChat(existingChat); err != nil {
+ log.Warnf("Failed to update chat name for %s: %v", jidStr, err)
+ } else {
+ log.Debugf("Updated chat name for %s to %s", jidStr, name)
+ }
+ }
+ }
+
+ return nil
+}
diff --git a/src/infrastructure/whatsapp/init.go b/src/infrastructure/whatsapp/init.go
index 3d69d193..82a38ded 100644
--- a/src/infrastructure/whatsapp/init.go
+++ b/src/infrastructure/whatsapp/init.go
@@ -2,32 +2,16 @@ package whatsapp
import (
"context"
- "encoding/json"
"fmt"
- "os"
- "path/filepath"
- "strings"
"sync"
- "sync/atomic"
"time"
- "go.mau.fi/whatsmeow/proto/waHistorySync"
-
"github.com/aldinokemal/go-whatsapp-web-multidevice/config"
domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
- pkgError "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/error"
- "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
- "github.com/aldinokemal/go-whatsapp-web-multidevice/ui/websocket"
- "github.com/sirupsen/logrus"
"go.mau.fi/whatsmeow"
- "go.mau.fi/whatsmeow/appstate"
- "go.mau.fi/whatsmeow/proto/waE2E"
"go.mau.fi/whatsmeow/store"
"go.mau.fi/whatsmeow/store/sqlstore"
- "go.mau.fi/whatsmeow/types"
- "go.mau.fi/whatsmeow/types/events"
waLog "go.mau.fi/whatsmeow/util/log"
- "google.golang.org/protobuf/proto"
)
// Type definitions
@@ -43,67 +27,11 @@ var (
cli *whatsmeow.Client
db *sqlstore.Container // Add global database reference for cleanup
keysDB *sqlstore.Container
+ deviceManager *DeviceManager
log waLog.Logger
- historySyncID int32
startupTime = time.Now().Unix()
)
-// InitWaDB initializes the WhatsApp database connection
-func InitWaDB(ctx context.Context, DBURI string) *sqlstore.Container {
- log = waLog.Stdout("Main", config.WhatsappLogLevel, true)
- dbLog := waLog.Stdout("Database", config.WhatsappLogLevel, true)
-
- storeContainer, err := initDatabase(ctx, dbLog, DBURI)
- if err != nil {
- log.Errorf("Database initialization error: %v", err)
- panic(pkgError.InternalServerError(fmt.Sprintf("Database initialization error: %v", err)))
- }
-
- return storeContainer
-}
-
-// initDatabase creates and returns a database store container based on the configured URI
-func initDatabase(ctx context.Context, dbLog waLog.Logger, DBURI string) (*sqlstore.Container, error) {
- if strings.HasPrefix(DBURI, "file:") {
- return sqlstore.New(ctx, "sqlite3", DBURI, dbLog)
- } else if strings.HasPrefix(DBURI, "postgres:") {
- return sqlstore.New(ctx, "postgres", DBURI, dbLog)
- }
-
- return nil, fmt.Errorf("unknown database type: %s. Currently only sqlite3(file:) and postgres are supported", DBURI)
-}
-
-// NormalizeJIDFromLID converts @lid JIDs to their corresponding @s.whatsapp.net JIDs
-// Returns the original JID if it's not an @lid or if LID lookup fails
-func NormalizeJIDFromLID(ctx context.Context, jid types.JID, client *whatsmeow.Client) types.JID {
- // Only process @lid JIDs
- if jid.Server != "lid" {
- return jid
- }
-
- // Safety check
- if client == nil || client.Store == nil || client.Store.LIDs == nil {
- log.Warnf("Cannot resolve LID %s: client not available", jid.String())
- return jid
- }
-
- // Attempt to get the phone number for this LID
- pn, err := client.Store.LIDs.GetPNForLID(ctx, jid)
- if err != nil {
- log.Debugf("Failed to resolve LID %s to phone number: %v", jid.String(), err)
- return jid
- }
-
- // If we got a valid phone number, use it
- if !pn.IsEmpty() {
- log.Debugf("Resolved LID %s to phone number %s", jid.String(), pn.String())
- return pn
- }
-
- // Fallback to original JID
- return jid
-}
-
func syncKeysDevice(ctx context.Context, db, keysDB *sqlstore.Container) {
if keysDB == nil {
return
@@ -168,16 +96,34 @@ func InitWaCLI(ctx context.Context, storeContainer, keysStoreContainer *sqlstore
device.PrivacyTokens = innerStore
}
+ instanceID := ""
+ if device.ID != nil {
+ instanceID = device.ID.String()
+ }
+
// Create and configure the client with filtered logging to avoid noisy reconnection EOF errors
baseLogger := waLog.Stdout("Client", config.WhatsappLogLevel, true)
client := whatsmeow.NewClient(device, newFilteredLogger(baseLogger))
client.EnableAutoReconnect = true
client.AutoTrustIdentity = true
+ deviceRepo := newDeviceChatStorage(instanceID, chatStorageRepo)
+ instance := NewDeviceInstance(instanceID, client, deviceRepo)
+
client.AddEventHandler(func(rawEvt interface{}) {
- handler(ctx, rawEvt, chatStorageRepo)
+ handler(ctx, instance, rawEvt)
})
+ // Register device instance in the manager for multi-device awareness
+ // Use EnsureDefault to avoid creating duplicates when a device with matching JID already exists
+ if device.ID != nil {
+ instanceID = device.ID.String()
+ }
+ dm := InitializeDeviceManager(storeContainer, keysStoreContainer, deviceRepo)
+ if dm != nil && instanceID != "" {
+ dm.EnsureDefault(instance)
+ }
+
globalStateMu.Lock()
cli = client
db = primaryDB
@@ -186,989 +132,3 @@ func InitWaCLI(ctx context.Context, storeContainer, keysStoreContainer *sqlstore
return client
}
-
-// UpdateGlobalClient updates the global cli variable with a new client instance
-// This is needed when reinitializing the client after logout to ensure all
-// infrastructure code uses the new client instance
-func UpdateGlobalClient(newCli *whatsmeow.Client, newDB *sqlstore.Container) {
- globalStateMu.Lock()
- cli = newCli
- db = newDB
- globalStateMu.Unlock()
- log.Infof("Global WhatsApp client updated successfully")
-}
-
-// GetClient returns the current global client instance (alias for GetGlobalClient)
-func GetClient() *whatsmeow.Client {
- globalStateMu.RLock()
- defer globalStateMu.RUnlock()
- return cli
-}
-
-// Get DB instance
-func GetDB() *sqlstore.Container {
- globalStateMu.RLock()
- defer globalStateMu.RUnlock()
- return db
-}
-
-func getStoreContainers() (*sqlstore.Container, *sqlstore.Container) {
- globalStateMu.RLock()
- defer globalStateMu.RUnlock()
- return db, keysDB
-}
-
-// GetConnectionStatus returns the current connection status of the global client
-func GetConnectionStatus() (isConnected bool, isLoggedIn bool, deviceID string) {
- globalStateMu.RLock()
- currentClient := cli
- globalStateMu.RUnlock()
- if currentClient == nil {
- return false, false, ""
- }
-
- isConnected = currentClient.IsConnected()
- isLoggedIn = currentClient.IsLoggedIn()
-
- if currentClient.Store != nil && currentClient.Store.ID != nil {
- deviceID = currentClient.Store.ID.String()
- }
-
- return isConnected, isLoggedIn, deviceID
-}
-
-// CleanupDatabase removes the database file (SQLite) or deletes all devices (PostgreSQL) to prevent foreign key constraint issues
-func CleanupDatabase() error {
- globalStateMu.RLock()
- currentDB := db
- currentKeysDB := keysDB
- globalStateMu.RUnlock()
-
- // Check if using PostgreSQL
- if strings.HasPrefix(config.DBURI, "postgres:") {
- logrus.Info("[CLEANUP] PostgreSQL detected - deleting all devices from database")
-
- // Check if database is initialized
- if currentDB == nil {
- logrus.Warn("[CLEANUP] Database is nil, skipping device deletion")
- return nil
- }
-
- ctx := context.Background()
-
- // Get all devices
- devices, err := currentDB.GetAllDevices(ctx)
- if err != nil {
- logrus.Errorf("[CLEANUP] Error getting devices: %v", err)
- return fmt.Errorf("failed to get devices: %v", err)
- }
-
- logrus.Infof("[CLEANUP] Found %d devices to delete", len(devices))
-
- // Delete each device (this will cascade delete related records like identity keys, sessions, etc.)
- for _, device := range devices {
- logrus.Infof("[CLEANUP] Deleting device: %s", device.ID)
- if err := currentDB.DeleteDevice(ctx, device); err != nil {
- logrus.Errorf("[CLEANUP] Error deleting device %s: %v", device.ID, err)
- return fmt.Errorf("failed to delete device %s: %v", device.ID, err)
- }
- }
-
- // Also clean up keysDB if it exists and is separate
- if currentKeysDB != nil && currentKeysDB != currentDB {
- keysDevices, err := currentKeysDB.GetAllDevices(ctx)
- if err != nil {
- logrus.Errorf("[CLEANUP] Error getting devices from keysDB: %v", err)
- return fmt.Errorf("failed to get devices from keysDB: %v", err)
- }
-
- logrus.Infof("[CLEANUP] Found %d devices in keysDB to delete", len(keysDevices))
-
- for _, device := range keysDevices {
- logrus.Infof("[CLEANUP] Deleting device from keysDB: %s", device.ID)
- if err := currentKeysDB.DeleteDevice(ctx, device); err != nil {
- logrus.Errorf("[CLEANUP] Error deleting device %s from keysDB: %v", device.ID, err)
- return fmt.Errorf("failed to delete device %s from keysDB: %v", device.ID, err)
- }
- }
- }
-
- logrus.Info("[CLEANUP] All devices deleted successfully from PostgreSQL")
- return nil
- }
-
- // SQLite: Close database connections before removing the file
- logrus.Info("[CLEANUP] SQLite detected - closing database connections before file removal")
-
- // Close the main database connection
- if db != nil {
- logrus.Info("[CLEANUP] Closing main database connection")
- if err := db.Close(); err != nil {
- logrus.Errorf("[CLEANUP] Error closing main database: %v", err)
- return fmt.Errorf("failed to close main database: %v", err)
- }
- logrus.Info("[CLEANUP] Main database connection closed successfully")
- }
-
- // Close keysDB if it exists and is separate from main db
- if keysDB != nil && keysDB != db {
- logrus.Info("[CLEANUP] Closing keysDB database connection")
- if err := keysDB.Close(); err != nil {
- logrus.Errorf("[CLEANUP] Error closing keysDB: %v", err)
- return fmt.Errorf("failed to close keysDB: %v", err)
- }
- logrus.Info("[CLEANUP] KeysDB connection closed successfully")
-
- // Remove keysDB file if it's also SQLite
- if config.DBKeysURI != "" && strings.HasPrefix(config.DBKeysURI, "file:") {
- keysDBPath := strings.TrimPrefix(config.DBKeysURI, "file:")
- if strings.Contains(keysDBPath, "?") {
- keysDBPath = strings.Split(keysDBPath, "?")[0]
- }
-
- logrus.Infof("[CLEANUP] Removing keysDB file: %s", keysDBPath)
- if err := os.Remove(keysDBPath); err != nil {
- if !os.IsNotExist(err) {
- logrus.Errorf("[CLEANUP] Error removing keysDB file: %v", err)
- return fmt.Errorf("failed to remove keysDB file: %v", err)
- } else {
- logrus.Info("[CLEANUP] KeysDB file already removed")
- }
- } else {
- logrus.Info("[CLEANUP] KeysDB file removed successfully")
- }
- }
- }
-
- // Now remove the main database file
- dbPath := strings.TrimPrefix(config.DBURI, "file:")
- if strings.Contains(dbPath, "?") {
- dbPath = strings.Split(dbPath, "?")[0]
- }
-
- logrus.Infof("[CLEANUP] Removing main database file: %s", dbPath)
- if err := os.Remove(dbPath); err != nil {
- if !os.IsNotExist(err) {
- logrus.Errorf("[CLEANUP] Error removing database file: %v", err)
- return err
- } else {
- logrus.Info("[CLEANUP] Database file already removed")
- }
- } else {
- logrus.Info("[CLEANUP] Database file removed successfully")
- }
- return nil
-}
-
-// CleanupTemporaryFiles removes history files, QR images, and send items
-func CleanupTemporaryFiles() error {
- // Clean up history files
- if files, err := filepath.Glob(fmt.Sprintf("./%s/history-*", config.PathStorages)); err == nil {
- for _, f := range files {
- if err := os.Remove(f); err != nil {
- logrus.Errorf("[CLEANUP] Error removing history file %s: %v", f, err)
- return err
- }
- }
- logrus.Info("[CLEANUP] History files cleaned up")
- }
-
- // Clean up QR images
- if qrImages, err := filepath.Glob(fmt.Sprintf("./%s/scan-*", config.PathQrCode)); err == nil {
- for _, f := range qrImages {
- if err := os.Remove(f); err != nil {
- logrus.Errorf("[CLEANUP] Error removing QR image %s: %v", f, err)
- return err
- }
- }
- logrus.Info("[CLEANUP] QR images cleaned up")
- }
-
- // Clean up send items
- if qrItems, err := filepath.Glob(fmt.Sprintf("./%s/*", config.PathSendItems)); err == nil {
- for _, f := range qrItems {
- if !strings.Contains(f, ".gitignore") {
- if err := os.Remove(f); err != nil {
- logrus.Errorf("[CLEANUP] Error removing send item %s: %v", f, err)
- return err
- }
- }
- }
- logrus.Info("[CLEANUP] Send items cleaned up")
- }
-
- return nil
-}
-
-// ReinitializeWhatsAppComponents reinitializes database and client components
-func ReinitializeWhatsAppComponents(ctx context.Context, chatStorageRepo domainChatStorage.IChatStorageRepository) (*sqlstore.Container, *whatsmeow.Client, error) {
- logrus.Info("[CLEANUP] Reinitializing database and client...")
-
- newDB := InitWaDB(ctx, config.DBURI)
- var newKeysDB *sqlstore.Container
- if config.DBKeysURI != "" {
- newKeysDB = InitWaDB(ctx, config.DBKeysURI)
- }
- newCli := InitWaCLI(ctx, newDB, newKeysDB, chatStorageRepo)
-
- logrus.Info("[CLEANUP] Database and client reinitialized successfully")
-
- return newDB, newCli, nil
-}
-
-// PerformCompleteCleanup performs all cleanup operations in the correct order
-func PerformCompleteCleanup(ctx context.Context, logPrefix string, chatStorageRepo domainChatStorage.IChatStorageRepository) (*sqlstore.Container, *whatsmeow.Client, error) {
- logrus.Infof("[%s] Starting complete cleanup process...", logPrefix)
-
- // Disconnect current client if it exists
- if current := GetClient(); current != nil {
- current.Disconnect()
- logrus.Infof("[%s] Client disconnected", logPrefix)
- }
-
- // Truncate all chatstorage data before other cleanup
- if chatStorageRepo != nil {
- logrus.Infof("[%s] Truncating chatstorage data...", logPrefix)
- if err := chatStorageRepo.TruncateAllDataWithLogging(logPrefix); err != nil {
- logrus.Errorf("[%s] Failed to truncate chatstorage data: %v", logPrefix, err)
- // Continue with cleanup even if chatstorage truncation fails
- }
- }
-
- // Clean up database
- if err := CleanupDatabase(); err != nil {
- return nil, nil, fmt.Errorf("database cleanup failed: %v", err)
- }
-
- // Reinitialize components
- newDB, newCli, err := ReinitializeWhatsAppComponents(ctx, chatStorageRepo)
- if err != nil {
- return nil, nil, fmt.Errorf("reinitialization failed: %v", err)
- }
-
- // Clean up temporary files
- if err := CleanupTemporaryFiles(); err != nil {
- logrus.Errorf("[%s] Temporary file cleanup failed (non-critical): %v", logPrefix, err)
- // Don't return error for file cleanup as it's non-critical
- }
-
- logrus.Infof("[%s] Complete cleanup process finished successfully", logPrefix)
- logrus.Infof("[%s] Application is ready for next login without restart", logPrefix)
-
- return newDB, newCli, nil
-}
-
-// PerformCleanupAndUpdateGlobals is a convenience function that performs cleanup
-// and ensures global client synchronization
-func PerformCleanupAndUpdateGlobals(ctx context.Context, logPrefix string, chatStorageRepo domainChatStorage.IChatStorageRepository) (*sqlstore.Container, *whatsmeow.Client, error) {
- newDB, newCli, err := PerformCompleteCleanup(ctx, logPrefix, chatStorageRepo)
- if err != nil {
- return nil, nil, err
- }
-
- // Ensure global client is properly synchronized
- UpdateGlobalClient(newCli, newDB)
-
- return newDB, newCli, nil
-}
-
-// handleRemoteLogout performs cleanup when user logs out from their phone
-func handleRemoteLogout(ctx context.Context, chatStorageRepo domainChatStorage.IChatStorageRepository) {
- logrus.Info("[REMOTE_LOGOUT] User logged out from phone - starting cleanup...")
- logrus.Info("[REMOTE_LOGOUT] This will clear all WhatsApp session data and chat storage")
-
- // Log database state before cleanup
- if database := GetDB(); database != nil {
- devices, dbErr := database.GetAllDevices(ctx)
- if dbErr != nil {
- logrus.Errorf("[REMOTE_LOGOUT] Error getting devices before cleanup: %v", dbErr)
- } else {
- logrus.Infof("[REMOTE_LOGOUT] Devices before cleanup: %d found", len(devices))
- }
- }
-
- // Perform complete cleanup with global client synchronization
- _, _, err := PerformCleanupAndUpdateGlobals(ctx, "REMOTE_LOGOUT", chatStorageRepo)
- if err != nil {
- logrus.Errorf("[REMOTE_LOGOUT] Cleanup failed: %v", err)
- return
- }
-
- logrus.Info("[REMOTE_LOGOUT] Remote logout cleanup completed successfully")
-}
-
-// handler is the main event handler for WhatsApp events
-func handler(ctx context.Context, rawEvt any, chatStorageRepo domainChatStorage.IChatStorageRepository) {
- switch evt := rawEvt.(type) {
- case *events.DeleteForMe:
- handleDeleteForMe(ctx, evt, chatStorageRepo)
- case *events.AppStateSyncComplete:
- handleAppStateSyncComplete(ctx, evt)
- case *events.PairSuccess:
- handlePairSuccess(ctx, evt)
- case *events.LoggedOut:
- handleLoggedOut(ctx, chatStorageRepo)
- case *events.Connected, *events.PushNameSetting:
- handleConnectionEvents(ctx)
- case *events.StreamReplaced:
- handleStreamReplaced(ctx)
- case *events.Message:
- handleMessage(ctx, evt, chatStorageRepo)
- case *events.Receipt:
- handleReceipt(ctx, evt)
- case *events.Presence:
- handlePresence(ctx, evt)
- case *events.HistorySync:
- handleHistorySync(ctx, evt, chatStorageRepo)
- case *events.AppState:
- handleAppState(ctx, evt)
- case *events.GroupInfo:
- handleGroupInfo(ctx, evt)
- }
-}
-
-// Event handler functions
-
-func handleDeleteForMe(ctx context.Context, evt *events.DeleteForMe, chatStorageRepo domainChatStorage.IChatStorageRepository) {
- log.Infof("Deleted message %s for %s", evt.MessageID, evt.SenderJID.String())
-
- // Find the message to get its chat JID
- message, err := chatStorageRepo.GetMessageByID(evt.MessageID)
- if err != nil {
- log.Errorf("Failed to find message %s for deletion: %v", evt.MessageID, err)
- return
- }
-
- if message == nil {
- log.Warnf("Message %s not found in database, skipping deletion", evt.MessageID)
- return
- }
-
- // Delete the message from database
- if err := chatStorageRepo.DeleteMessage(evt.MessageID, message.ChatJID); err != nil {
- log.Errorf("Failed to delete message %s from database: %v", evt.MessageID, err)
- } else {
- log.Infof("Successfully deleted message %s from database", evt.MessageID)
- }
-
- // Send webhook notification for delete event
- if len(config.WhatsappWebhook) > 0 {
- go func() {
- if err := forwardDeleteToWebhook(ctx, evt, message); err != nil {
- log.Errorf("Failed to forward delete event to webhook: %v", err)
- }
- }()
- }
-}
-
-func handleAppStateSyncComplete(_ context.Context, evt *events.AppStateSyncComplete) {
- client := GetClient()
- if client == nil {
- return
- }
- if len(client.Store.PushName) > 0 && evt.Name == appstate.WAPatchCriticalBlock {
- if err := client.SendPresence(context.Background(), types.PresenceAvailable); err != nil {
- log.Warnf("Failed to send available presence: %v", err)
- } else {
- log.Infof("Marked self as available")
- }
- }
-}
-
-func handlePairSuccess(ctx context.Context, evt *events.PairSuccess) {
- websocket.Broadcast <- websocket.BroadcastMessage{
- Code: "LOGIN_SUCCESS",
- Message: fmt.Sprintf("Successfully pair with %s", evt.ID.String()),
- }
- primaryDB, secondaryDB := getStoreContainers()
- syncKeysDevice(ctx, primaryDB, secondaryDB)
-}
-
-func handleLoggedOut(ctx context.Context, chatStorageRepo domainChatStorage.IChatStorageRepository) {
- logrus.Warn("[REMOTE_LOGOUT] Received LoggedOut event - user logged out from phone")
-
- // Perform comprehensive cleanup
- handleRemoteLogout(ctx, chatStorageRepo)
-
- // Broadcast final notification that cleanup is complete and ready for new login
- websocket.Broadcast <- websocket.BroadcastMessage{
- Code: "LOGOUT_COMPLETE",
- Message: "Remote logout cleanup completed - ready for new login",
- Result: nil,
- }
-}
-
-func handleConnectionEvents(_ context.Context) {
- client := GetClient()
- if client == nil {
- return
- }
- if len(client.Store.PushName) == 0 {
- return
- }
-
- // Send presence available when connecting and when the pushname is changed.
- // This makes sure that outgoing messages always have the right pushname.
- if err := client.SendPresence(context.Background(), types.PresenceAvailable); err != nil {
- log.Warnf("Failed to send available presence: %v", err)
- } else {
- log.Infof("Marked self as available")
- }
-}
-
-func handleStreamReplaced(_ context.Context) {
- os.Exit(0)
-}
-
-func handleMessage(ctx context.Context, evt *events.Message, chatStorageRepo domainChatStorage.IChatStorageRepository) {
- // Log message metadata
- metaParts := buildMessageMetaParts(evt)
- log.Infof("Received message %s from %s (%s): %+v",
- evt.Info.ID,
- evt.Info.SourceString(),
- strings.Join(metaParts, ", "),
- evt.Message,
- )
-
- if err := chatStorageRepo.CreateMessage(ctx, evt); err != nil {
- // Log storage errors to avoid silent failures that could lead to data loss
- log.Errorf("Failed to store incoming message %s: %v", evt.Info.ID, err)
- }
-
- // Handle image message if present
- handleImageMessage(ctx, evt)
-
- // Auto-mark message as read if configured
- handleAutoMarkRead(ctx, evt)
-
- // Handle auto-reply if configured
- handleAutoReply(ctx, evt, chatStorageRepo)
-
- // Forward to webhook if configured
- handleWebhookForward(ctx, evt)
-}
-
-func buildMessageMetaParts(evt *events.Message) []string {
- metaParts := []string{
- fmt.Sprintf("pushname: %s", evt.Info.PushName),
- fmt.Sprintf("timestamp: %s", evt.Info.Timestamp),
- }
- if evt.Info.Type != "" {
- metaParts = append(metaParts, fmt.Sprintf("type: %s", evt.Info.Type))
- }
- if evt.Info.Category != "" {
- metaParts = append(metaParts, fmt.Sprintf("category: %s", evt.Info.Category))
- }
- if evt.IsViewOnce {
- metaParts = append(metaParts, "view once")
- }
- return metaParts
-}
-
-func handleImageMessage(ctx context.Context, evt *events.Message) {
- if !config.WhatsappAutoDownloadMedia {
- return
- }
- client := GetClient()
- if client == nil {
- return
- }
- if img := evt.Message.GetImageMessage(); img != nil {
- if path, 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)
- }
- }
-}
-
-func handleAutoMarkRead(_ context.Context, evt *events.Message) {
- // Only mark read if auto-mark read is enabled and message is incoming
- if !config.WhatsappAutoMarkRead || evt.Info.IsFromMe {
- return
- }
-
- client := GetClient()
- if client == nil {
- return
- }
-
- // Mark the message as read
- messageIDs := []types.MessageID{evt.Info.ID}
- timestamp := time.Now()
- chat := evt.Info.Chat
- sender := evt.Info.Sender
-
- if err := client.MarkRead(context.Background(), messageIDs, timestamp, chat, sender); err != nil {
- log.Warnf("Failed to mark message %s as read: %v", evt.Info.ID, err)
- } else {
- log.Debugf("Marked message %s as read", evt.Info.ID)
- }
-}
-
-func handleAutoReply(ctx context.Context, evt *events.Message, chatStorageRepo domainChatStorage.IChatStorageRepository) {
- if config.WhatsappAutoReplyMessage == "" {
- return
- }
-
- client := GetClient()
- if client == nil {
- return
- }
-
- // Skip groups, broadcasts, and self messages
- if utils.IsGroupJID(evt.Info.Chat.String()) || evt.Info.IsIncomingBroadcast() || evt.Info.IsFromMe {
- return
- }
-
- // Only reply to direct 1:1 chats (e.g., *@s.whatsapp.net)
- if evt.Info.Chat.Server != types.DefaultUserServer {
- return
- }
-
- // Extra safety: skip any broadcast/status contexts
- source := evt.Info.SourceString()
- if strings.Contains(source, "broadcast") ||
- strings.HasSuffix(evt.Info.Chat.String(), "@broadcast") ||
- strings.HasPrefix(evt.Info.Chat.String(), "status@") {
- return
- }
-
- // 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
- }
-
- // Check for genuine typed text on the unwrapped content
- if conv := innerMsg.GetConversation(); conv != "" {
- hasText = true
- } else if ext := innerMsg.GetExtendedTextMessage(); ext != nil && ext.GetText() != "" {
- hasText = true
- } else if protoMsg := innerMsg.GetProtocolMessage(); protoMsg != nil {
- if edited := protoMsg.GetEditedMessage(); edited != nil {
- if ext := edited.GetExtendedTextMessage(); ext != nil && ext.GetText() != "" {
- hasText = true
- } else if conv := edited.GetConversation(); conv != "" {
- hasText = true
- }
- }
- }
- if !hasText {
- return
- }
-
- // Format recipient JID
- recipientJID := utils.FormatJID(evt.Info.Sender.String())
-
- // Send the auto-reply message
- response, err := client.SendMessage(
- ctx,
- recipientJID,
- &waE2E.Message{Conversation: proto.String(config.WhatsappAutoReplyMessage)},
- )
-
- if err != nil {
- log.Errorf("Failed to send auto-reply message: %v", err)
- return
- }
-
- // Store the auto-reply message in chat storage if send was successful
- if chatStorageRepo != nil {
- // Get our own JID as sender
- senderJID := ""
- if client.Store.ID != nil {
- senderJID = client.Store.ID.String()
- }
-
- // Store the sent auto-reply message
- if err := chatStorageRepo.StoreSentMessageWithContext(
- ctx,
- response.ID, // Message ID from WhatsApp response
- senderJID, // Our JID as sender
- recipientJID.String(), // Recipient JID
- config.WhatsappAutoReplyMessage, // Auto-reply content
- response.Timestamp, // Timestamp from response
- ); err != nil {
- // Log storage error but don't fail the auto-reply
- log.Errorf("Failed to store auto-reply message in chat storage: %v", err)
- } else {
- log.Debugf("Auto-reply message %s stored successfully in chat storage", response.ID)
- }
- }
-}
-
-func handleWebhookForward(ctx context.Context, evt *events.Message) {
- // Skip webhook for specific protocol messages that shouldn't trigger webhooks
- if protocolMessage := evt.Message.GetProtocolMessage(); protocolMessage != nil {
- protocolType := protocolMessage.GetType().String()
- // Skip EPHEMERAL_SYNC_RESPONSE but allow REVOKE and MESSAGE_EDIT
- if protocolType == "EPHEMERAL_SYNC_RESPONSE" {
- log.Debugf("Skipping webhook for EPHEMERAL_SYNC_RESPONSE message")
- return
- }
- }
-
- if len(config.WhatsappWebhook) > 0 &&
- !strings.Contains(evt.Info.SourceString(), "broadcast") {
- go func(evt *events.Message) {
- if err := forwardMessageToWebhook(ctx, evt); err != nil {
- logrus.Error("Failed forward to webhook: ", err)
- }
- }(evt)
- }
-}
-
-func handleReceipt(ctx context.Context, evt *events.Receipt) {
- sendReceipt := false
- switch evt.Type {
- case types.ReceiptTypeRead, types.ReceiptTypeReadSelf:
- sendReceipt = true
- log.Infof("%v was read by %s at %s: %+v", evt.MessageIDs, evt.SourceString(), evt.Timestamp, evt)
- case types.ReceiptTypeDelivered:
- sendReceipt = true
- log.Infof("%s was delivered to %s at %s: %+v", evt.MessageIDs[0], evt.SourceString(), evt.Timestamp, evt)
- }
-
- // Forward receipt (ack) event to webhook if configured
- // Note: Receipt events are not rate limited as they are critical for message delivery status
- if len(config.WhatsappWebhook) > 0 && sendReceipt {
- go func(e *events.Receipt) {
- if err := forwardReceiptToWebhook(ctx, e); err != nil {
- logrus.Errorf("Failed to forward ack event to webhook: %v", err)
- }
- }(evt)
- }
-}
-
-func handlePresence(_ context.Context, evt *events.Presence) {
- if evt.Unavailable {
- if evt.LastSeen.IsZero() {
- log.Infof("%s is now offline", evt.From)
- } else {
- log.Infof("%s is now offline (last seen: %s)", evt.From, evt.LastSeen)
- }
- } else {
- log.Infof("%s is now online", evt.From)
- }
-}
-
-func handleHistorySync(ctx context.Context, evt *events.HistorySync, chatStorageRepo domainChatStorage.IChatStorageRepository) {
- client := GetClient()
- if client == nil || client.Store == nil || client.Store.ID == nil {
- log.Warnf("Skipping history sync handling: WhatsApp client not initialized")
- return
- }
- id := atomic.AddInt32(&historySyncID, 1)
- fileName := fmt.Sprintf("%s/history-%d-%s-%d-%s.json",
- config.PathStorages,
- startupTime,
- client.Store.ID.String(),
- id,
- evt.Data.SyncType.String(),
- )
-
- file, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE, 0600)
- if err != nil {
- log.Errorf("Failed to open file to write history sync: %v", err)
- return
- }
- defer file.Close()
-
- enc := json.NewEncoder(file)
- enc.SetIndent("", " ")
- if err = enc.Encode(evt.Data); err != nil {
- log.Errorf("Failed to write history sync: %v", err)
- return
- }
-
- log.Infof("Wrote history sync to %s", fileName)
-
- // Process history sync data to database
- if chatStorageRepo != nil {
- if err := processHistorySync(ctx, evt.Data, chatStorageRepo); err != nil {
- log.Errorf("Failed to process history sync to database: %v", err)
- }
- }
-}
-
-func handleAppState(_ context.Context, evt *events.AppState) {
- log.Debugf("App state event: %+v / %+v", evt.Index, evt.SyncActionValue)
-}
-
-// processHistorySync processes history sync data and stores messages in the database
-func processHistorySync(ctx context.Context, data *waHistorySync.HistorySync, chatStorageRepo domainChatStorage.IChatStorageRepository) error {
- if data == nil {
- return nil
- }
-
- syncType := data.GetSyncType()
- log.Infof("Processing history sync type: %s", syncType.String())
-
- switch syncType {
- case waHistorySync.HistorySync_INITIAL_BOOTSTRAP, waHistorySync.HistorySync_RECENT:
- // Process conversation messages
- return processConversationMessages(ctx, data, chatStorageRepo)
- case waHistorySync.HistorySync_PUSH_NAME:
- // Process push names to update chat names
- return processPushNames(ctx, data, chatStorageRepo)
- default:
- // Other sync types are not needed for message storage
- log.Debugf("Skipping history sync type: %s", syncType.String())
- return nil
- }
-}
-
-// processConversationMessages processes and stores conversation messages from history sync
-func processConversationMessages(ctx context.Context, data *waHistorySync.HistorySync, chatStorageRepo domainChatStorage.IChatStorageRepository) error {
- conversations := data.GetConversations()
- log.Infof("Processing %d conversations from history sync", len(conversations))
-
- client := GetClient()
-
- for _, conv := range conversations {
- rawChatJID := conv.GetID()
- if rawChatJID == "" {
- continue
- }
-
- // Parse JID to get proper format
- jid, err := types.ParseJID(rawChatJID)
- if err != nil {
- log.Warnf("Failed to parse JID %s: %v", rawChatJID, err)
- continue
- }
-
- // Normalize JID (convert @lid to @s.whatsapp.net if possible)
- jid = NormalizeJIDFromLID(ctx, jid, client)
- chatJID := jid.String()
-
- displayName := conv.GetDisplayName()
-
- // Get or create chat
- chatName := chatStorageRepo.GetChatNameWithPushName(jid, chatJID, "", displayName)
-
- // Extract ephemeral expiration from conversation
- ephemeralExpiration := conv.GetEphemeralExpiration()
-
- // Process messages in the conversation
- messages := conv.GetMessages()
- log.Debugf("Processing %d messages for chat %s", len(messages), chatJID)
-
- // Collect messages for batch processing
- var messageBatch []*domainChatStorage.Message
- var latestTimestamp time.Time
-
- for _, histMsg := range messages {
- if histMsg == nil || histMsg.Message == nil {
- continue
- }
-
- msg := histMsg.Message
- msgKey := msg.GetKey()
- if msgKey == nil {
- continue
- }
-
- // Skip messages without ID
- messageID := msgKey.GetID()
- if messageID == "" {
- continue
- }
-
- // Extract message content and media info
- content := utils.ExtractMessageTextFromProto(msg.GetMessage())
- mediaType, filename, url, mediaKey, fileSHA256, fileEncSHA256, fileLength := utils.ExtractMediaInfo(msg.GetMessage())
-
- // Skip if there's no content and no media
- if content == "" && mediaType == "" {
- continue
- }
-
- // Determine sender
- sender := ""
- isFromMe := msgKey.GetFromMe()
- if isFromMe {
- // For self-messages, use the full JID format to match regular message processing
- if client != nil && client.Store.ID != nil {
- sender = client.Store.ID.String() // Use full JID instead of just User part
- } else {
- // Skip messages where we can't determine the sender to avoid NOT NULL violations
- log.Warnf("Skipping self-message %s: client ID unavailable", messageID)
- continue
- }
- } else {
- participant := msgKey.GetParticipant()
- if participant != "" {
- // For group messages, participant contains the actual sender
- if senderJID, err := types.ParseJID(participant); err == nil {
- // Normalize sender JID (convert @lid to @s.whatsapp.net if possible)
- senderJID = NormalizeJIDFromLID(ctx, senderJID, client)
- sender = senderJID.String() // Use full JID format for consistency
- } else {
- // Fallback to participant string, but ensure it's not empty
- if participant != "" {
- sender = participant
- } else {
- log.Warnf("Skipping message %s: empty participant", messageID)
- continue
- }
- }
- } else {
- // For individual chats, use the chat JID as sender with full format
- sender = jid.String() // Use full JID format for consistency
- }
- }
-
- // Convert timestamp from Unix seconds to time.Time
- // WhatsApp history sync timestamps are in seconds, not milliseconds
- timestamp := time.Unix(int64(msg.GetMessageTimestamp()), 0)
-
- // Track latest timestamp
- if timestamp.After(latestTimestamp) {
- latestTimestamp = timestamp
- }
-
- // Create message object and add to batch
- message := &domainChatStorage.Message{
- ID: messageID,
- ChatJID: chatJID,
- Sender: sender,
- Content: content,
- Timestamp: timestamp,
- IsFromMe: isFromMe,
- MediaType: mediaType,
- Filename: filename,
- URL: url,
- MediaKey: mediaKey,
- FileSHA256: fileSHA256,
- FileEncSHA256: fileEncSHA256,
- FileLength: fileLength,
- }
-
- messageBatch = append(messageBatch, message)
- }
-
- // Store or update the chat with latest message time
- if len(messageBatch) > 0 {
- chat := &domainChatStorage.Chat{
- JID: chatJID,
- Name: chatName,
- LastMessageTime: latestTimestamp,
- EphemeralExpiration: ephemeralExpiration,
- }
-
- // Store or update the chat
- if err := chatStorageRepo.StoreChat(chat); err != nil {
- log.Warnf("Failed to store chat %s: %v", chatJID, err)
- continue
- }
-
- // Store messages in batch
- if err := chatStorageRepo.StoreMessagesBatch(messageBatch); err != nil {
- log.Warnf("Failed to store messages batch for chat %s: %v", chatJID, err)
- } else {
- log.Debugf("Stored %d messages for chat %s", len(messageBatch), chatJID)
- }
- }
- }
-
- return nil
-}
-
-// processPushNames processes push names from history sync to update chat names
-func processPushNames(ctx context.Context, data *waHistorySync.HistorySync, chatStorageRepo domainChatStorage.IChatStorageRepository) error {
- pushnames := data.GetPushnames()
- log.Infof("Processing %d push names from history sync", len(pushnames))
-
- client := GetClient()
-
- for _, pushname := range pushnames {
- rawJIDStr := pushname.GetID()
- name := pushname.GetPushname()
-
- if rawJIDStr == "" || name == "" {
- continue
- }
-
- // Parse and normalize JID (convert @lid to @s.whatsapp.net if possible)
- jid, err := types.ParseJID(rawJIDStr)
- if err != nil {
- log.Warnf("Failed to parse JID %s in push names: %v", rawJIDStr, err)
- continue
- }
- jid = NormalizeJIDFromLID(ctx, jid, client)
- jidStr := jid.String()
-
- // Check if chat exists
- existingChat, err := chatStorageRepo.GetChat(jidStr)
- if err != nil || existingChat == nil {
- // Chat doesn't exist yet, skip
- continue
- }
-
- // Update chat name if it's different
- if existingChat.Name != name {
- existingChat.Name = name
- if err := chatStorageRepo.StoreChat(existingChat); err != nil {
- log.Warnf("Failed to update chat name for %s: %v", jidStr, err)
- } else {
- log.Debugf("Updated chat name for %s to %s", jidStr, name)
- }
- }
- }
-
- return nil
-}
-
-func handleGroupInfo(ctx context.Context, evt *events.GroupInfo) {
- // Only process events that have actual changes
- hasChanges := len(evt.Join) > 0 || len(evt.Leave) > 0 || len(evt.Promote) > 0 || len(evt.Demote) > 0 ||
- evt.Name != nil || evt.Topic != nil || evt.Locked != nil || evt.Announce != nil
-
- if !hasChanges {
- return
- }
-
- // Log group events for debugging
- if len(evt.Join) > 0 {
- log.Infof("Group %s: %d users joined at %s", evt.JID, len(evt.Join), evt.Timestamp)
- }
- if len(evt.Leave) > 0 {
- log.Infof("Group %s: %d users left at %s", evt.JID, len(evt.Leave), evt.Timestamp)
- }
- if len(evt.Promote) > 0 {
- log.Infof("Group %s: %d users promoted at %s", evt.JID, len(evt.Promote), evt.Timestamp)
- }
- if len(evt.Demote) > 0 {
- log.Infof("Group %s: %d users demoted at %s", evt.JID, len(evt.Demote), evt.Timestamp)
- }
-
- // Forward group info event to webhook if configured
- if len(config.WhatsappWebhook) > 0 {
- go func(e *events.GroupInfo) {
- if err := forwardGroupInfoToWebhook(ctx, e); err != nil {
- logrus.Errorf("Failed to forward group info event to webhook: %v", err)
- }
- }(evt)
- }
-}
diff --git a/src/infrastructure/whatsapp/jid_utils.go b/src/infrastructure/whatsapp/jid_utils.go
new file mode 100644
index 00000000..6718f890
--- /dev/null
+++ b/src/infrastructure/whatsapp/jid_utils.go
@@ -0,0 +1,39 @@
+package whatsapp
+
+import (
+ "context"
+
+ "go.mau.fi/whatsmeow"
+ "go.mau.fi/whatsmeow/types"
+)
+
+// NormalizeJIDFromLID converts @lid JIDs to their corresponding @s.whatsapp.net JIDs
+// Returns the original JID if it's not an @lid or if LID lookup fails
+func NormalizeJIDFromLID(ctx context.Context, jid types.JID, client *whatsmeow.Client) types.JID {
+ // Only process @lid JIDs
+ if jid.Server != "lid" {
+ return jid
+ }
+
+ // Safety check
+ if client == nil || client.Store == nil || client.Store.LIDs == nil {
+ log.Warnf("Cannot resolve LID %s: client not available", jid.String())
+ return jid
+ }
+
+ // Attempt to get the phone number for this LID
+ pn, err := client.Store.LIDs.GetPNForLID(ctx, jid)
+ if err != nil {
+ log.Debugf("Failed to resolve LID %s to phone number: %v", jid.String(), err)
+ return jid
+ }
+
+ // If we got a valid phone number, use it
+ if !pn.IsEmpty() {
+ log.Debugf("Resolved LID %s to phone number %s", jid.String(), pn.String())
+ return pn
+ }
+
+ // Fallback to original JID
+ return jid
+}
diff --git a/src/ui/mcp/app.go b/src/ui/mcp/app.go
index 801e2eee..020dcdcb 100644
--- a/src/ui/mcp/app.go
+++ b/src/ui/mcp/app.go
@@ -8,7 +8,6 @@ import (
"strings"
domainApp "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/app"
- "github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/whatsapp"
"github.com/mark3labs/mcp-go/mcp"
"github.com/mark3labs/mcp-go/server"
)
@@ -41,14 +40,20 @@ func (h *AppHandler) toolConnectionStatus() mcp.Tool {
}
func (h *AppHandler) handleConnectionStatus(_ context.Context, _ mcp.CallToolRequest) (*mcp.CallToolResult, error) {
- isConnected, isLoggedIn, deviceID := whatsapp.GetConnectionStatus()
+ deviceID, err := h.defaultDeviceID()
+ if err != nil {
+ return nil, err
+ }
+
+ isConnected, isLoggedIn, err := h.appService.Status(context.Background(), deviceID)
+ if err != nil {
+ return nil, err
+ }
structured := map[string]any{
"is_connected": isConnected,
"is_logged_in": isLoggedIn,
- }
- if deviceID != "" {
- structured["device_id"] = deviceID
+ "device_id": deviceID,
}
fallback := fmt.Sprintf("connected=%t logged_in=%t", isConnected, isLoggedIn)
@@ -67,13 +72,19 @@ func (h *AppHandler) toolLoginWithQR() mcp.Tool {
}
func (h *AppHandler) handleLoginWithQR(ctx context.Context, _ mcp.CallToolRequest) (*mcp.CallToolResult, error) {
- resp, err := h.appService.Login(ctx)
+ deviceID, err := h.defaultDeviceID()
+ if err != nil {
+ return nil, err
+ }
+
+ resp, err := h.appService.Login(ctx, deviceID)
if err != nil {
return nil, err
}
fallback := fmt.Sprintf("Scan the QR image to log in (expires in ~%d seconds)", int(resp.Duration.Seconds()))
structured := map[string]any{
+ "device_id": deviceID,
"qr_image_path": resp.ImagePath,
"qr_code": resp.Code,
"expires_in": int(resp.Duration.Seconds()),
@@ -112,12 +123,18 @@ func (h *AppHandler) handleLoginWithCode(ctx context.Context, request mcp.CallTo
}
trimmedPhone := strings.TrimSpace(phone)
- pairCode, err := h.appService.LoginWithCode(ctx, trimmedPhone)
+ deviceID, err := h.defaultDeviceID()
+ if err != nil {
+ return nil, err
+ }
+
+ pairCode, err := h.appService.LoginWithCode(ctx, deviceID, trimmedPhone)
if err != nil {
return nil, err
}
structured := map[string]any{
+ "device_id": deviceID,
"phone": trimmedPhone,
"pair_code": pairCode,
}
@@ -138,11 +155,16 @@ func (h *AppHandler) toolLogout() mcp.Tool {
}
func (h *AppHandler) handleLogout(ctx context.Context, _ mcp.CallToolRequest) (*mcp.CallToolResult, error) {
- if err := h.appService.Logout(ctx); err != nil {
+ deviceID, err := h.defaultDeviceID()
+ if err != nil {
return nil, err
}
- return mcp.NewToolResultText("Logged out successfully"), nil
+ if err := h.appService.Logout(ctx, deviceID); err != nil {
+ return nil, err
+ }
+
+ return mcp.NewToolResultText(fmt.Sprintf("Logged out device %s successfully", deviceID)), nil
}
func (h *AppHandler) toolReconnect() mcp.Tool {
@@ -157,9 +179,25 @@ func (h *AppHandler) toolReconnect() mcp.Tool {
}
func (h *AppHandler) handleReconnect(ctx context.Context, _ mcp.CallToolRequest) (*mcp.CallToolResult, error) {
- if err := h.appService.Reconnect(ctx); err != nil {
+ deviceID, err := h.defaultDeviceID()
+ if err != nil {
+ return nil, err
+ }
+
+ if err := h.appService.Reconnect(ctx, deviceID); err != nil {
return nil, err
}
- return mcp.NewToolResultText("Reconnect initiated"), nil
+ return mcp.NewToolResultText(fmt.Sprintf("Reconnect initiated for %s", deviceID)), nil
+}
+
+func (h *AppHandler) defaultDeviceID() (string, error) {
+ devices, err := h.appService.FetchDevices(context.Background())
+ if err != nil {
+ return "", err
+ }
+ if len(devices) == 0 {
+ return "", fmt.Errorf("no devices registered")
+ }
+ return devices[0].Device, nil
}
diff --git a/src/ui/rest/app.go b/src/ui/rest/app.go
index d80a52b6..823e672d 100644
--- a/src/ui/rest/app.go
+++ b/src/ui/rest/app.go
@@ -27,7 +27,12 @@ func InitRestApp(app fiber.Router, service domainApp.IAppUsecase) App {
}
func (handler *App) Login(c *fiber.Ctx) error {
- response, err := handler.Service.Login(c.UserContext())
+ device, err := getDeviceInstance(c)
+ if err != nil {
+ return err
+ }
+
+ response, err := handler.Service.Login(c.UserContext(), device.ID())
utils.PanicIfNeeded(err)
return c.JSON(utils.ResponseData{
@@ -35,6 +40,7 @@ func (handler *App) Login(c *fiber.Ctx) error {
Code: "SUCCESS",
Message: "Login success",
Results: map[string]any{
+ "device_id": device.ID(),
"qr_link": fmt.Sprintf("%s://%s%s/%s", c.Protocol(), c.Hostname(), config.AppBasePath, response.ImagePath),
"qr_duration": response.Duration,
},
@@ -42,7 +48,12 @@ func (handler *App) Login(c *fiber.Ctx) error {
}
func (handler *App) LoginWithCode(c *fiber.Ctx) error {
- pairCode, err := handler.Service.LoginWithCode(c.UserContext(), c.Query("phone"))
+ device, err := getDeviceInstance(c)
+ if err != nil {
+ return err
+ }
+
+ pairCode, err := handler.Service.LoginWithCode(c.UserContext(), device.ID(), c.Query("phone"))
utils.PanicIfNeeded(err)
return c.JSON(utils.ResponseData{
@@ -50,32 +61,43 @@ func (handler *App) LoginWithCode(c *fiber.Ctx) error {
Code: "SUCCESS",
Message: "Login with code success",
Results: map[string]any{
+ "device_id": device.ID(),
"pair_code": pairCode,
},
})
}
func (handler *App) Logout(c *fiber.Ctx) error {
- err := handler.Service.Logout(c.UserContext())
+ device, err := getDeviceInstance(c)
+ if err != nil {
+ return err
+ }
+
+ err = handler.Service.Logout(c.UserContext(), device.ID())
utils.PanicIfNeeded(err)
return c.JSON(utils.ResponseData{
Status: 200,
Code: "SUCCESS",
Message: "Success logout",
- Results: nil,
+ Results: map[string]any{"device_id": device.ID()},
})
}
func (handler *App) Reconnect(c *fiber.Ctx) error {
- err := handler.Service.Reconnect(c.UserContext())
+ device, err := getDeviceInstance(c)
+ if err != nil {
+ return err
+ }
+
+ err = handler.Service.Reconnect(c.UserContext(), device.ID())
utils.PanicIfNeeded(err)
return c.JSON(utils.ResponseData{
Status: 200,
Code: "SUCCESS",
Message: "Reconnect success",
- Results: nil,
+ Results: map[string]any{"device_id": device.ID()},
})
}
@@ -92,7 +114,13 @@ func (handler *App) Devices(c *fiber.Ctx) error {
}
func (handler *App) ConnectionStatus(c *fiber.Ctx) error {
- isConnected, isLoggedIn, deviceID := whatsapp.GetConnectionStatus()
+ device, err := getDeviceInstance(c)
+ if err != nil {
+ return err
+ }
+
+ isConnected, isLoggedIn, err := handler.Service.Status(c.UserContext(), device.ID())
+ utils.PanicIfNeeded(err)
return c.JSON(utils.ResponseData{
Status: 200,
@@ -101,7 +129,19 @@ func (handler *App) ConnectionStatus(c *fiber.Ctx) error {
Results: map[string]any{
"is_connected": isConnected,
"is_logged_in": isLoggedIn,
- "device_id": deviceID,
+ "device_id": device.ID(),
},
})
}
+
+func getDeviceInstance(c *fiber.Ctx) (*whatsapp.DeviceInstance, error) {
+ value := c.Locals("device")
+ if value == nil {
+ return nil, fiber.NewError(fiber.StatusBadRequest, "device context is missing")
+ }
+ device, ok := value.(*whatsapp.DeviceInstance)
+ if !ok || device == nil {
+ return nil, fiber.NewError(fiber.StatusBadRequest, "invalid device context")
+ }
+ return device, nil
+}
diff --git a/src/ui/rest/chat.go b/src/ui/rest/chat.go
index dbafdb36..3c415b95 100644
--- a/src/ui/rest/chat.go
+++ b/src/ui/rest/chat.go
@@ -2,6 +2,7 @@ package rest
import (
domainChat "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chat"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/whatsapp"
"github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
"github.com/gofiber/fiber/v2"
)
@@ -31,7 +32,7 @@ func (controller *Chat) ListChats(c *fiber.Ctx) error {
request.Search = c.Query("search", "")
request.HasMedia = c.QueryBool("has_media", false)
- response, err := controller.Service.ListChats(c.UserContext(), request)
+ response, err := controller.Service.ListChats(whatsapp.ContextWithDevice(c.UserContext(), getDeviceFromCtx(c)), request)
utils.PanicIfNeeded(err)
return c.JSON(utils.ResponseData{
@@ -68,7 +69,7 @@ func (controller *Chat) GetChatMessages(c *fiber.Ctx) error {
request.IsFromMe = &isFromMe
}
- response, err := controller.Service.GetChatMessages(c.UserContext(), request)
+ response, err := controller.Service.GetChatMessages(whatsapp.ContextWithDevice(c.UserContext(), getDeviceFromCtx(c)), request)
utils.PanicIfNeeded(err)
return c.JSON(utils.ResponseData{
@@ -95,7 +96,7 @@ func (controller *Chat) PinChat(c *fiber.Ctx) error {
})
}
- response, err := controller.Service.PinChat(c.UserContext(), request)
+ response, err := controller.Service.PinChat(whatsapp.ContextWithDevice(c.UserContext(), getDeviceFromCtx(c)), request)
utils.PanicIfNeeded(err)
return c.JSON(utils.ResponseData{
@@ -122,7 +123,7 @@ func (controller *Chat) SetDisappearingTimer(c *fiber.Ctx) error {
})
}
- response, err := controller.Service.SetDisappearingTimer(c.UserContext(), request)
+ response, err := controller.Service.SetDisappearingTimer(whatsapp.ContextWithDevice(c.UserContext(), getDeviceFromCtx(c)), request)
utils.PanicIfNeeded(err)
return c.JSON(utils.ResponseData{
diff --git a/src/ui/rest/device.go b/src/ui/rest/device.go
new file mode 100644
index 00000000..9a9fd7dc
--- /dev/null
+++ b/src/ui/rest/device.go
@@ -0,0 +1,172 @@
+package rest
+
+import (
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/device"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
+ "github.com/gofiber/fiber/v2"
+)
+
+type Device struct {
+ Service device.IDeviceUsecase
+}
+
+func InitRestDevice(app fiber.Router, service device.IDeviceUsecase) Device {
+ rest := Device{Service: service}
+
+ app.Get("/devices", rest.ListDevices)
+ app.Post("/devices", rest.AddDevice)
+
+ app.Get("/devices/:device_id", rest.GetDevice)
+ app.Delete("/devices/:device_id", rest.RemoveDevice)
+
+ app.Get("/devices/:device_id/login", rest.LoginDevice)
+ app.Post("/devices/:device_id/login/code", rest.LoginDeviceWithCode)
+ app.Post("/devices/:device_id/logout", rest.LogoutDevice)
+ app.Post("/devices/:device_id/reconnect", rest.ReconnectDevice)
+ app.Get("/devices/:device_id/status", rest.Status)
+
+ return rest
+}
+
+func (handler *Device) ListDevices(c *fiber.Ctx) error {
+ devices, err := handler.Service.ListDevices(c.UserContext())
+ utils.PanicIfNeeded(err)
+
+ return c.JSON(utils.ResponseData{
+ Status: 200,
+ Code: "SUCCESS",
+ Message: "List devices",
+ Results: devices,
+ })
+}
+
+func (handler *Device) GetDevice(c *fiber.Ctx) error {
+ deviceID := c.Params("device_id")
+ device, err := handler.Service.GetDevice(c.UserContext(), deviceID)
+ utils.PanicIfNeeded(err)
+
+ return c.JSON(utils.ResponseData{
+ Status: 200,
+ Code: "SUCCESS",
+ Message: "Device info",
+ Results: device,
+ })
+}
+
+func (handler *Device) AddDevice(c *fiber.Ctx) error {
+ var req struct {
+ DeviceID string `json:"device_id"`
+ }
+
+ if err := c.BodyParser(&req); err != nil {
+ return c.Status(fiber.StatusBadRequest).JSON(utils.ResponseData{
+ Status: 400,
+ Code: "BAD_REQUEST",
+ Message: "Invalid request body",
+ Results: nil,
+ })
+ }
+
+ device, err := handler.Service.AddDevice(c.UserContext(), req.DeviceID)
+ utils.PanicIfNeeded(err)
+
+ result := map[string]any{
+ "id": device.ID,
+ "display_name": device.DisplayName,
+ "jid": device.JID,
+ "state": device.State,
+ "created_at": device.CreatedAt,
+ }
+
+ return c.JSON(utils.ResponseData{
+ Status: 200,
+ Code: "SUCCESS",
+ Message: "Device added",
+ Results: result,
+ })
+}
+
+func (handler *Device) RemoveDevice(c *fiber.Ctx) error {
+ deviceID := c.Params("device_id")
+ err := handler.Service.RemoveDevice(c.UserContext(), deviceID)
+ utils.PanicIfNeeded(err)
+
+ return c.JSON(utils.ResponseData{
+ Status: 200,
+ Code: "SUCCESS",
+ Message: "Device removed",
+ Results: nil,
+ })
+}
+
+func (handler *Device) LoginDevice(c *fiber.Ctx) error {
+ deviceID := c.Params("device_id")
+ err := handler.Service.LoginDevice(c.UserContext(), deviceID)
+ utils.PanicIfNeeded(err)
+
+ return c.JSON(utils.ResponseData{
+ Status: 200,
+ Code: "SUCCESS",
+ Message: "Login started",
+ Results: map[string]any{"device_id": deviceID},
+ })
+}
+
+func (handler *Device) LoginDeviceWithCode(c *fiber.Ctx) error {
+ deviceID := c.Params("device_id")
+ code, err := handler.Service.LoginDeviceWithCode(c.UserContext(), deviceID, c.Query("phone"))
+ utils.PanicIfNeeded(err)
+
+ return c.JSON(utils.ResponseData{
+ Status: 200,
+ Code: "SUCCESS",
+ Message: "Login with code started",
+ Results: map[string]any{
+ "device_id": deviceID,
+ "pair_code": code,
+ },
+ })
+}
+
+func (handler *Device) LogoutDevice(c *fiber.Ctx) error {
+ deviceID := c.Params("device_id")
+ err := handler.Service.LogoutDevice(c.UserContext(), deviceID)
+ utils.PanicIfNeeded(err)
+
+ return c.JSON(utils.ResponseData{
+ Status: 200,
+ Code: "SUCCESS",
+ Message: "Logout requested",
+ Results: nil,
+ })
+}
+
+func (handler *Device) ReconnectDevice(c *fiber.Ctx) error {
+ deviceID := c.Params("device_id")
+ err := handler.Service.ReconnectDevice(c.UserContext(), deviceID)
+ utils.PanicIfNeeded(err)
+
+ return c.JSON(utils.ResponseData{
+ Status: 200,
+ Code: "SUCCESS",
+ Message: "Reconnect requested",
+ Results: nil,
+ })
+}
+
+func (handler *Device) Status(c *fiber.Ctx) error {
+ deviceID := c.Params("device_id")
+ isConnected, isLoggedIn, err := handler.Service.GetStatus(c.UserContext(), deviceID)
+ utils.PanicIfNeeded(err)
+
+ return c.JSON(utils.ResponseData{
+ Status: 200,
+ Code: "SUCCESS",
+ Message: "Device status",
+ Results: map[string]any{
+ "device_id": deviceID,
+ "is_connected": isConnected,
+ "is_logged_in": isLoggedIn,
+ },
+ })
+}
diff --git a/src/ui/rest/group.go b/src/ui/rest/group.go
index bcac3c7c..8427fb03 100644
--- a/src/ui/rest/group.go
+++ b/src/ui/rest/group.go
@@ -9,6 +9,7 @@ import (
"github.com/sirupsen/logrus"
domainGroup "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/group"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/whatsapp"
"github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
"github.com/gofiber/fiber/v2"
"go.mau.fi/whatsmeow"
@@ -48,7 +49,7 @@ func (controller *Group) JoinGroupWithLink(c *fiber.Ctx) error {
err := c.BodyParser(&request)
utils.PanicIfNeeded(err)
- response, err := controller.Service.JoinGroupWithLink(c.UserContext(), request)
+ response, err := controller.Service.JoinGroupWithLink(whatsapp.ContextWithDevice(c.UserContext(), getDeviceFromCtx(c)), request)
utils.PanicIfNeeded(err)
return c.JSON(utils.ResponseData{
@@ -66,7 +67,7 @@ func (controller *Group) GetGroupInfoFromLink(c *fiber.Ctx) error {
err := c.QueryParser(&request)
utils.PanicIfNeeded(err)
- response, err := controller.Service.GetGroupInfoFromLink(c.UserContext(), request)
+ response, err := controller.Service.GetGroupInfoFromLink(whatsapp.ContextWithDevice(c.UserContext(), getDeviceFromCtx(c)), request)
utils.PanicIfNeeded(err)
return c.JSON(utils.ResponseData{
@@ -84,7 +85,7 @@ func (controller *Group) LeaveGroup(c *fiber.Ctx) error {
utils.SanitizePhone(&request.GroupID)
- err = controller.Service.LeaveGroup(c.UserContext(), request)
+ err = controller.Service.LeaveGroup(whatsapp.ContextWithDevice(c.UserContext(), getDeviceFromCtx(c)), request)
utils.PanicIfNeeded(err)
return c.JSON(utils.ResponseData{
@@ -99,7 +100,7 @@ func (controller *Group) CreateGroup(c *fiber.Ctx) error {
err := c.BodyParser(&request)
utils.PanicIfNeeded(err)
- groupID, err := controller.Service.CreateGroup(c.UserContext(), request)
+ groupID, err := controller.Service.CreateGroup(whatsapp.ContextWithDevice(c.UserContext(), getDeviceFromCtx(c)), request)
utils.PanicIfNeeded(err)
return c.JSON(utils.ResponseData{
@@ -127,7 +128,7 @@ func (controller *Group) ListParticipants(c *fiber.Ctx) error {
utils.SanitizePhone(&request.GroupID)
- result, err := controller.Service.GetGroupParticipants(c.UserContext(), request)
+ result, err := controller.Service.GetGroupParticipants(whatsapp.ContextWithDevice(c.UserContext(), getDeviceFromCtx(c)), request)
utils.PanicIfNeeded(err)
return c.JSON(utils.ResponseData{
@@ -153,7 +154,7 @@ func (controller *Group) ExportParticipants(c *fiber.Ctx) error {
utils.SanitizePhone(&request.GroupID)
- result, err := controller.Service.GetGroupParticipants(c.UserContext(), request)
+ result, err := controller.Service.GetGroupParticipants(whatsapp.ContextWithDevice(c.UserContext(), getDeviceFromCtx(c)), request)
utils.PanicIfNeeded(err)
var buffer bytes.Buffer
@@ -222,7 +223,7 @@ func (controller *Group) ListParticipantRequests(c *fiber.Ctx) error {
utils.SanitizePhone(&request.GroupID)
- result, err := controller.Service.GetGroupRequestParticipants(c.UserContext(), request)
+ result, err := controller.Service.GetGroupRequestParticipants(whatsapp.ContextWithDevice(c.UserContext(), getDeviceFromCtx(c)), request)
utils.PanicIfNeeded(err)
return c.JSON(utils.ResponseData{
@@ -248,7 +249,7 @@ func (controller *Group) manageParticipants(c *fiber.Ctx, action whatsmeow.Parti
utils.PanicIfNeeded(err)
utils.SanitizePhone(&request.GroupID)
request.Action = action
- result, err := controller.Service.ManageParticipant(c.UserContext(), request)
+ result, err := controller.Service.ManageParticipant(whatsapp.ContextWithDevice(c.UserContext(), getDeviceFromCtx(c)), request)
utils.PanicIfNeeded(err)
return c.JSON(utils.ResponseData{
Status: 200,
@@ -265,7 +266,7 @@ func (controller *Group) handleRequestedParticipants(c *fiber.Ctx, action whatsm
utils.PanicIfNeeded(err)
utils.SanitizePhone(&request.GroupID)
request.Action = action
- result, err := controller.Service.ManageGroupRequestParticipants(c.UserContext(), request)
+ result, err := controller.Service.ManageGroupRequestParticipants(whatsapp.ContextWithDevice(c.UserContext(), getDeviceFromCtx(c)), request)
utils.PanicIfNeeded(err)
return c.JSON(utils.ResponseData{
Status: 200,
@@ -302,7 +303,7 @@ func (controller *Group) SetGroupPhoto(c *fiber.Ctx) error {
logrus.Printf("DEBUG: No photo file provided - Error: %v", err)
}
- pictureID, err := controller.Service.SetGroupPhoto(c.UserContext(), request)
+ pictureID, err := controller.Service.SetGroupPhoto(whatsapp.ContextWithDevice(c.UserContext(), getDeviceFromCtx(c)), request)
if err != nil {
logrus.Printf("ERROR: WhatsApp service failed to set group photo - %v", err)
}
@@ -331,7 +332,7 @@ func (controller *Group) SetGroupName(c *fiber.Ctx) error {
utils.SanitizePhone(&request.GroupID)
- err = controller.Service.SetGroupName(c.UserContext(), request)
+ err = controller.Service.SetGroupName(whatsapp.ContextWithDevice(c.UserContext(), getDeviceFromCtx(c)), request)
utils.PanicIfNeeded(err)
return c.JSON(utils.ResponseData{
@@ -348,7 +349,7 @@ func (controller *Group) SetGroupLocked(c *fiber.Ctx) error {
utils.SanitizePhone(&request.GroupID)
- err = controller.Service.SetGroupLocked(c.UserContext(), request)
+ err = controller.Service.SetGroupLocked(whatsapp.ContextWithDevice(c.UserContext(), getDeviceFromCtx(c)), request)
utils.PanicIfNeeded(err)
message := "Success set group as unlocked"
@@ -370,7 +371,7 @@ func (controller *Group) SetGroupAnnounce(c *fiber.Ctx) error {
utils.SanitizePhone(&request.GroupID)
- err = controller.Service.SetGroupAnnounce(c.UserContext(), request)
+ err = controller.Service.SetGroupAnnounce(whatsapp.ContextWithDevice(c.UserContext(), getDeviceFromCtx(c)), request)
utils.PanicIfNeeded(err)
message := "Success disable announce mode"
@@ -392,7 +393,7 @@ func (controller *Group) SetGroupTopic(c *fiber.Ctx) error {
utils.SanitizePhone(&request.GroupID)
- err = controller.Service.SetGroupTopic(c.UserContext(), request)
+ err = controller.Service.SetGroupTopic(whatsapp.ContextWithDevice(c.UserContext(), getDeviceFromCtx(c)), request)
utils.PanicIfNeeded(err)
message := "Success update group topic"
@@ -415,7 +416,7 @@ func (controller *Group) GroupInfo(c *fiber.Ctx) error {
utils.SanitizePhone(&request.GroupID)
- response, err := controller.Service.GroupInfo(c.UserContext(), request)
+ response, err := controller.Service.GroupInfo(whatsapp.ContextWithDevice(c.UserContext(), getDeviceFromCtx(c)), request)
utils.PanicIfNeeded(err)
return c.JSON(utils.ResponseData{
@@ -433,7 +434,7 @@ func (controller *Group) GetGroupInviteLink(c *fiber.Ctx) error {
utils.SanitizePhone(&request.GroupID)
- response, err := controller.Service.GetGroupInviteLink(c.UserContext(), request)
+ response, err := controller.Service.GetGroupInviteLink(whatsapp.ContextWithDevice(c.UserContext(), getDeviceFromCtx(c)), request)
utils.PanicIfNeeded(err)
return c.JSON(utils.ResponseData{
diff --git a/src/ui/rest/helpers/common.go b/src/ui/rest/helpers/common.go
index b8653d51..f39a06e2 100644
--- a/src/ui/rest/helpers/common.go
+++ b/src/ui/rest/helpers/common.go
@@ -12,7 +12,18 @@ import (
func SetAutoConnectAfterBooting(service domainApp.IAppUsecase) {
time.Sleep(2 * time.Second)
- _ = service.Reconnect(context.Background())
+ devices, err := service.FetchDevices(context.Background())
+ if err != nil || len(devices) == 0 {
+ logrus.Warn("auto-connect skipped: no devices available")
+ return
+ }
+ for _, device := range devices {
+ if err := service.Reconnect(context.Background(), device.Device); err != nil {
+ logrus.Warnf("auto-connect failed for device %s: %v", device.Device, err)
+ } else {
+ logrus.Infof("auto-connected device %s", device.Device)
+ }
+ }
}
func SetAutoReconnectChecking(cli *whatsmeow.Client) {
diff --git a/src/ui/rest/message.go b/src/ui/rest/message.go
index 00ddd288..eceec27c 100644
--- a/src/ui/rest/message.go
+++ b/src/ui/rest/message.go
@@ -2,6 +2,7 @@ package rest
import (
domainMessage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/message"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/whatsapp"
"github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
"github.com/gofiber/fiber/v2"
)
@@ -33,7 +34,7 @@ func (controller *Message) RevokeMessage(c *fiber.Ctx) error {
request.MessageID = c.Params("message_id")
utils.SanitizePhone(&request.Phone)
- response, err := controller.Service.RevokeMessage(c.UserContext(), request)
+ response, err := controller.Service.RevokeMessage(whatsapp.ContextWithDevice(c.UserContext(), getDeviceFromCtx(c)), request)
utils.PanicIfNeeded(err)
return c.JSON(utils.ResponseData{
@@ -52,7 +53,7 @@ func (controller *Message) DeleteMessage(c *fiber.Ctx) error {
request.MessageID = c.Params("message_id")
utils.SanitizePhone(&request.Phone)
- err = controller.Service.DeleteMessage(c.UserContext(), request)
+ err = controller.Service.DeleteMessage(whatsapp.ContextWithDevice(c.UserContext(), getDeviceFromCtx(c)), request)
utils.PanicIfNeeded(err)
return c.JSON(utils.ResponseData{
@@ -71,7 +72,7 @@ func (controller *Message) UpdateMessage(c *fiber.Ctx) error {
request.MessageID = c.Params("message_id")
utils.SanitizePhone(&request.Phone)
- response, err := controller.Service.UpdateMessage(c.UserContext(), request)
+ response, err := controller.Service.UpdateMessage(whatsapp.ContextWithDevice(c.UserContext(), getDeviceFromCtx(c)), request)
utils.PanicIfNeeded(err)
return c.JSON(utils.ResponseData{
@@ -90,7 +91,7 @@ func (controller *Message) ReactMessage(c *fiber.Ctx) error {
request.MessageID = c.Params("message_id")
utils.SanitizePhone(&request.Phone)
- response, err := controller.Service.ReactMessage(c.UserContext(), request)
+ response, err := controller.Service.ReactMessage(whatsapp.ContextWithDevice(c.UserContext(), getDeviceFromCtx(c)), request)
utils.PanicIfNeeded(err)
return c.JSON(utils.ResponseData{
@@ -109,7 +110,7 @@ func (controller *Message) MarkAsRead(c *fiber.Ctx) error {
request.MessageID = c.Params("message_id")
utils.SanitizePhone(&request.Phone)
- response, err := controller.Service.MarkAsRead(c.UserContext(), request)
+ response, err := controller.Service.MarkAsRead(whatsapp.ContextWithDevice(c.UserContext(), getDeviceFromCtx(c)), request)
utils.PanicIfNeeded(err)
return c.JSON(utils.ResponseData{
@@ -129,7 +130,7 @@ func (controller *Message) StarMessage(c *fiber.Ctx) error {
utils.SanitizePhone(&request.Phone)
request.IsStarred = true
- err = controller.Service.StarMessage(c.UserContext(), request)
+ err = controller.Service.StarMessage(whatsapp.ContextWithDevice(c.UserContext(), getDeviceFromCtx(c)), request)
utils.PanicIfNeeded(err)
return c.JSON(utils.ResponseData{
@@ -148,7 +149,7 @@ func (controller *Message) UnstarMessage(c *fiber.Ctx) error {
request.MessageID = c.Params("message_id")
utils.SanitizePhone(&request.Phone)
request.IsStarred = false
- err = controller.Service.StarMessage(c.UserContext(), request)
+ err = controller.Service.StarMessage(whatsapp.ContextWithDevice(c.UserContext(), getDeviceFromCtx(c)), request)
utils.PanicIfNeeded(err)
return c.JSON(utils.ResponseData{
@@ -166,7 +167,12 @@ func (controller *Message) DownloadMedia(c *fiber.Ctx) error {
request.Phone = c.Query("phone")
utils.SanitizePhone(&request.Phone)
- response, err := controller.Service.DownloadMedia(c.UserContext(), request)
+ ctx := c.UserContext()
+ if device, ok := c.Locals("device").(*whatsapp.DeviceInstance); ok {
+ ctx = whatsapp.ContextWithDevice(ctx, device)
+ }
+
+ response, err := controller.Service.DownloadMedia(ctx, request)
utils.PanicIfNeeded(err)
return c.JSON(utils.ResponseData{
diff --git a/src/ui/rest/middleware/device.go b/src/ui/rest/middleware/device.go
new file mode 100644
index 00000000..e363b3ae
--- /dev/null
+++ b/src/ui/rest/middleware/device.go
@@ -0,0 +1,61 @@
+package middleware
+
+import (
+ "strings"
+
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/whatsapp"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
+ "github.com/gofiber/fiber/v2"
+)
+
+const DeviceIDHeader = "X-Device-Id"
+
+// DeviceMiddleware fetches a device instance by header (preferred), path param, or query param
+// and injects it into the context. It falls back to the default/only device for single-device mode.
+func DeviceMiddleware(dm *whatsapp.DeviceManager) fiber.Handler {
+ return func(c *fiber.Ctx) error {
+ // Allow non-device-scoped public endpoints (e.g., landing page) to pass through.
+ if path := strings.TrimSpace(c.Path()); path == "/" || path == "" {
+ return c.Next()
+ }
+
+ if dm == nil {
+ return c.Status(fiber.StatusServiceUnavailable).JSON(utils.ResponseData{
+ Status: fiber.StatusServiceUnavailable,
+ Code: "DEVICE_MANAGER_UNAVAILABLE",
+ Message: "Device manager is not initialized",
+ Results: nil,
+ })
+ }
+
+ deviceID := strings.TrimSpace(c.Get(DeviceIDHeader))
+ if deviceID == "" {
+ deviceID = strings.TrimSpace(c.Query("device_id"))
+ }
+
+ instance, resolvedID, err := dm.ResolveDevice(deviceID)
+ if err != nil {
+ // ResolveDevice returns an ID when provided but missing; use it for payload clarity.
+ if resolvedID != "" || strings.TrimSpace(deviceID) != "" {
+ return c.Status(fiber.StatusNotFound).JSON(utils.ResponseData{
+ Status: fiber.StatusNotFound,
+ Code: "DEVICE_NOT_FOUND",
+ Message: "device not found; create a device first from /api/devices or provide a valid X-Device-Id",
+ Results: map[string]string{"device_id": resolvedID},
+ })
+ }
+
+ return c.Status(fiber.StatusBadRequest).JSON(utils.ResponseData{
+ Status: fiber.StatusBadRequest,
+ Code: "DEVICE_ID_REQUIRED",
+ Message: "device_id is required via X-Device-Id header or device_id query",
+ Results: nil,
+ })
+ }
+
+ c.Locals("device_id", resolvedID)
+ c.Locals("device", instance)
+ c.SetUserContext(whatsapp.ContextWithDevice(c.UserContext(), instance))
+ return c.Next()
+ }
+}
diff --git a/src/ui/rest/newsletter.go b/src/ui/rest/newsletter.go
index 0c0636c3..fc7e2754 100644
--- a/src/ui/rest/newsletter.go
+++ b/src/ui/rest/newsletter.go
@@ -2,6 +2,7 @@ package rest
import (
domainNewsletter "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/newsletter"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/whatsapp"
"github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
"github.com/gofiber/fiber/v2"
)
@@ -21,7 +22,7 @@ func (controller *Newsletter) Unfollow(c *fiber.Ctx) error {
err := c.BodyParser(&request)
utils.PanicIfNeeded(err)
- err = controller.Service.Unfollow(c.UserContext(), request)
+ err = controller.Service.Unfollow(whatsapp.ContextWithDevice(c.UserContext(), getDeviceFromCtx(c)), request)
utils.PanicIfNeeded(err)
return c.JSON(utils.ResponseData{
diff --git a/src/ui/rest/send.go b/src/ui/rest/send.go
index e388b889..76c3d48c 100644
--- a/src/ui/rest/send.go
+++ b/src/ui/rest/send.go
@@ -2,6 +2,7 @@ package rest
import (
domainSend "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/send"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/whatsapp"
"github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
"github.com/gofiber/fiber/v2"
)
@@ -34,7 +35,7 @@ func (controller *Send) SendText(c *fiber.Ctx) error {
utils.SanitizePhone(&request.Phone)
- response, err := controller.Service.SendText(c.UserContext(), request)
+ response, err := controller.Service.SendText(whatsapp.ContextWithDevice(c.UserContext(), getDeviceFromCtx(c)), request)
utils.PanicIfNeeded(err)
return c.JSON(utils.ResponseData{
@@ -59,7 +60,7 @@ func (controller *Send) SendImage(c *fiber.Ctx) error {
utils.SanitizePhone(&request.Phone)
- response, err := controller.Service.SendImage(c.UserContext(), request)
+ response, err := controller.Service.SendImage(whatsapp.ContextWithDevice(c.UserContext(), getDeviceFromCtx(c)), request)
utils.PanicIfNeeded(err)
return c.JSON(utils.ResponseData{
@@ -81,7 +82,7 @@ func (controller *Send) SendFile(c *fiber.Ctx) error {
request.File = file
utils.SanitizePhone(&request.Phone)
- response, err := controller.Service.SendFile(c.UserContext(), request)
+ response, err := controller.Service.SendFile(whatsapp.ContextWithDevice(c.UserContext(), getDeviceFromCtx(c)), request)
utils.PanicIfNeeded(err)
return c.JSON(utils.ResponseData{
@@ -104,7 +105,7 @@ func (controller *Send) SendVideo(c *fiber.Ctx) error {
utils.SanitizePhone(&request.Phone)
- response, err := controller.Service.SendVideo(c.UserContext(), request)
+ response, err := controller.Service.SendVideo(whatsapp.ContextWithDevice(c.UserContext(), getDeviceFromCtx(c)), request)
utils.PanicIfNeeded(err)
return c.JSON(utils.ResponseData{
@@ -127,7 +128,7 @@ func (controller *Send) SendSticker(c *fiber.Ctx) error {
utils.SanitizePhone(&request.Phone)
- response, err := controller.Service.SendSticker(c.UserContext(), request)
+ response, err := controller.Service.SendSticker(whatsapp.ContextWithDevice(c.UserContext(), getDeviceFromCtx(c)), request)
utils.PanicIfNeeded(err)
return c.JSON(utils.ResponseData{
@@ -145,7 +146,7 @@ func (controller *Send) SendContact(c *fiber.Ctx) error {
utils.SanitizePhone(&request.Phone)
- response, err := controller.Service.SendContact(c.UserContext(), request)
+ response, err := controller.Service.SendContact(whatsapp.ContextWithDevice(c.UserContext(), getDeviceFromCtx(c)), request)
utils.PanicIfNeeded(err)
return c.JSON(utils.ResponseData{
@@ -163,7 +164,7 @@ func (controller *Send) SendLink(c *fiber.Ctx) error {
utils.SanitizePhone(&request.Phone)
- response, err := controller.Service.SendLink(c.UserContext(), request)
+ response, err := controller.Service.SendLink(whatsapp.ContextWithDevice(c.UserContext(), getDeviceFromCtx(c)), request)
utils.PanicIfNeeded(err)
return c.JSON(utils.ResponseData{
@@ -181,7 +182,7 @@ func (controller *Send) SendLocation(c *fiber.Ctx) error {
utils.SanitizePhone(&request.Phone)
- response, err := controller.Service.SendLocation(c.UserContext(), request)
+ response, err := controller.Service.SendLocation(whatsapp.ContextWithDevice(c.UserContext(), getDeviceFromCtx(c)), request)
utils.PanicIfNeeded(err)
return c.JSON(utils.ResponseData{
@@ -204,7 +205,7 @@ func (controller *Send) SendAudio(c *fiber.Ctx) error {
utils.SanitizePhone(&request.Phone)
- response, err := controller.Service.SendAudio(c.UserContext(), request)
+ response, err := controller.Service.SendAudio(whatsapp.ContextWithDevice(c.UserContext(), getDeviceFromCtx(c)), request)
utils.PanicIfNeeded(err)
return c.JSON(utils.ResponseData{
@@ -222,7 +223,7 @@ func (controller *Send) SendPoll(c *fiber.Ctx) error {
utils.SanitizePhone(&request.Phone)
- response, err := controller.Service.SendPoll(c.UserContext(), request)
+ response, err := controller.Service.SendPoll(whatsapp.ContextWithDevice(c.UserContext(), getDeviceFromCtx(c)), request)
utils.PanicIfNeeded(err)
return c.JSON(utils.ResponseData{
@@ -238,7 +239,7 @@ func (controller *Send) SendPresence(c *fiber.Ctx) error {
err := c.BodyParser(&request)
utils.PanicIfNeeded(err)
- response, err := controller.Service.SendPresence(c.UserContext(), request)
+ response, err := controller.Service.SendPresence(whatsapp.ContextWithDevice(c.UserContext(), getDeviceFromCtx(c)), request)
utils.PanicIfNeeded(err)
return c.JSON(utils.ResponseData{
@@ -256,7 +257,7 @@ func (controller *Send) SendChatPresence(c *fiber.Ctx) error {
utils.SanitizePhone(&request.Phone)
- response, err := controller.Service.SendChatPresence(c.UserContext(), request)
+ response, err := controller.Service.SendChatPresence(whatsapp.ContextWithDevice(c.UserContext(), getDeviceFromCtx(c)), request)
utils.PanicIfNeeded(err)
return c.JSON(utils.ResponseData{
diff --git a/src/ui/rest/user.go b/src/ui/rest/user.go
index d9662bb9..27b9f200 100644
--- a/src/ui/rest/user.go
+++ b/src/ui/rest/user.go
@@ -2,6 +2,7 @@ package rest
import (
domainUser "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/user"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/whatsapp"
"github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
"github.com/gofiber/fiber/v2"
)
@@ -33,7 +34,9 @@ func (controller *User) UserInfo(c *fiber.Ctx) error {
utils.SanitizePhone(&request.Phone)
- response, err := controller.Service.Info(c.UserContext(), request)
+ ctx := whatsapp.ContextWithDevice(c.UserContext(), getDeviceFromCtx(c))
+
+ response, err := controller.Service.Info(ctx, request)
utils.PanicIfNeeded(err)
return c.JSON(utils.ResponseData{
@@ -51,7 +54,9 @@ func (controller *User) UserAvatar(c *fiber.Ctx) error {
utils.SanitizePhone(&request.Phone)
- response, err := controller.Service.Avatar(c.UserContext(), request)
+ ctx := whatsapp.ContextWithDevice(c.UserContext(), getDeviceFromCtx(c))
+
+ response, err := controller.Service.Avatar(ctx, request)
utils.PanicIfNeeded(err)
return c.JSON(utils.ResponseData{
@@ -70,7 +75,9 @@ func (controller *User) UserChangeAvatar(c *fiber.Ctx) error {
request.Avatar, err = c.FormFile("avatar")
utils.PanicIfNeeded(err)
- err = controller.Service.ChangeAvatar(c.UserContext(), request)
+ ctx := whatsapp.ContextWithDevice(c.UserContext(), getDeviceFromCtx(c))
+
+ err = controller.Service.ChangeAvatar(ctx, request)
utils.PanicIfNeeded(err)
return c.JSON(utils.ResponseData{
@@ -81,7 +88,8 @@ func (controller *User) UserChangeAvatar(c *fiber.Ctx) error {
}
func (controller *User) UserMyPrivacySetting(c *fiber.Ctx) error {
- response, err := controller.Service.MyPrivacySetting(c.UserContext())
+ ctx := whatsapp.ContextWithDevice(c.UserContext(), getDeviceFromCtx(c))
+ response, err := controller.Service.MyPrivacySetting(ctx)
utils.PanicIfNeeded(err)
return c.JSON(utils.ResponseData{
@@ -93,7 +101,13 @@ func (controller *User) UserMyPrivacySetting(c *fiber.Ctx) error {
}
func (controller *User) UserMyListGroups(c *fiber.Ctx) error {
- response, err := controller.Service.MyListGroups(c.UserContext())
+ deviceVal := c.Locals("device")
+ ctx := c.UserContext()
+ if device, ok := deviceVal.(*whatsapp.DeviceInstance); ok {
+ ctx = whatsapp.ContextWithDevice(ctx, device)
+ }
+
+ response, err := controller.Service.MyListGroups(ctx)
utils.PanicIfNeeded(err)
return c.JSON(utils.ResponseData{
@@ -105,7 +119,8 @@ func (controller *User) UserMyListGroups(c *fiber.Ctx) error {
}
func (controller *User) UserMyListNewsletter(c *fiber.Ctx) error {
- response, err := controller.Service.MyListNewsletter(c.UserContext())
+ ctx := whatsapp.ContextWithDevice(c.UserContext(), getDeviceFromCtx(c))
+ response, err := controller.Service.MyListNewsletter(ctx)
utils.PanicIfNeeded(err)
return c.JSON(utils.ResponseData{
@@ -117,7 +132,8 @@ func (controller *User) UserMyListNewsletter(c *fiber.Ctx) error {
}
func (controller *User) UserMyListContacts(c *fiber.Ctx) error {
- response, err := controller.Service.MyListContacts(c.UserContext())
+ ctx := whatsapp.ContextWithDevice(c.UserContext(), getDeviceFromCtx(c))
+ response, err := controller.Service.MyListContacts(ctx)
utils.PanicIfNeeded(err)
return c.JSON(utils.ResponseData{
@@ -166,7 +182,9 @@ func (controller *User) UserBusinessProfile(c *fiber.Ctx) error {
utils.SanitizePhone(&request.Phone)
- response, err := controller.Service.BusinessProfile(c.UserContext(), request)
+ ctx := whatsapp.ContextWithDevice(c.UserContext(), getDeviceFromCtx(c))
+
+ response, err := controller.Service.BusinessProfile(ctx, request)
utils.PanicIfNeeded(err)
return c.JSON(utils.ResponseData{
@@ -176,3 +194,13 @@ func (controller *User) UserBusinessProfile(c *fiber.Ctx) error {
Results: response,
})
}
+
+func getDeviceFromCtx(c *fiber.Ctx) *whatsapp.DeviceInstance {
+ if c == nil {
+ return nil
+ }
+ if device, ok := c.Locals("device").(*whatsapp.DeviceInstance); ok {
+ return device
+ }
+ return nil
+}
diff --git a/src/usecase/app.go b/src/usecase/app.go
index 63b23860..6db5551a 100644
--- a/src/usecase/app.go
+++ b/src/usecase/app.go
@@ -12,6 +12,7 @@ import (
domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
"github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/whatsapp"
pkgError "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/error"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/ui/websocket"
"github.com/aldinokemal/go-whatsapp-web-multidevice/validations"
fiberUtils "github.com/gofiber/fiber/v2/utils"
_ "github.com/mattn/go-sqlite3"
@@ -23,260 +24,246 @@ import (
type serviceApp struct {
chatStorageRepo domainChatStorage.IChatStorageRepository
+ deviceManager *whatsapp.DeviceManager
}
-func NewAppService(chatStorageRepo domainChatStorage.IChatStorageRepository) domainApp.IAppUsecase {
+func NewAppService(chatStorageRepo domainChatStorage.IChatStorageRepository, deviceManager *whatsapp.DeviceManager) domainApp.IAppUsecase {
return &serviceApp{
chatStorageRepo: chatStorageRepo,
+ deviceManager: deviceManager,
}
}
-func (service *serviceApp) Login(_ context.Context) (response domainApp.LoginResponse, err error) {
- client := whatsapp.GetClient()
- if client == nil {
- return response, pkgError.ErrWaCLI
- }
-
- // [DEBUG] Log database state before login
- logrus.Info("[DEBUG] Starting login process...")
- devices, dbErr := whatsapp.GetDB().GetAllDevices(context.Background())
- if dbErr != nil {
- logrus.Errorf("[DEBUG] Error getting devices before login: %v", dbErr)
- } else {
- logrus.Infof("[DEBUG] Devices before login: %d found", len(devices))
- for _, device := range devices {
- logrus.Infof("[DEBUG] Device ID: %s, PushName: %s", device.ID.String(), device.PushName)
- }
+func (service *serviceApp) Login(ctx context.Context, deviceID string) (response domainApp.LoginResponse, err error) {
+ instance, client, err := service.ensureClient(ctx, deviceID)
+ if err != nil {
+ return response, err
}
- // [DEBUG] Log client state
- if client.Store.ID != nil {
- logrus.Infof("[DEBUG] Client has existing store ID: %s", client.Store.ID.String())
- } else {
- logrus.Info("[DEBUG] Client has no store ID")
+ if client.IsLoggedIn() {
+ instance.UpdateStateFromClient()
+ return response, pkgError.ErrAlreadyLoggedIn
}
- // Disconnect for reconnecting
+ // Disconnect first to ensure QR flow starts cleanly.
client.Disconnect()
- chImage := make(chan string)
-
- logrus.Info("[DEBUG] Attempting to get QR channel...")
- ch, err := client.GetQRChannel(context.Background())
+ chImage := make(chan string, 1) // Buffered to prevent goroutine leak
+ ch, err := client.GetQRChannel(ctx)
if err != nil {
- logrus.Errorf("[DEBUG] GetQRChannel failed: %v", err)
- logrus.Error(err.Error())
- // This error means that we're already logged in, so ignore it.
+ logrus.Errorf("[LOGIN][%s] GetQRChannel failed: %v", deviceID, err)
if errors.Is(err, whatsmeow.ErrQRStoreContainsID) {
- logrus.Info("[DEBUG] Error is ErrQRStoreContainsID - attempting to connect")
- _ = client.Connect() // just connect to websocket
+ _ = client.Connect()
+ instance.UpdateStateFromClient()
if client.IsLoggedIn() {
return response, pkgError.ErrAlreadyLoggedIn
}
return response, pkgError.ErrSessionSaved
- } else {
- return response, pkgError.ErrQrChannel
}
- } else {
- logrus.Info("[DEBUG] QR channel obtained successfully")
- go func() {
- for evt := range ch {
- response.Code = evt.Code
- response.Duration = evt.Timeout / time.Second / 2
- if evt.Event == "code" {
- qrPath := fmt.Sprintf("%s/scan-qr-%s.png", config.PathQrCode, fiberUtils.UUIDv4())
- err = qrcode.WriteFile(evt.Code, qrcode.Medium, 512, qrPath)
- if err != nil {
- logrus.Error("Error when write qr code to file: ", err)
+ return response, pkgError.ErrQrChannel
+ }
+
+ go func() {
+ defer close(chImage) // Ensure channel is closed when done
+ for evt := range ch {
+ response.Code = evt.Code
+ response.Duration = evt.Timeout / time.Second / 2
+ if evt.Event == "code" {
+ qrPath := fmt.Sprintf("%s/scan-qr-%s.png", config.PathQrCode, fiberUtils.UUIDv4())
+ if err := qrcode.WriteFile(evt.Code, qrcode.Medium, 512, qrPath); err != nil {
+ logrus.Errorf("[LOGIN][%s] Error when write qr code to file: %v", deviceID, err)
+ continue // Skip sending if QR generation failed
+ }
+ go func(path string, duration time.Duration) {
+ time.Sleep(duration * time.Second)
+ if err := os.Remove(path); err != nil && !os.IsNotExist(err) {
+ logrus.Errorf("[LOGIN][%s] error when remove qrImage file: %v", deviceID, err)
}
- go func() {
- time.Sleep(response.Duration * time.Second)
- err := os.Remove(qrPath)
- if err != nil {
- // Only log if it's not a "file not found" error
- if !os.IsNotExist(err) {
- logrus.Error("error when remove qrImage file", err.Error())
- }
- }
- }()
- chImage <- qrPath
- } else {
- logrus.Error("error when get qrCode", evt.Event, evt.Error)
+ }(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)
+ return
}
+ } else {
+ logrus.Errorf("[LOGIN][%s] error when get qrCode %s %v", deviceID, evt.Event, evt.Error)
}
- }()
- }
+ }
+ }()
- err = client.Connect()
- if err != nil {
+ if err = client.Connect(); err != nil {
logger.Error("Error when connect to whatsapp", err)
return response, pkgError.ErrReconnect
}
- response.ImagePath = <-chImage
- // [DEBUG] Verify connection state and sync global client
- logrus.Infof("[DEBUG] Login connection established - IsConnected: %v, IsLoggedIn: %v",
- client.IsConnected(), client.IsLoggedIn())
+ instance.UpdateStateFromClient()
- // Ensure global client is synchronized with service client
- whatsapp.UpdateGlobalClient(client, whatsapp.GetDB())
+ // Wait for QR image with timeout to prevent hanging
+ select {
+ case imagePath, ok := <-chImage:
+ if !ok {
+ return response, fmt.Errorf("QR channel closed without receiving image")
+ }
+ response.ImagePath = imagePath
+ case <-ctx.Done():
+ return response, ctx.Err()
+ case <-time.After(120 * time.Second):
+ return response, fmt.Errorf("timeout waiting for QR code")
+ }
return response, nil
}
-func (service *serviceApp) LoginWithCode(ctx context.Context, phoneNumber string) (loginCode string, err error) {
+func (service *serviceApp) LoginWithCode(ctx context.Context, deviceID string, phoneNumber string) (loginCode string, err error) {
if err = validations.ValidateLoginWithCode(ctx, phoneNumber); err != nil {
logrus.Errorf("Error when validate login with code: %s", err.Error())
return loginCode, err
}
- client := whatsapp.GetClient()
- // detect is already logged in
- if client.Store.ID != nil || client.IsLoggedIn() {
- logrus.Warn("User is already logged in")
- return loginCode, pkgError.ErrAlreadyLoggedIn
- }
-
- // reconnect first
- if err = service.Reconnect(ctx); err != nil {
- logrus.Errorf("Error when reconnecting before login with code: %s", err.Error())
+ instance, client, err := service.ensureClient(ctx, deviceID)
+ if err != nil {
return loginCode, err
}
- // refresh client reference after reconnect
- client = whatsapp.GetClient()
- if client.IsLoggedIn() || client.Store.ID != nil {
- logrus.Warn("User is already logged in after reconnect")
+ if client.IsLoggedIn() {
+ instance.UpdateStateFromClient()
return loginCode, pkgError.ErrAlreadyLoggedIn
}
- logrus.Infof("[DEBUG] Starting phone pairing for number: %s", phoneNumber)
+ // Connect before requesting pairing code.
+ if !client.IsConnected() {
+ if err = client.Connect(); err != nil {
+ return loginCode, err
+ }
+ }
+
+ logrus.Infof("[LOGIN_CODE][%s] Starting phone pairing for number: %s", deviceID, phoneNumber)
loginCode, err = client.PairPhone(ctx, phoneNumber, true, whatsmeow.PairClientChrome, "Chrome (Linux)")
if err != nil {
logrus.Errorf("Error when pairing phone: %s", err.Error())
return loginCode, err
}
- // [DEBUG] Verify pairing state and sync global client
- logrus.Infof("[DEBUG] Phone pairing completed - IsConnected: %v, IsLoggedIn: %v",
- client.IsConnected(), client.IsLoggedIn())
-
- // Ensure global client is synchronized with service client
- whatsapp.UpdateGlobalClient(client, whatsapp.GetDB())
-
+ instance.UpdateStateFromClient()
logrus.Infof("Successfully paired phone with code: %s", loginCode)
return loginCode, nil
}
-func (service *serviceApp) Logout(ctx context.Context) (err error) {
- // [DEBUG] Log database state before logout
- logrus.Info("[DEBUG] Starting logout process...")
- devices, dbErr := whatsapp.GetDB().GetAllDevices(ctx)
- if dbErr != nil {
- logrus.Errorf("[DEBUG] Error getting devices before logout: %v", dbErr)
- } else {
- logrus.Infof("[DEBUG] Devices before logout: %d found", len(devices))
- for _, device := range devices {
- logrus.Infof("[DEBUG] Device ID: %s, PushName: %s", device.ID.String(), device.PushName)
- }
+func (service *serviceApp) Logout(ctx context.Context, deviceID string) error {
+ if service.deviceManager == nil {
+ return fmt.Errorf("device manager not initialized")
}
- // [DEBUG] Call WhatsApp client logout first to disconnect from server
- logrus.Info("[DEBUG] Calling WhatsApp client logout...")
- err = whatsapp.GetClient().Logout(ctx)
- if err != nil {
- logrus.Errorf("[DEBUG] WhatsApp logout failed: %v", err)
- // Continue with cleanup even if logout fails
- } else {
- logrus.Info("[DEBUG] WhatsApp logout completed successfully")
+ if err := service.deviceManager.PurgeDevice(ctx, deviceID); err != nil {
+ logrus.WithError(err).Warnf("[LOGOUT][%s] purge completed with warnings", deviceID)
+ return err
}
- // [DEBUG] Verify devices after logout
- devices, dbErr = whatsapp.GetDB().GetAllDevices(ctx)
- if dbErr != nil {
- logrus.Errorf("[DEBUG] Error getting devices after logout: %v", dbErr)
+ // Broadcast device removal so UI can refresh without manual polling
+ var devices []domainApp.DevicesResponse
+ if list, err := service.FetchDevices(ctx); err == nil {
+ devices = list
} else {
- logrus.Infof("[DEBUG] Devices after logout: %d found", len(devices))
+ logrus.WithError(err).Warn("[LOGOUT] failed to fetch devices after purge")
}
- // Perform complete cleanup with global client synchronization
- newDB, newCli, err := whatsapp.PerformCleanupAndUpdateGlobals(ctx, "MANUAL_LOGOUT", service.chatStorageRepo)
- if err != nil {
- logrus.Errorf("[DEBUG] Cleanup failed: %v", err)
- return err
+ websocket.Broadcast <- websocket.BroadcastMessage{
+ Code: "DEVICE_REMOVED",
+ Message: fmt.Sprintf("Device %s logged out and removed", deviceID),
+ Result: map[string]any{
+ "device_id": deviceID,
+ "devices": devices,
+ },
}
- // Update service references
- whatsapp.UpdateGlobalClient(newCli, newDB)
-
- logrus.Info("[DEBUG] Logout process completed successfully")
return nil
}
-func (service *serviceApp) Reconnect(_ context.Context) (err error) {
- logrus.Info("[DEBUG] Starting reconnect process...")
+func (service *serviceApp) Reconnect(_ context.Context, deviceID string) (err error) {
+ instance, client, err := service.ensureClient(context.Background(), deviceID)
+ if err != nil {
+ return err
+ }
- client := whatsapp.GetClient()
client.Disconnect()
err = client.Connect()
-
+ instance.UpdateStateFromClient()
if err != nil {
- logrus.Errorf("[DEBUG] Reconnect failed: %v", err)
- return err
+ logrus.Errorf("[RECONNECT][%s] Reconnect failed: %v", deviceID, err)
}
+ return err
+}
- // [DEBUG] Verify reconnection state and sync global client
- logrus.Infof("[DEBUG] Reconnection completed - IsConnected: %v, IsLoggedIn: %v",
- client.IsConnected(), client.IsLoggedIn())
+func (service *serviceApp) Status(_ context.Context, deviceID string) (bool, bool, error) {
+ if service.deviceManager == nil {
+ return false, false, fmt.Errorf("device manager not initialized")
+ }
- // Ensure global client is synchronized with service client
- whatsapp.UpdateGlobalClient(client, whatsapp.GetDB())
+ instance, ok := service.deviceManager.GetDevice(deviceID)
+ if !ok || instance == nil {
+ return false, false, fmt.Errorf("device %s not found", deviceID)
+ }
- logrus.Info("[DEBUG] Reconnect process completed successfully")
- return err
+ instance.UpdateStateFromClient()
+ client := instance.GetClient()
+ if client == nil {
+ return false, false, nil
+ }
+ return client.IsConnected(), client.IsLoggedIn(), nil
}
func (service *serviceApp) FirstDevice(ctx context.Context) (response domainApp.DevicesResponse, err error) {
- if whatsapp.GetClient() == nil {
- return response, pkgError.ErrWaCLI
- }
-
- devices, err := whatsapp.GetDB().GetFirstDevice(ctx)
+ devices, err := service.FetchDevices(ctx)
if err != nil {
return response, err
}
+ if len(devices) == 0 {
+ return response, fmt.Errorf("no devices available")
+ }
+ return devices[0], nil
+}
- response.Device = devices.ID.String()
- if devices.PushName != "" {
- response.Name = devices.PushName
- } else {
- response.Name = devices.BusinessName
+func (service *serviceApp) FetchDevices(_ context.Context) (response []domainApp.DevicesResponse, err error) {
+ if service.deviceManager == nil {
+ return response, fmt.Errorf("device manager not initialized")
+ }
+
+ for _, inst := range service.deviceManager.ListDevices() {
+ inst.UpdateStateFromClient()
+ name := inst.DisplayName()
+ if name == "" {
+ name = inst.PhoneNumber()
+ }
+
+ response = append(response, domainApp.DevicesResponse{
+ Name: name,
+ Device: inst.ID(),
+ })
}
return response, nil
}
-func (service *serviceApp) FetchDevices(ctx context.Context) (response []domainApp.DevicesResponse, err error) {
- if whatsapp.GetClient() == nil {
- return response, pkgError.ErrWaCLI
+func (service *serviceApp) ensureClient(ctx context.Context, deviceID string) (*whatsapp.DeviceInstance, *whatsmeow.Client, error) {
+ if deviceID == "" {
+ return nil, nil, fmt.Errorf("device id is required")
}
- devices, err := whatsapp.GetDB().GetAllDevices(ctx)
- if err != nil {
- return nil, err
+ if service.deviceManager == nil {
+ return nil, nil, fmt.Errorf("device manager not initialized")
}
- for _, device := range devices {
- var d domainApp.DevicesResponse
- d.Device = device.ID.String()
- if device.PushName != "" {
- d.Name = device.PushName
- } else {
- d.Name = device.BusinessName
- }
+ instance, err := service.deviceManager.EnsureClient(ctx, deviceID)
+ if err != nil {
+ return nil, nil, err
+ }
- response = append(response, d)
+ client := instance.GetClient()
+ if client == nil {
+ return instance, nil, pkgError.ErrWaCLI
}
- return response, nil
+ return instance, client, nil
}
diff --git a/src/usecase/chat.go b/src/usecase/chat.go
index b4ff7c85..defc418c 100644
--- a/src/usecase/chat.go
+++ b/src/usecase/chat.go
@@ -8,6 +8,7 @@ import (
domainChat "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chat"
domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
"github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/whatsapp"
+ pkgError "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/error"
"github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
"github.com/aldinokemal/go-whatsapp-web-multidevice/validations"
"github.com/sirupsen/logrus"
@@ -31,6 +32,7 @@ func (service serviceChat) ListChats(ctx context.Context, request domainChat.Lis
// Create filter from request
filter := &domainChatStorage.ChatFilter{
+ DeviceID: deviceIDFromContext(ctx),
Limit: request.Limit,
Offset: request.Offset,
SearchName: request.Search,
@@ -203,13 +205,28 @@ func (service serviceChat) GetChatMessages(ctx context.Context, request domainCh
return response, nil
}
+func deviceIDFromContext(ctx context.Context) string {
+ if inst, ok := whatsapp.DeviceFromContext(ctx); ok && inst != nil {
+ if jid := inst.JID(); jid != "" {
+ return jid
+ }
+ return inst.ID()
+ }
+ return ""
+}
+
func (service serviceChat) PinChat(ctx context.Context, request domainChat.PinChatRequest) (response domainChat.PinChatResponse, err error) {
if err = validations.ValidatePinChat(ctx, &request); err != nil {
return response, err
}
+ client := whatsapp.ClientFromContext(ctx)
+ if client == nil {
+ return response, pkgError.ErrWaCLI
+ }
+
// Validate JID and ensure connection
- targetJID, err := utils.ValidateJidWithLogin(whatsapp.GetClient(), request.ChatJID)
+ targetJID, err := utils.ValidateJidWithLogin(client, request.ChatJID)
if err != nil {
return response, err
}
@@ -218,7 +235,7 @@ func (service serviceChat) PinChat(ctx context.Context, request domainChat.PinCh
patchInfo := appstate.BuildPin(targetJID, request.Pinned)
// Send app state update
- if err = whatsapp.GetClient().SendAppState(ctx, patchInfo); err != nil {
+ if err = client.SendAppState(ctx, patchInfo); err != nil {
logrus.WithError(err).WithFields(logrus.Fields{
"chat_jid": request.ChatJID,
"pinned": request.Pinned,
@@ -250,14 +267,19 @@ func (service serviceChat) SetDisappearingTimer(ctx context.Context, request dom
return response, err
}
+ client := whatsapp.ClientFromContext(ctx)
+ if client == nil {
+ return response, pkgError.ErrWaCLI
+ }
+
// Validate JID and ensure connection
- targetJID, err := utils.ValidateJidWithLogin(whatsapp.GetClient(), request.ChatJID)
+ targetJID, err := utils.ValidateJidWithLogin(client, request.ChatJID)
if err != nil {
return response, err
}
// Set disappearing timer using whatsmeow
- if err = whatsapp.GetClient().SetDisappearingTimer(ctx, targetJID, time.Duration(request.TimerSeconds)*time.Second, time.Now()); err != nil {
+ if err = client.SetDisappearingTimer(ctx, targetJID, time.Duration(request.TimerSeconds)*time.Second, time.Now()); err != nil {
logrus.WithError(err).WithFields(logrus.Fields{
"chat_jid": request.ChatJID,
"timer_seconds": request.TimerSeconds,
diff --git a/src/usecase/device.go b/src/usecase/device.go
new file mode 100644
index 00000000..d409110f
--- /dev/null
+++ b/src/usecase/device.go
@@ -0,0 +1,174 @@
+package usecase
+
+import (
+ "context"
+ "fmt"
+
+ domainDevice "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/device"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/whatsapp"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/ui/websocket"
+)
+
+type serviceDevice struct {
+ manager *whatsapp.DeviceManager
+}
+
+func NewDeviceService(manager *whatsapp.DeviceManager) domainDevice.IDeviceUsecase {
+ return &serviceDevice{
+ manager: manager,
+ }
+}
+
+func (s *serviceDevice) ListDevices(_ context.Context) ([]domainDevice.Device, error) {
+ if s.manager == nil {
+ return []domainDevice.Device{}, nil
+ }
+
+ var result []domainDevice.Device
+ for _, inst := range s.manager.ListDevices() {
+ inst.UpdateStateFromClient()
+ result = append(result, convertInstance(inst))
+ }
+ return result, nil
+}
+
+func (s *serviceDevice) GetDevice(_ context.Context, deviceID string) (*domainDevice.Device, error) {
+ if s.manager == nil {
+ return nil, fmt.Errorf("device manager not initialized")
+ }
+ if inst, ok := s.manager.GetDevice(deviceID); ok {
+ device := convertInstance(inst)
+ return &device, nil
+ }
+ return nil, fmt.Errorf("device %s not found", deviceID)
+}
+
+func (s *serviceDevice) AddDevice(ctx context.Context, deviceID string) (*domainDevice.Device, error) {
+ if s.manager == nil {
+ return nil, fmt.Errorf("device manager not initialized")
+ }
+
+ inst, err := s.manager.CreateDevice(ctx, deviceID)
+ if err != nil {
+ return nil, err
+ }
+ device := convertInstance(inst)
+ return &device, nil
+}
+
+func (s *serviceDevice) RemoveDevice(_ context.Context, deviceID string) error {
+ if s.manager == nil {
+ return fmt.Errorf("device manager not initialized")
+ }
+ s.manager.RemoveDevice(deviceID)
+ return nil
+}
+
+func (s *serviceDevice) LoginDevice(_ context.Context, _ string) error {
+ return fmt.Errorf("device login per ID is not implemented yet")
+}
+
+func (s *serviceDevice) LoginDeviceWithCode(_ context.Context, _ string, _ string) (string, error) {
+ return "", fmt.Errorf("device login with code is not implemented yet")
+}
+
+func (s *serviceDevice) LogoutDevice(ctx context.Context, deviceID string) error {
+ if s.manager == nil {
+ return fmt.Errorf("device manager not initialized")
+ }
+
+ if err := s.manager.PurgeDevice(ctx, deviceID); err != nil {
+ return err
+ }
+
+ // Broadcast device removal so UI clients can refresh.
+ var devices []domainDevice.Device
+ if s.manager != nil {
+ for _, inst := range s.manager.ListDevices() {
+ inst.UpdateStateFromClient()
+ devices = append(devices, convertInstance(inst))
+ }
+ }
+
+ websocket.Broadcast <- websocket.BroadcastMessage{
+ Code: "DEVICE_REMOVED",
+ Message: fmt.Sprintf("Device %s logged out and removed", deviceID),
+ Result: map[string]any{
+ "device_id": deviceID,
+ "devices": devices,
+ },
+ }
+
+ return nil
+}
+
+func (s *serviceDevice) ReconnectDevice(_ context.Context, deviceID string) error {
+ if s.manager == nil {
+ return fmt.Errorf("device manager not initialized")
+ }
+ if inst, ok := s.manager.GetDevice(deviceID); ok {
+ client := inst.GetClient()
+ if client == nil {
+ return fmt.Errorf("device %s client not initialized", deviceID)
+ }
+ client.Disconnect()
+ return client.Connect()
+ }
+ return fmt.Errorf("device %s not found", deviceID)
+}
+
+func (s *serviceDevice) GetStatus(_ context.Context, deviceID string) (bool, bool, error) {
+ if s.manager == nil {
+ return false, false, fmt.Errorf("device manager not initialized")
+ }
+ if inst, ok := s.manager.GetDevice(deviceID); ok {
+ inst.UpdateStateFromClient()
+ client := inst.GetClient()
+ if client == nil {
+ return false, false, nil
+ }
+ // Update state snapshot based on live client flags
+ state := deriveState(inst)
+ _ = state
+ return client.IsConnected(), client.IsLoggedIn(), nil
+ }
+ return false, false, fmt.Errorf("device %s not found", deviceID)
+}
+
+func convertInstance(inst *whatsapp.DeviceInstance) domainDevice.Device {
+ if inst == nil {
+ return domainDevice.Device{}
+ }
+
+ state := deriveState(inst)
+
+ return domainDevice.Device{
+ ID: inst.ID(),
+ PhoneNumber: inst.PhoneNumber(),
+ DisplayName: inst.DisplayName(),
+ State: state,
+ JID: inst.JID(),
+ CreatedAt: inst.CreatedAt(),
+ }
+}
+
+func deriveState(inst *whatsapp.DeviceInstance) domainDevice.DeviceState {
+ if inst == nil {
+ return domainDevice.DeviceStateDisconnected
+ }
+
+ client := inst.GetClient()
+ state := inst.State()
+ if client != nil {
+ if client.IsLoggedIn() {
+ state = domainDevice.DeviceStateLoggedIn
+ } else if client.IsConnected() {
+ state = domainDevice.DeviceStateConnected
+ } else {
+ state = domainDevice.DeviceStateDisconnected
+ }
+ inst.SetState(state)
+ }
+
+ return state
+}
diff --git a/src/usecase/group.go b/src/usecase/group.go
index fa2be3c5..f4f6ac91 100644
--- a/src/usecase/group.go
+++ b/src/usecase/group.go
@@ -5,6 +5,8 @@ import (
"fmt"
"github.com/sirupsen/logrus"
+ "go.mau.fi/whatsmeow"
+ "go.mau.fi/whatsmeow/types"
"github.com/aldinokemal/go-whatsapp-web-multidevice/config"
domainGroup "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/group"
@@ -12,8 +14,6 @@ import (
pkgError "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/error"
"github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
"github.com/aldinokemal/go-whatsapp-web-multidevice/validations"
- "go.mau.fi/whatsmeow"
- "go.mau.fi/whatsmeow/types"
)
type serviceGroup struct{}
@@ -26,9 +26,14 @@ func (service serviceGroup) JoinGroupWithLink(ctx context.Context, request domai
if err = validations.ValidateJoinGroupWithLink(ctx, request); err != nil {
return groupID, err
}
- utils.MustLogin(whatsapp.GetClient())
- jid, err := whatsapp.GetClient().JoinGroupWithLink(ctx, request.Link)
+ client := whatsapp.ClientFromContext(ctx)
+ if client == nil {
+ return groupID, pkgError.ErrWaCLI
+ }
+ utils.MustLogin(client)
+
+ jid, err := client.JoinGroupWithLink(ctx, request.Link)
if err != nil {
return
}
@@ -40,21 +45,31 @@ func (service serviceGroup) LeaveGroup(ctx context.Context, request domainGroup.
return err
}
- JID, err := utils.ValidateJidWithLogin(whatsapp.GetClient(), request.GroupID)
+ client := whatsapp.ClientFromContext(ctx)
+ if client == nil {
+ return pkgError.ErrWaCLI
+ }
+
+ JID, err := utils.ValidateJidWithLogin(client, request.GroupID)
if err != nil {
return err
}
- return whatsapp.GetClient().LeaveGroup(ctx, JID)
+ return client.LeaveGroup(ctx, JID)
}
func (service serviceGroup) CreateGroup(ctx context.Context, request domainGroup.CreateGroupRequest) (groupID string, err error) {
if err = validations.ValidateCreateGroup(ctx, request); err != nil {
return groupID, err
}
- utils.MustLogin(whatsapp.GetClient())
- participantsJID, err := service.participantToJID(request.Participants)
+ client := whatsapp.ClientFromContext(ctx)
+ if client == nil {
+ return groupID, pkgError.ErrWaCLI
+ }
+ utils.MustLogin(client)
+
+ participantsJID, err := service.participantToJID(ctx, request.Participants)
if err != nil {
return
}
@@ -66,7 +81,7 @@ func (service serviceGroup) CreateGroup(ctx context.Context, request domainGroup
GroupLinkedParent: types.GroupLinkedParent{},
}
- groupInfo, err := whatsapp.GetClient().CreateGroup(ctx, groupConfig)
+ groupInfo, err := client.CreateGroup(ctx, groupConfig)
if err != nil {
return
}
@@ -78,9 +93,14 @@ func (service serviceGroup) GetGroupInfoFromLink(ctx context.Context, request do
if err = validations.ValidateGetGroupInfoFromLink(ctx, request); err != nil {
return response, err
}
- utils.MustLogin(whatsapp.GetClient())
- groupInfo, err := whatsapp.GetClient().GetGroupInfoFromLink(ctx, request.Link)
+ client := whatsapp.ClientFromContext(ctx)
+ if client == nil {
+ return response, pkgError.ErrWaCLI
+ }
+ utils.MustLogin(client)
+
+ groupInfo, err := client.GetGroupInfoFromLink(ctx, request.Link)
if err != nil {
return response, err
}
@@ -104,19 +124,24 @@ func (service serviceGroup) ManageParticipant(ctx context.Context, request domai
if err = validations.ValidateParticipant(ctx, request); err != nil {
return result, err
}
- utils.MustLogin(whatsapp.GetClient())
- groupJID, err := utils.ValidateJidWithLogin(whatsapp.GetClient(), request.GroupID)
+ client := whatsapp.ClientFromContext(ctx)
+ if client == nil {
+ return result, pkgError.ErrWaCLI
+ }
+ utils.MustLogin(client)
+
+ groupJID, err := utils.ValidateJidWithLogin(client, request.GroupID)
if err != nil {
return result, err
}
- participantsJID, err := service.participantToJID(request.Participants)
+ participantsJID, err := service.participantToJID(ctx, request.Participants)
if err != nil {
return result, err
}
- participants, err := whatsapp.GetClient().UpdateGroupParticipants(ctx, groupJID, participantsJID, request.Action)
+ participants, err := client.UpdateGroupParticipants(ctx, groupJID, participantsJID, request.Action)
if err != nil {
return result, err
}
@@ -145,12 +170,17 @@ func (service serviceGroup) GetGroupParticipants(ctx context.Context, request do
return response, err
}
- groupJID, err := utils.ValidateJidWithLogin(whatsapp.GetClient(), request.GroupID)
+ client := whatsapp.ClientFromContext(ctx)
+ if client == nil {
+ return response, pkgError.ErrWaCLI
+ }
+
+ groupJID, err := utils.ValidateJidWithLogin(client, request.GroupID)
if err != nil {
return response, err
}
- groupInfo, err := whatsapp.GetClient().GetGroupInfo(ctx, groupJID)
+ groupInfo, err := client.GetGroupInfo(ctx, groupJID)
if err != nil {
return response, err
}
@@ -181,12 +211,17 @@ func (service serviceGroup) GetGroupRequestParticipants(ctx context.Context, req
return result, err
}
- groupJID, err := utils.ValidateJidWithLogin(whatsapp.GetClient(), request.GroupID)
+ client := whatsapp.ClientFromContext(ctx)
+ if client == nil {
+ return result, pkgError.ErrWaCLI
+ }
+
+ groupJID, err := utils.ValidateJidWithLogin(client, request.GroupID)
if err != nil {
return result, err
}
- participants, err := whatsapp.GetClient().GetGroupRequestParticipants(ctx, groupJID)
+ participants, err := client.GetGroupRequestParticipants(ctx, groupJID)
if err != nil {
return result, err
}
@@ -200,14 +235,14 @@ func (service serviceGroup) GetGroupRequestParticipants(ctx context.Context, req
// Fetch user info for verified business names (ignore errors)
userInfoMap := make(map[types.JID]types.UserInfo)
if len(jids) > 0 {
- userInfoMap, _ = whatsapp.GetClient().GetUserInfo(ctx, jids)
+ userInfoMap, _ = client.GetUserInfo(ctx, jids)
}
for _, participant := range participants {
displayName := ""
// Try contact store first (for known contacts)
- if contact, err := whatsapp.GetClient().Store.Contacts.GetContact(ctx, participant.JID); err == nil && contact.FullName != "" {
+ if contact, err := client.Store.Contacts.GetContact(ctx, participant.JID); err == nil && contact.FullName != "" {
displayName = contact.FullName
} else if info, ok := userInfoMap[participant.JID]; ok && info.VerifiedName != nil && info.VerifiedName.Details != nil {
// Fall back to verified business name
@@ -230,17 +265,22 @@ func (service serviceGroup) ManageGroupRequestParticipants(ctx context.Context,
return result, err
}
- groupJID, err := utils.ValidateJidWithLogin(whatsapp.GetClient(), request.GroupID)
+ client := whatsapp.ClientFromContext(ctx)
+ if client == nil {
+ return result, pkgError.ErrWaCLI
+ }
+
+ groupJID, err := utils.ValidateJidWithLogin(client, request.GroupID)
if err != nil {
return result, err
}
- participantsJID, err := service.participantToJID(request.Participants)
+ participantsJID, err := service.participantToJID(ctx, request.Participants)
if err != nil {
return result, err
}
- participants, err := whatsapp.GetClient().UpdateGroupRequestParticipants(ctx, groupJID, participantsJID, request.Action)
+ participants, err := client.UpdateGroupRequestParticipants(ctx, groupJID, participantsJID, request.Action)
if err != nil {
return result, err
}
@@ -264,12 +304,17 @@ func (service serviceGroup) ManageGroupRequestParticipants(ctx context.Context,
return result, nil
}
-func (service serviceGroup) participantToJID(participants []string) ([]types.JID, error) {
+func (service serviceGroup) participantToJID(ctx context.Context, participants []string) ([]types.JID, error) {
+ client := whatsapp.ClientFromContext(ctx)
+ if client == nil {
+ return nil, pkgError.ErrWaCLI
+ }
+
var participantsJID []types.JID
for _, participant := range participants {
formattedParticipant := participant + config.WhatsappTypeUser
- if !utils.IsOnWhatsapp(whatsapp.GetClient(), formattedParticipant) {
+ if !utils.IsOnWhatsapp(client, formattedParticipant) {
return nil, pkgError.ErrUserNotRegistered
}
@@ -285,7 +330,12 @@ func (service serviceGroup) SetGroupPhoto(ctx context.Context, request domainGro
return pictureID, err
}
- groupJID, err := utils.ValidateJidWithLogin(whatsapp.GetClient(), request.GroupID)
+ client := whatsapp.ClientFromContext(ctx)
+ if client == nil {
+ return pictureID, pkgError.ErrWaCLI
+ }
+
+ groupJID, err := utils.ValidateJidWithLogin(client, request.GroupID)
if err != nil {
return pictureID, err
}
@@ -308,7 +358,7 @@ func (service serviceGroup) SetGroupPhoto(ctx context.Context, request domainGro
photoBytes = processedImageBuffer.Bytes()
}
- pictureID, err = whatsapp.GetClient().SetGroupPhoto(ctx, groupJID, photoBytes)
+ pictureID, err = client.SetGroupPhoto(ctx, groupJID, photoBytes)
if err != nil {
logrus.Printf("Failed to set group photo: %v", err)
return pictureID, err
@@ -322,12 +372,17 @@ func (service serviceGroup) SetGroupName(ctx context.Context, request domainGrou
return err
}
- groupJID, err := utils.ValidateJidWithLogin(whatsapp.GetClient(), request.GroupID)
+ client := whatsapp.ClientFromContext(ctx)
+ if client == nil {
+ return pkgError.ErrWaCLI
+ }
+
+ groupJID, err := utils.ValidateJidWithLogin(client, request.GroupID)
if err != nil {
return err
}
- return whatsapp.GetClient().SetGroupName(ctx, groupJID, request.Name)
+ return client.SetGroupName(ctx, groupJID, request.Name)
}
func (service serviceGroup) SetGroupLocked(ctx context.Context, request domainGroup.SetGroupLockedRequest) (err error) {
@@ -335,12 +390,17 @@ func (service serviceGroup) SetGroupLocked(ctx context.Context, request domainGr
return err
}
- groupJID, err := utils.ValidateJidWithLogin(whatsapp.GetClient(), request.GroupID)
+ client := whatsapp.ClientFromContext(ctx)
+ if client == nil {
+ return pkgError.ErrWaCLI
+ }
+
+ groupJID, err := utils.ValidateJidWithLogin(client, request.GroupID)
if err != nil {
return err
}
- return whatsapp.GetClient().SetGroupLocked(ctx, groupJID, request.Locked)
+ return client.SetGroupLocked(ctx, groupJID, request.Locked)
}
func (service serviceGroup) SetGroupAnnounce(ctx context.Context, request domainGroup.SetGroupAnnounceRequest) (err error) {
@@ -348,12 +408,17 @@ func (service serviceGroup) SetGroupAnnounce(ctx context.Context, request domain
return err
}
- groupJID, err := utils.ValidateJidWithLogin(whatsapp.GetClient(), request.GroupID)
+ client := whatsapp.ClientFromContext(ctx)
+ if client == nil {
+ return pkgError.ErrWaCLI
+ }
+
+ groupJID, err := utils.ValidateJidWithLogin(client, request.GroupID)
if err != nil {
return err
}
- return whatsapp.GetClient().SetGroupAnnounce(ctx, groupJID, request.Announce)
+ return client.SetGroupAnnounce(ctx, groupJID, request.Announce)
}
func (service serviceGroup) SetGroupTopic(ctx context.Context, request domainGroup.SetGroupTopicRequest) (err error) {
@@ -361,13 +426,18 @@ func (service serviceGroup) SetGroupTopic(ctx context.Context, request domainGro
return err
}
- groupJID, err := utils.ValidateJidWithLogin(whatsapp.GetClient(), request.GroupID)
+ client := whatsapp.ClientFromContext(ctx)
+ if client == nil {
+ return pkgError.ErrWaCLI
+ }
+
+ groupJID, err := utils.ValidateJidWithLogin(client, request.GroupID)
if err != nil {
return err
}
// SetGroupTopic with auto-generated IDs (previousID and newID will be handled automatically)
- return whatsapp.GetClient().SetGroupTopic(ctx, groupJID, "", "", request.Topic)
+ return client.SetGroupTopic(ctx, groupJID, "", "", request.Topic)
}
// GroupInfo retrieves detailed information about a WhatsApp group
@@ -377,17 +447,22 @@ func (service serviceGroup) GroupInfo(ctx context.Context, request domainGroup.G
return response, err
}
+ client := whatsapp.ClientFromContext(ctx)
+ if client == nil {
+ return response, pkgError.ErrWaCLI
+ }
+
// Ensure we are logged in
- utils.MustLogin(whatsapp.GetClient())
+ utils.MustLogin(client)
// Validate and parse the provided group JID / ID
- groupJID, err := utils.ValidateJidWithLogin(whatsapp.GetClient(), request.GroupID)
+ groupJID, err := utils.ValidateJidWithLogin(client, request.GroupID)
if err != nil {
return response, err
}
// Fetch group information from WhatsApp
- groupInfo, err := whatsapp.GetClient().GetGroupInfo(ctx, groupJID)
+ groupInfo, err := client.GetGroupInfo(ctx, groupJID)
if err != nil {
return response, err
}
@@ -404,14 +479,19 @@ func (service serviceGroup) GetGroupInviteLink(ctx context.Context, request doma
if err = validations.ValidateGetGroupInviteLink(ctx, request); err != nil {
return response, err
}
- utils.MustLogin(whatsapp.GetClient())
- groupJID, err := utils.ValidateJidWithLogin(whatsapp.GetClient(), request.GroupID)
+ client := whatsapp.ClientFromContext(ctx)
+ if client == nil {
+ return response, pkgError.ErrWaCLI
+ }
+ utils.MustLogin(client)
+
+ groupJID, err := utils.ValidateJidWithLogin(client, request.GroupID)
if err != nil {
return response, err
}
- inviteLink, err := whatsapp.GetClient().GetGroupInviteLink(ctx, groupJID, request.Reset)
+ inviteLink, err := client.GetGroupInviteLink(ctx, groupJID, request.Reset)
if err != nil {
return response, err
}
diff --git a/src/usecase/message.go b/src/usecase/message.go
index 7c5bf64a..469efae1 100644
--- a/src/usecase/message.go
+++ b/src/usecase/message.go
@@ -11,6 +11,7 @@ import (
domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
domainMessage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/message"
"github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/whatsapp"
+ pkgError "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/error"
"github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
"github.com/aldinokemal/go-whatsapp-web-multidevice/validations"
"github.com/sirupsen/logrus"
@@ -37,13 +38,19 @@ func (service serviceMessage) MarkAsRead(ctx context.Context, request domainMess
if err = validations.ValidateMarkAsRead(ctx, request); err != nil {
return response, err
}
- dataWaRecipient, err := utils.ValidateJidWithLogin(whatsapp.GetClient(), request.Phone)
+
+ client := whatsapp.ClientFromContext(ctx)
+ if client == nil {
+ return response, pkgError.ErrWaCLI
+ }
+
+ dataWaRecipient, err := utils.ValidateJidWithLogin(client, request.Phone)
if err != nil {
return response, err
}
ids := []types.MessageID{request.MessageID}
- if err = whatsapp.GetClient().MarkRead(ctx, ids, time.Now(), dataWaRecipient, *whatsapp.GetClient().Store.ID); err != nil {
+ if err = client.MarkRead(ctx, ids, time.Now(), dataWaRecipient, *client.Store.ID); err != nil {
return response, err
}
@@ -51,7 +58,7 @@ func (service serviceMessage) MarkAsRead(ctx context.Context, request domainMess
"phone": request.Phone,
"message_id": request.MessageID,
"chat": dataWaRecipient.String(),
- "sender": whatsapp.GetClient().Store.ID.String(),
+ "sender": client.Store.ID.String(),
})
response.MessageID = request.MessageID
@@ -63,7 +70,13 @@ func (service serviceMessage) ReactMessage(ctx context.Context, request domainMe
if err = validations.ValidateReactMessage(ctx, request); err != nil {
return response, err
}
- dataWaRecipient, err := utils.ValidateJidWithLogin(whatsapp.GetClient(), request.Phone)
+
+ client := whatsapp.ClientFromContext(ctx)
+ if client == nil {
+ return response, pkgError.ErrWaCLI
+ }
+
+ dataWaRecipient, err := utils.ValidateJidWithLogin(client, request.Phone)
if err != nil {
return response, err
}
@@ -79,7 +92,7 @@ func (service serviceMessage) ReactMessage(ctx context.Context, request domainMe
SenderTimestampMS: proto.Int64(time.Now().UnixMilli()),
},
}
- ts, err := whatsapp.GetClient().SendMessage(ctx, dataWaRecipient, msg)
+ ts, err := client.SendMessage(ctx, dataWaRecipient, msg)
if err != nil {
return response, err
}
@@ -93,12 +106,18 @@ func (service serviceMessage) RevokeMessage(ctx context.Context, request domainM
if err = validations.ValidateRevokeMessage(ctx, request); err != nil {
return response, err
}
- dataWaRecipient, err := utils.ValidateJidWithLogin(whatsapp.GetClient(), request.Phone)
+
+ client := whatsapp.ClientFromContext(ctx)
+ if client == nil {
+ return response, pkgError.ErrWaCLI
+ }
+
+ dataWaRecipient, err := utils.ValidateJidWithLogin(client, request.Phone)
if err != nil {
return response, err
}
- ts, err := whatsapp.GetClient().SendMessage(context.Background(), dataWaRecipient, whatsapp.GetClient().BuildRevoke(dataWaRecipient, types.EmptyJID, request.MessageID))
+ ts, err := client.SendMessage(ctx, dataWaRecipient, client.BuildRevoke(dataWaRecipient, types.EmptyJID, request.MessageID))
if err != nil {
return response, err
}
@@ -112,7 +131,13 @@ func (service serviceMessage) DeleteMessage(ctx context.Context, request domainM
if err = validations.ValidateDeleteMessage(ctx, request); err != nil {
return err
}
- dataWaRecipient, err := utils.ValidateJidWithLogin(whatsapp.GetClient(), request.Phone)
+
+ client := whatsapp.ClientFromContext(ctx)
+ if client == nil {
+ return pkgError.ErrWaCLI
+ }
+
+ dataWaRecipient, err := utils.ValidateJidWithLogin(client, request.Phone)
if err != nil {
return err
}
@@ -126,7 +151,7 @@ func (service serviceMessage) DeleteMessage(ctx context.Context, request domainM
Timestamp: time.Now(),
Type: appstate.WAPatchRegularHigh,
Mutations: []appstate.MutationInfo{{
- Index: []string{appstate.IndexDeleteMessageForMe, dataWaRecipient.String(), request.MessageID, isFromMe, whatsapp.GetClient().Store.ID.String()},
+ Index: []string{appstate.IndexDeleteMessageForMe, dataWaRecipient.String(), request.MessageID, isFromMe, client.Store.ID.String()},
Value: &waSyncAction.SyncActionValue{
DeleteMessageForMeAction: &waSyncAction.DeleteMessageForMeAction{
DeleteMedia: proto.Bool(true),
@@ -136,7 +161,7 @@ func (service serviceMessage) DeleteMessage(ctx context.Context, request domainM
}},
}
- if err = whatsapp.GetClient().SendAppState(ctx, patchInfo); err != nil {
+ if err = client.SendAppState(ctx, patchInfo); err != nil {
return err
}
return nil
@@ -147,13 +172,18 @@ func (service serviceMessage) UpdateMessage(ctx context.Context, request domainM
return response, err
}
- dataWaRecipient, err := utils.ValidateJidWithLogin(whatsapp.GetClient(), request.Phone)
+ client := whatsapp.ClientFromContext(ctx)
+ if client == nil {
+ return response, pkgError.ErrWaCLI
+ }
+
+ dataWaRecipient, err := utils.ValidateJidWithLogin(client, request.Phone)
if err != nil {
return response, err
}
msg := &waE2E.Message{Conversation: proto.String(request.Message)}
- ts, err := whatsapp.GetClient().SendMessage(context.Background(), dataWaRecipient, whatsapp.GetClient().BuildEdit(dataWaRecipient, request.MessageID, msg))
+ ts, err := client.SendMessage(ctx, dataWaRecipient, client.BuildEdit(dataWaRecipient, request.MessageID, msg))
if err != nil {
return response, err
}
@@ -169,7 +199,12 @@ func (service serviceMessage) StarMessage(ctx context.Context, request domainMes
return err
}
- dataWaRecipient, err := utils.ValidateJidWithLogin(whatsapp.GetClient(), request.Phone)
+ client := whatsapp.ClientFromContext(ctx)
+ if client == nil {
+ return pkgError.ErrWaCLI
+ }
+
+ dataWaRecipient, err := utils.ValidateJidWithLogin(client, request.Phone)
if err != nil {
return err
}
@@ -179,9 +214,9 @@ func (service serviceMessage) StarMessage(ctx context.Context, request domainMes
isFromMe = false
}
- patchInfo := appstate.BuildStar(dataWaRecipient.ToNonAD(), *whatsapp.GetClient().Store.ID, request.MessageID, isFromMe, request.IsStarred)
+ patchInfo := appstate.BuildStar(dataWaRecipient.ToNonAD(), *client.Store.ID, request.MessageID, isFromMe, request.IsStarred)
- if err = whatsapp.GetClient().SendAppState(ctx, patchInfo); err != nil {
+ if err = client.SendAppState(ctx, patchInfo); err != nil {
return err
}
return nil
@@ -193,7 +228,12 @@ func (service serviceMessage) DownloadMedia(ctx context.Context, request domainM
return response, err
}
- dataWaRecipient, err := utils.ValidateJidWithLogin(whatsapp.GetClient(), request.Phone)
+ client := whatsapp.ClientFromContext(ctx)
+ if client == nil {
+ return response, pkgError.ErrWaCLI
+ }
+
+ dataWaRecipient, err := utils.ValidateJidWithLogin(client, request.Phone)
if err != nil {
return response, err
}
@@ -277,7 +317,7 @@ func (service serviceMessage) DownloadMedia(ctx context.Context, request domainM
}
// Download the media using existing utils.ExtractMedia function
- extractedMedia, err := utils.ExtractMedia(ctx, whatsapp.GetClient(), dateDir, downloadableMsg.(whatsmeow.DownloadableMessage))
+ extractedMedia, err := utils.ExtractMedia(ctx, client, dateDir, downloadableMsg.(whatsmeow.DownloadableMessage))
if err != nil {
return response, fmt.Errorf("failed to download media: %v", err)
}
diff --git a/src/usecase/newsletter.go b/src/usecase/newsletter.go
index 1ab37806..4cc994ec 100644
--- a/src/usecase/newsletter.go
+++ b/src/usecase/newsletter.go
@@ -5,6 +5,7 @@ import (
domainNewsletter "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/newsletter"
"github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/whatsapp"
+ pkgError "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/error"
"github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
"github.com/aldinokemal/go-whatsapp-web-multidevice/validations"
)
@@ -20,10 +21,15 @@ func (service serviceNewsletter) Unfollow(ctx context.Context, request domainNew
return err
}
- JID, err := utils.ValidateJidWithLogin(whatsapp.GetClient(), request.NewsletterID)
+ client := whatsapp.ClientFromContext(ctx)
+ if client == nil {
+ return pkgError.ErrWaCLI
+ }
+
+ JID, err := utils.ValidateJidWithLogin(client, request.NewsletterID)
if err != nil {
return err
}
- return whatsapp.GetClient().UnfollowNewsletter(ctx, JID)
+ return client.UnfollowNewsletter(ctx, JID)
}
diff --git a/src/usecase/send.go b/src/usecase/send.go
index cb65d72a..d7009bf9 100644
--- a/src/usecase/send.go
+++ b/src/usecase/send.go
@@ -45,16 +45,16 @@ func NewSendService(appService app.IAppUsecase, chatStorageRepo domainChatStorag
}
// wrapSendMessage wraps the message sending process with message ID saving
-func (service serviceSend) wrapSendMessage(ctx context.Context, recipient types.JID, msg *waE2E.Message, content string) (whatsmeow.SendResponse, error) {
- ts, err := whatsapp.GetClient().SendMessage(ctx, recipient, msg)
+func (service serviceSend) wrapSendMessage(ctx context.Context, client *whatsmeow.Client, recipient types.JID, msg *waE2E.Message, content string) (whatsmeow.SendResponse, error) {
+ ts, err := client.SendMessage(ctx, recipient, msg)
if err != nil {
return whatsmeow.SendResponse{}, err
}
// Store the sent message using chatstorage
senderJID := ""
- if whatsapp.GetClient().Store.ID != nil {
- senderJID = whatsapp.GetClient().Store.ID.String()
+ if client.Store.ID != nil {
+ senderJID = client.Store.ID.String()
}
// Store message asynchronously with timeout
@@ -80,7 +80,13 @@ func (service serviceSend) SendText(ctx context.Context, request domainSend.Mess
if err != nil {
return response, err
}
- dataWaRecipient, err := utils.ValidateJidWithLogin(whatsapp.GetClient(), request.BaseRequest.Phone)
+
+ client := whatsapp.ClientFromContext(ctx)
+ if client == nil {
+ return response, pkgError.ErrWaCLI
+ }
+
+ dataWaRecipient, err := utils.ValidateJidWithLogin(client, request.BaseRequest.Phone)
if err != nil {
return response, err
}
@@ -159,7 +165,7 @@ func (service serviceSend) SendText(ctx context.Context, request domainSend.Mess
}
}
- ts, err := service.wrapSendMessage(ctx, dataWaRecipient, msg, request.Message)
+ ts, err := service.wrapSendMessage(ctx, client, dataWaRecipient, msg, request.Message)
if err != nil {
return response, err
}
@@ -174,7 +180,13 @@ func (service serviceSend) SendImage(ctx context.Context, request domainSend.Ima
if err != nil {
return response, err
}
- dataWaRecipient, err := utils.ValidateJidWithLogin(whatsapp.GetClient(), request.Phone)
+
+ client := whatsapp.ClientFromContext(ctx)
+ if client == nil {
+ return response, pkgError.ErrWaCLI
+ }
+
+ dataWaRecipient, err := utils.ValidateJidWithLogin(client, request.Phone)
if err != nil {
return response, err
}
@@ -273,7 +285,7 @@ func (service serviceSend) SendImage(ctx context.Context, request domainSend.Ima
if err != nil {
return response, err
}
- uploadedImage, err := service.uploadMedia(ctx, whatsmeow.MediaImage, dataWaImage, dataWaRecipient)
+ uploadedImage, err := service.uploadMedia(ctx, client, whatsmeow.MediaImage, dataWaImage, dataWaRecipient)
if err != nil {
fmt.Printf("failed to upload file: %v", err)
return response, err
@@ -315,7 +327,7 @@ func (service serviceSend) SendImage(ctx context.Context, request domainSend.Ima
if request.Caption != "" {
caption = "πŸ–ΌοΈ " + request.Caption
}
- ts, err := service.wrapSendMessage(ctx, dataWaRecipient, msg, caption)
+ ts, err := service.wrapSendMessage(ctx, client, dataWaRecipient, msg, caption)
go func() {
errDelete := utils.RemoveFile(0, deletedItems...)
if errDelete != nil {
@@ -336,7 +348,13 @@ func (service serviceSend) SendFile(ctx context.Context, request domainSend.File
if err != nil {
return response, err
}
- dataWaRecipient, err := utils.ValidateJidWithLogin(whatsapp.GetClient(), request.BaseRequest.Phone)
+
+ client := whatsapp.ClientFromContext(ctx)
+ if client == nil {
+ return response, pkgError.ErrWaCLI
+ }
+
+ dataWaRecipient, err := utils.ValidateJidWithLogin(client, request.BaseRequest.Phone)
if err != nil {
return response, err
}
@@ -345,7 +363,7 @@ func (service serviceSend) SendFile(ctx context.Context, request domainSend.File
fileMimeType := resolveDocumentMIME(request.File.Filename, fileBytes)
// Send to WA server
- uploadedFile, err := service.uploadMedia(ctx, whatsmeow.MediaDocument, fileBytes, dataWaRecipient)
+ uploadedFile, err := service.uploadMedia(ctx, client, whatsmeow.MediaDocument, fileBytes, dataWaRecipient)
if err != nil {
fmt.Printf("Failed to upload file: %v", err)
return response, err
@@ -382,7 +400,7 @@ func (service serviceSend) SendFile(ctx context.Context, request domainSend.File
if request.Caption != "" {
caption = "πŸ“„ " + request.Caption
}
- ts, err := service.wrapSendMessage(ctx, dataWaRecipient, msg, caption)
+ ts, err := service.wrapSendMessage(ctx, client, dataWaRecipient, msg, caption)
if err != nil {
return response, err
}
@@ -412,7 +430,13 @@ func (service serviceSend) SendVideo(ctx context.Context, request domainSend.Vid
if err != nil {
return response, err
}
- dataWaRecipient, err := utils.ValidateJidWithLogin(whatsapp.GetClient(), request.BaseRequest.Phone)
+
+ client := whatsapp.ClientFromContext(ctx)
+ if client == nil {
+ return response, pkgError.ErrWaCLI
+ }
+
+ dataWaRecipient, err := utils.ValidateJidWithLogin(client, request.BaseRequest.Phone)
if err != nil {
return response, err
}
@@ -529,7 +553,7 @@ func (service serviceSend) SendVideo(ctx context.Context, request domainSend.Vid
if err != nil {
return response, err
}
- uploaded, err := service.uploadMedia(ctx, whatsmeow.MediaVideo, dataWaVideo, dataWaRecipient)
+ uploaded, err := service.uploadMedia(ctx, client, whatsmeow.MediaVideo, dataWaVideo, dataWaRecipient)
if err != nil {
return response, pkgError.InternalServerError(fmt.Sprintf("Failed to upload file: %v", err))
}
@@ -572,7 +596,7 @@ func (service serviceSend) SendVideo(ctx context.Context, request domainSend.Vid
if request.Caption != "" {
caption = "πŸŽ₯ " + request.Caption
}
- ts, err := service.wrapSendMessage(ctx, dataWaRecipient, msg, caption)
+ ts, err := service.wrapSendMessage(ctx, client, dataWaRecipient, msg, caption)
if err != nil {
return response, err
}
@@ -587,7 +611,13 @@ func (service serviceSend) SendContact(ctx context.Context, request domainSend.C
if err != nil {
return response, err
}
- dataWaRecipient, err := utils.ValidateJidWithLogin(whatsapp.GetClient(), request.BaseRequest.Phone)
+
+ client := whatsapp.ClientFromContext(ctx)
+ if client == nil {
+ return response, pkgError.ErrWaCLI
+ }
+
+ dataWaRecipient, err := utils.ValidateJidWithLogin(client, request.BaseRequest.Phone)
if err != nil {
return response, err
}
@@ -615,7 +645,7 @@ func (service serviceSend) SendContact(ctx context.Context, request domainSend.C
content := "πŸ‘€ " + request.ContactName
- ts, err := service.wrapSendMessage(ctx, dataWaRecipient, msg, content)
+ ts, err := service.wrapSendMessage(ctx, client, dataWaRecipient, msg, content)
if err != nil {
return response, err
}
@@ -630,7 +660,13 @@ func (service serviceSend) SendLink(ctx context.Context, request domainSend.Link
if err != nil {
return response, err
}
- dataWaRecipient, err := utils.ValidateJidWithLogin(whatsapp.GetClient(), request.BaseRequest.Phone)
+
+ client := whatsapp.ClientFromContext(ctx)
+ if client == nil {
+ return response, pkgError.ErrWaCLI
+ }
+
+ dataWaRecipient, err := utils.ValidateJidWithLogin(client, request.BaseRequest.Phone)
if err != nil {
return response, err
}
@@ -672,7 +708,7 @@ func (service serviceSend) SendLink(ctx context.Context, request domainSend.Link
// If we have a thumbnail image, upload it to WhatsApp's servers
if len(metadata.ImageThumb) > 0 && metadata.Height != nil && metadata.Width != nil {
- uploadedThumb, err := service.uploadMedia(ctx, whatsmeow.MediaLinkThumbnail, metadata.ImageThumb, dataWaRecipient)
+ uploadedThumb, err := service.uploadMedia(ctx, client, whatsmeow.MediaLinkThumbnail, metadata.ImageThumb, dataWaRecipient)
if err == nil {
// Update the message with the uploaded thumbnail information
msg.ExtendedTextMessage.ThumbnailDirectPath = proto.String(uploadedThumb.DirectPath)
@@ -690,7 +726,7 @@ func (service serviceSend) SendLink(ctx context.Context, request domainSend.Link
if request.Caption != "" {
content = "πŸ”— " + request.Caption
}
- ts, err := service.wrapSendMessage(ctx, dataWaRecipient, msg, content)
+ ts, err := service.wrapSendMessage(ctx, client, dataWaRecipient, msg, content)
if err != nil {
return response, err
}
@@ -705,7 +741,13 @@ func (service serviceSend) SendLocation(ctx context.Context, request domainSend.
if err != nil {
return response, err
}
- dataWaRecipient, err := utils.ValidateJidWithLogin(whatsapp.GetClient(), request.BaseRequest.Phone)
+
+ client := whatsapp.ClientFromContext(ctx)
+ if client == nil {
+ return response, pkgError.ErrWaCLI
+ }
+
+ dataWaRecipient, err := utils.ValidateJidWithLogin(client, request.BaseRequest.Phone)
if err != nil {
return response, err
}
@@ -735,7 +777,7 @@ func (service serviceSend) SendLocation(ctx context.Context, request domainSend.
content := "πŸ“ " + request.Latitude + ", " + request.Longitude
// Send WhatsApp Message Proto
- ts, err := service.wrapSendMessage(ctx, dataWaRecipient, msg, content)
+ ts, err := service.wrapSendMessage(ctx, client, dataWaRecipient, msg, content)
if err != nil {
return response, err
}
@@ -752,7 +794,12 @@ func (service serviceSend) SendAudio(ctx context.Context, request domainSend.Aud
return response, err
}
- dataWaRecipient, err := utils.ValidateJidWithLogin(whatsapp.GetClient(), request.BaseRequest.Phone)
+ client := whatsapp.ClientFromContext(ctx)
+ if client == nil {
+ return response, pkgError.ErrWaCLI
+ }
+
+ dataWaRecipient, err := utils.ValidateJidWithLogin(client, request.BaseRequest.Phone)
if err != nil {
return response, err
}
@@ -775,7 +822,7 @@ func (service serviceSend) SendAudio(ctx context.Context, request domainSend.Aud
}
// upload to WhatsApp servers
- audioUploaded, err := service.uploadMedia(ctx, whatsmeow.MediaAudio, audioBytes, dataWaRecipient)
+ audioUploaded, err := service.uploadMedia(ctx, client, whatsmeow.MediaAudio, audioBytes, dataWaRecipient)
if err != nil {
err = pkgError.WaUploadMediaError(fmt.Sprintf("Failed to upload audio: %v", err))
return response, err
@@ -809,7 +856,7 @@ func (service serviceSend) SendAudio(ctx context.Context, request domainSend.Aud
content := "🎡 Audio"
- ts, err := service.wrapSendMessage(ctx, dataWaRecipient, msg, content)
+ ts, err := service.wrapSendMessage(ctx, client, dataWaRecipient, msg, content)
if err != nil {
return response, err
}
@@ -824,14 +871,20 @@ func (service serviceSend) SendPoll(ctx context.Context, request domainSend.Poll
if err != nil {
return response, err
}
- dataWaRecipient, err := utils.ValidateJidWithLogin(whatsapp.GetClient(), request.BaseRequest.Phone)
+
+ client := whatsapp.ClientFromContext(ctx)
+ if client == nil {
+ return response, pkgError.ErrWaCLI
+ }
+
+ dataWaRecipient, err := utils.ValidateJidWithLogin(client, request.BaseRequest.Phone)
if err != nil {
return response, err
}
content := "πŸ“Š " + request.Question
- msg := whatsapp.GetClient().BuildPollCreation(request.Question, request.Options, request.MaxAnswer)
+ msg := client.BuildPollCreation(request.Question, request.Options, request.MaxAnswer)
if request.BaseRequest.Duration != nil && *request.BaseRequest.Duration > 0 {
if msg.PollCreationMessage.ContextInfo == nil {
@@ -840,7 +893,7 @@ func (service serviceSend) SendPoll(ctx context.Context, request domainSend.Poll
msg.PollCreationMessage.ContextInfo.Expiration = proto.Uint32(uint32(*request.BaseRequest.Duration))
}
- ts, err := service.wrapSendMessage(ctx, dataWaRecipient, msg, content)
+ ts, err := service.wrapSendMessage(ctx, client, dataWaRecipient, msg, content)
if err != nil {
return response, err
}
@@ -856,7 +909,12 @@ func (service serviceSend) SendPresence(ctx context.Context, request domainSend.
return response, err
}
- err = whatsapp.GetClient().SendPresence(ctx, types.Presence(request.Type))
+ client := whatsapp.ClientFromContext(ctx)
+ if client == nil {
+ return response, pkgError.ErrWaCLI
+ }
+
+ err = client.SendPresence(ctx, types.Presence(request.Type))
if err != nil {
return response, err
}
@@ -872,7 +930,12 @@ func (service serviceSend) SendChatPresence(ctx context.Context, request domainS
return response, err
}
- userJid, err := utils.ValidateJidWithLogin(whatsapp.GetClient(), request.Phone)
+ client := whatsapp.ClientFromContext(ctx)
+ if client == nil {
+ return response, pkgError.ErrWaCLI
+ }
+
+ userJid, err := utils.ValidateJidWithLogin(client, request.Phone)
if err != nil {
return response, err
}
@@ -894,7 +957,7 @@ func (service serviceSend) SendChatPresence(ctx context.Context, request domainS
return response, fmt.Errorf("invalid action: %s. Must be 'start' or 'stop'", request.Action)
}
- err = whatsapp.GetClient().SendChatPresence(ctx, userJid, presenceType, types.ChatPresenceMedia(""))
+ err = client.SendChatPresence(ctx, userJid, presenceType, types.ChatPresenceMedia(""))
if err != nil {
return response, err
}
@@ -904,11 +967,16 @@ func (service serviceSend) SendChatPresence(ctx context.Context, request domainS
return response, nil
}
-func (service serviceSend) getMentionFromText(_ context.Context, messages string) (result []string) {
+func (service serviceSend) getMentionFromText(ctx context.Context, messages string) (result []string) {
+ client := whatsapp.ClientFromContext(ctx)
+ if client == nil {
+ return result
+ }
+
mentions := utils.ContainsMention(messages)
for _, mention := range mentions {
// Get JID from phone number
- if dataWaRecipient, err := utils.ValidateJidWithLogin(whatsapp.GetClient(), mention); err == nil {
+ if dataWaRecipient, err := utils.ValidateJidWithLogin(client, mention); err == nil {
result = append(result, dataWaRecipient.String())
}
}
@@ -922,7 +990,12 @@ func (service serviceSend) SendSticker(ctx context.Context, request domainSend.S
return response, err
}
- dataWaRecipient, err := utils.ValidateJidWithLogin(whatsapp.GetClient(), request.Phone)
+ client := whatsapp.ClientFromContext(ctx)
+ if client == nil {
+ return response, pkgError.ErrWaCLI
+ }
+
+ dataWaRecipient, err := utils.ValidateJidWithLogin(client, request.Phone)
if err != nil {
return response, err
}
@@ -1050,7 +1123,7 @@ func (service serviceSend) SendSticker(ctx context.Context, request domainSend.S
}
// Upload sticker to WhatsApp servers
- stickerUploaded, err := service.uploadMedia(ctx, whatsmeow.MediaImage, stickerBytes, dataWaRecipient)
+ stickerUploaded, err := service.uploadMedia(ctx, client, whatsmeow.MediaImage, stickerBytes, dataWaRecipient)
if err != nil {
return response, pkgError.WaUploadMediaError(fmt.Sprintf("failed to upload sticker: %v", err))
}
@@ -1088,7 +1161,7 @@ func (service serviceSend) SendSticker(ctx context.Context, request domainSend.S
content := "🎨 Sticker"
// Send the sticker message
- ts, err := service.wrapSendMessage(ctx, dataWaRecipient, msg, content)
+ ts, err := service.wrapSendMessage(ctx, client, dataWaRecipient, msg, content)
if err != nil {
return response, err
}
@@ -1098,11 +1171,11 @@ func (service serviceSend) SendSticker(ctx context.Context, request domainSend.S
return response, nil
}
-func (service serviceSend) uploadMedia(ctx context.Context, mediaType whatsmeow.MediaType, media []byte, recipient types.JID) (uploaded whatsmeow.UploadResponse, err error) {
+func (service serviceSend) uploadMedia(ctx context.Context, client *whatsmeow.Client, mediaType whatsmeow.MediaType, media []byte, recipient types.JID) (uploaded whatsmeow.UploadResponse, err error) {
if recipient.Server == types.NewsletterServer {
- uploaded, err = whatsapp.GetClient().UploadNewsletter(ctx, media, mediaType)
+ uploaded, err = client.UploadNewsletter(ctx, media, mediaType)
} else {
- uploaded, err = whatsapp.GetClient().Upload(ctx, media, mediaType)
+ uploaded, err = client.Upload(ctx, media, mediaType)
}
return uploaded, err
}
diff --git a/src/usecase/user.go b/src/usecase/user.go
index b9378e36..23ed57c5 100644
--- a/src/usecase/user.go
+++ b/src/usecase/user.go
@@ -32,14 +32,20 @@ func (service serviceUser) Info(ctx context.Context, request domainUser.InfoRequ
if err != nil {
return response, err
}
+
+ client := whatsapp.ClientFromContext(ctx)
+ if client == nil {
+ return response, pkgError.ErrWaCLI
+ }
+
var jids []types.JID
- dataWaRecipient, err := utils.ValidateJidWithLogin(whatsapp.GetClient(), request.Phone)
+ dataWaRecipient, err := utils.ValidateJidWithLogin(client, request.Phone)
if err != nil {
return response, err
}
jids = append(jids, dataWaRecipient)
- resp, err := whatsapp.GetClient().GetUserInfo(ctx, jids)
+ resp, err := client.GetUserInfo(ctx, jids)
if err != nil {
return response, err
}
@@ -71,6 +77,10 @@ func (service serviceUser) Info(ctx context.Context, request domainUser.InfoRequ
}
func (service serviceUser) Avatar(ctx context.Context, request domainUser.AvatarRequest) (response domainUser.AvatarResponse, err error) {
+ client := whatsapp.ClientFromContext(ctx)
+ if client == nil {
+ return response, pkgError.ErrWaCLI
+ }
chanResp := make(chan domainUser.AvatarResponse)
chanErr := make(chan error)
@@ -81,11 +91,11 @@ func (service serviceUser) Avatar(ctx context.Context, request domainUser.Avatar
if err != nil {
chanErr <- err
}
- dataWaRecipient, err := utils.ValidateJidWithLogin(whatsapp.GetClient(), request.Phone)
+ dataWaRecipient, err := utils.ValidateJidWithLogin(client, request.Phone)
if err != nil {
chanErr <- err
}
- pic, err := whatsapp.GetClient().GetProfilePictureInfo(ctx, dataWaRecipient, &whatsmeow.GetProfilePictureParams{
+ pic, err := client.GetProfilePictureInfo(ctx, dataWaRecipient, &whatsmeow.GetProfilePictureParams{
Preview: request.IsPreview,
IsCommunity: request.IsCommunity,
})
@@ -118,9 +128,13 @@ func (service serviceUser) Avatar(ctx context.Context, request domainUser.Avatar
}
func (service serviceUser) MyListGroups(ctx context.Context) (response domainUser.MyListGroupsResponse, err error) {
- utils.MustLogin(whatsapp.GetClient())
+ client := whatsapp.ClientFromContext(ctx)
+ if client == nil {
+ return response, pkgError.ErrWaCLI
+ }
+ utils.MustLogin(client)
- groups, err := whatsapp.GetClient().GetJoinedGroups(ctx)
+ groups, err := client.GetJoinedGroups(ctx)
if err != nil {
return
}
@@ -131,10 +145,14 @@ func (service serviceUser) MyListGroups(ctx context.Context) (response domainUse
return response, nil
}
-func (service serviceUser) MyListNewsletter(_ context.Context) (response domainUser.MyListNewsletterResponse, err error) {
- utils.MustLogin(whatsapp.GetClient())
+func (service serviceUser) MyListNewsletter(ctx context.Context) (response domainUser.MyListNewsletterResponse, err error) {
+ client := whatsapp.ClientFromContext(ctx)
+ if client == nil {
+ return response, pkgError.ErrWaCLI
+ }
+ utils.MustLogin(client)
- datas, err := whatsapp.GetClient().GetSubscribedNewsletters(context.Background())
+ datas, err := client.GetSubscribedNewsletters(ctx)
if err != nil {
return
}
@@ -146,9 +164,13 @@ func (service serviceUser) MyListNewsletter(_ context.Context) (response domainU
}
func (service serviceUser) MyPrivacySetting(ctx context.Context) (response domainUser.MyPrivacySettingResponse, err error) {
- utils.MustLogin(whatsapp.GetClient())
+ client := whatsapp.ClientFromContext(ctx)
+ if client == nil {
+ return response, pkgError.ErrWaCLI
+ }
+ utils.MustLogin(client)
- resp, err := whatsapp.GetClient().TryFetchPrivacySettings(ctx, true)
+ resp, err := client.TryFetchPrivacySettings(ctx, true)
if err != nil {
return
}
@@ -161,9 +183,13 @@ func (service serviceUser) MyPrivacySetting(ctx context.Context) (response domai
}
func (service serviceUser) MyListContacts(ctx context.Context) (response domainUser.MyListContactsResponse, err error) {
- utils.MustLogin(whatsapp.GetClient())
+ client := whatsapp.ClientFromContext(ctx)
+ if client == nil {
+ return response, pkgError.ErrWaCLI
+ }
+ utils.MustLogin(client)
- contacts, err := whatsapp.GetClient().Store.Contacts.GetAllContacts(ctx)
+ contacts, err := client.Store.Contacts.GetAllContacts(ctx)
if err != nil {
return
}
@@ -179,7 +205,11 @@ func (service serviceUser) MyListContacts(ctx context.Context) (response domainU
}
func (service serviceUser) ChangeAvatar(ctx context.Context, request domainUser.ChangeAvatarRequest) (err error) {
- utils.MustLogin(whatsapp.GetClient())
+ client := whatsapp.ClientFromContext(ctx)
+ if client == nil {
+ return pkgError.ErrWaCLI
+ }
+ utils.MustLogin(client)
file, err := request.Avatar.Open()
if err != nil {
@@ -224,7 +254,7 @@ func (service serviceUser) ChangeAvatar(ctx context.Context, request domainUser.
return fmt.Errorf("failed to encode image: %v", err)
}
- _, err = whatsapp.GetClient().SetGroupPhoto(ctx, types.JID{}, buf.Bytes())
+ _, err = client.SetGroupPhoto(ctx, types.JID{}, buf.Bytes())
if err != nil {
return err
}
@@ -233,9 +263,13 @@ func (service serviceUser) ChangeAvatar(ctx context.Context, request domainUser.
}
func (service serviceUser) ChangePushName(ctx context.Context, request domainUser.ChangePushNameRequest) (err error) {
- utils.MustLogin(whatsapp.GetClient())
+ client := whatsapp.ClientFromContext(ctx)
+ if client == nil {
+ return pkgError.ErrWaCLI
+ }
+ utils.MustLogin(client)
- err = whatsapp.GetClient().SendAppState(ctx, appstate.BuildSettingPushName(request.PushName))
+ err = client.SendAppState(ctx, appstate.BuildSettingPushName(request.PushName))
if err != nil {
return err
}
@@ -243,11 +277,15 @@ func (service serviceUser) ChangePushName(ctx context.Context, request domainUse
}
func (service serviceUser) IsOnWhatsApp(ctx context.Context, request domainUser.CheckRequest) (response domainUser.CheckResponse, err error) {
- utils.MustLogin(whatsapp.GetClient())
+ client := whatsapp.ClientFromContext(ctx)
+ if client == nil {
+ return response, pkgError.ErrWaCLI
+ }
+ utils.MustLogin(client)
utils.SanitizePhone(&request.Phone)
- response.IsOnWhatsApp = utils.IsOnWhatsapp(whatsapp.GetClient(), request.Phone)
+ response.IsOnWhatsApp = utils.IsOnWhatsapp(client, request.Phone)
return response, nil
}
@@ -258,12 +296,17 @@ func (service serviceUser) BusinessProfile(ctx context.Context, request domainUs
return response, err
}
- dataWaRecipient, err := utils.ValidateJidWithLogin(whatsapp.GetClient(), request.Phone)
+ client := whatsapp.ClientFromContext(ctx)
+ if client == nil {
+ return response, pkgError.ErrWaCLI
+ }
+
+ dataWaRecipient, err := utils.ValidateJidWithLogin(client, request.Phone)
if err != nil {
return response, err
}
- profile, err := whatsapp.GetClient().GetBusinessProfile(ctx, dataWaRecipient)
+ profile, err := client.GetBusinessProfile(ctx, dataWaRecipient)
if err != nil {
return response, err
}
diff --git a/src/views/components/AppLogin.js b/src/views/components/AppLogin.js
index 2265b09a..54b8063e 100644
--- a/src/views/components/AppLogin.js
+++ b/src/views/components/AppLogin.js
@@ -1,7 +1,10 @@
export default {
name: 'AppLogin',
props: {
- connected: null,
+ loggedIn: {
+ type: Boolean,
+ default: false,
+ },
},
data() {
return {
@@ -13,7 +16,7 @@ export default {
methods: {
async openModal() {
try {
- if (this.connected) throw Error('You are already logged in.');
+ if (this.loggedIn) throw Error('You are already logged in.');
await this.submitApi();
$('#modalLogin').modal({
diff --git a/src/views/components/AppLoginWithCode.js b/src/views/components/AppLoginWithCode.js
index 8495e422..93685ef0 100644
--- a/src/views/components/AppLoginWithCode.js
+++ b/src/views/components/AppLoginWithCode.js
@@ -1,22 +1,11 @@
export default {
name: 'AppLoginWithCode',
props: {
- connected: {
- type: Array,
- default: [],
+ loggedIn: {
+ type: Boolean,
+ default: false,
}
},
- watch: {
- connected: function(val) {
- if (val) {
- // reset form
- this.phone = '';
- this.pair_code = null;
-
- $('#modalLoginWithCode').modal('hide');
- }
- },
- },
data: () => {
return {
phone: '',
@@ -27,7 +16,7 @@ export default {
methods: {
async openModal() {
try {
- if (this.connected) throw Error('You are already logged in.');
+ if (this.loggedIn) throw Error('You are already logged in.');
$('#modalLoginWithCode').modal({
onApprove: function() {
diff --git a/src/views/components/DeviceManager.js b/src/views/components/DeviceManager.js
new file mode 100644
index 00000000..64a5bd8e
--- /dev/null
+++ b/src/views/components/DeviceManager.js
@@ -0,0 +1,238 @@
+export default {
+ name: 'DeviceManager',
+ props: {
+ wsBasePath: {
+ type: String,
+ default: ''
+ }
+ },
+ data() {
+ return {
+ deviceList: [],
+ selectedDeviceId: '',
+ deviceIdInput: '',
+ isCreatingDevice: false,
+ deviceToDelete: { id: '', jid: '', state: '' },
+ isDeleting: false
+ }
+ },
+ computed: {
+ selectedDevice() {
+ if (!this.selectedDeviceId) return null;
+ return this.deviceList.find(d => (d.id || d.device) === this.selectedDeviceId) || null;
+ },
+ isSelectedDeviceLoggedIn() {
+ return this.selectedDevice?.state === 'logged_in';
+ }
+ },
+ methods: {
+ async fetchDevices() {
+ try {
+ const res = await window.http.get(`/devices`);
+ this.deviceList = res.data.results || [];
+ if (!this.selectedDeviceId && this.deviceList.length > 0) {
+ const first = this.deviceList[0].id || this.deviceList[0].device;
+ this.setDeviceContext(first);
+ }
+ // Emit devices to parent for other components
+ this.$emit('devices-updated', this.deviceList);
+ } catch (err) {
+ console.error(err);
+ }
+ },
+ setDeviceContext(id) {
+ if (!id) {
+ showErrorInfo('Device ID is required');
+ return;
+ }
+ this.selectedDeviceId = id;
+ this.$emit('device-selected', id);
+ showSuccessInfo(`Using device ${id}`);
+ },
+ async createDevice() {
+ try {
+ this.isCreatingDevice = true;
+ const payload = this.deviceIdInput ? {device_id: this.deviceIdInput} : {};
+ const res = await window.http.post('/devices', payload);
+ const deviceID = res.data?.results?.id || res.data?.results?.device_id || this.deviceIdInput;
+ this.setDeviceContext(deviceID);
+ this.deviceIdInput = '';
+ } catch (err) {
+ const msg = err.response?.data?.message || err.message || 'Failed to create device';
+ showErrorInfo(msg);
+ } finally {
+ this.isCreatingDevice = false;
+ }
+ },
+ useDeviceFromInput() {
+ if (!this.deviceIdInput) {
+ showErrorInfo('Enter a device_id or create one first.');
+ return;
+ }
+ this.setDeviceContext(this.deviceIdInput);
+ },
+ openDeleteModal(deviceId, jid) {
+ const device = this.deviceList.find(d => (d.id || d.device) === deviceId);
+ this.deviceToDelete = { id: deviceId, jid: jid || '', state: device?.state || '' };
+ $('#deleteDeviceModal').modal({
+ closable: false,
+ onApprove: () => {
+ this.executeDelete();
+ return false;
+ },
+ onDeny: () => {
+ this.resetDeleteState();
+ }
+ }).modal('show');
+ },
+ resetDeleteState() {
+ this.deviceToDelete = { id: '', jid: '', state: '' };
+ this.isDeleting = false;
+ },
+ async executeDelete() {
+ const deviceId = this.deviceToDelete.id;
+ if (!deviceId) {
+ showErrorInfo('No device selected for deletion');
+ return;
+ }
+ try {
+ this.isDeleting = true;
+
+ // Logout first (fire and forget), then delete
+ window.http.get(`/app/logout`, {
+ headers: { 'X-Device-Id': deviceId }
+ }).catch(() => {});
+
+ await window.http.delete(`/devices/${encodeURIComponent(deviceId)}`);
+ showSuccessInfo(`Device ${deviceId} deleted successfully`);
+ $('#deleteDeviceModal').modal('hide');
+
+ if (this.selectedDeviceId === deviceId) {
+ this.selectedDeviceId = '';
+ this.$emit('device-selected', '');
+ }
+
+ await this.fetchDevices();
+ this.resetDeleteState();
+ } catch (err) {
+ const msg = err.response?.data?.message || err.message || 'Failed to delete device';
+ showErrorInfo(msg);
+ this.isDeleting = false;
+ }
+ },
+ // Called by parent to refresh devices
+ refresh() {
+ this.fetchDevices();
+ },
+ // Called by parent to update device list from websocket
+ updateDeviceList(devices) {
+ if (Array.isArray(devices)) {
+ this.deviceList = devices;
+ this.$emit('devices-updated', devices);
+ }
+ }
+ },
+ mounted() {
+ this.fetchDevices();
+ },
+ template: `
+ <div class="ui stackable grid">
+ <div class="ten wide column">
+ <div class="ui segment">
+ <h3 class="ui header">
+ <i class="play icon"></i>
+ <div class="content">
+ Device setup
+ <div class="sub header">Create or select a device_id, then open login.</div>
+ </div>
+ </h3>
+ <div class="ui form">
+ <div class="two fields">
+ <div class="field">
+ <label>Device ID (optional)</label>
+ <input type="text" v-model="deviceIdInput" placeholder="Leave empty to auto-generate">
+ </div>
+ <div class="field">
+ <label>Actions</label>
+ <div class="ui buttons">
+ <button class="ui primary button" :class="{loading: isCreatingDevice}" @click="createDevice">
+ Create device
+ </button>
+ <div class="or"></div>
+ <button class="ui button" @click="useDeviceFromInput">Use this device</button>
+ </div>
+ </div>
+ </div>
+ </div>
+ <div class="ui divider"></div>
+
+ <!-- Device List -->
+ <div class="ui relaxed list" v-if="deviceList.length">
+ <div class="item" v-for="dev in deviceList" :key="dev.id || dev.device">
+ <i class="mobile alternate icon"></i>
+ <div class="content">
+ <div class="header">{{ dev.id || dev.device }}</div>
+ <div class="description">
+ <span>State: {{ dev.state || 'unknown' }}</span>
+ <span v-if="dev.jid"> Β· JID: {{ dev.jid }}</span>
+ </div>
+ </div>
+ <div class="right floated content">
+ <button class="ui mini button"
+ :class="{active: selectedDeviceId === (dev.id || dev.device)}"
+ @click="setDeviceContext(dev.id || dev.device)">
+ {{ selectedDeviceId === (dev.id || dev.device) ? 'Selected' : 'Use' }}
+ </button>
+ <button class="ui mini red icon button"
+ @click="openDeleteModal(dev.id || dev.device, dev.jid)"
+ :class="{loading: isDeleting && deviceToDelete.id === (dev.id || dev.device)}">
+ <i class="trash icon" style="margin: 0;"></i>
+ </button>
+ </div>
+ </div>
+ </div>
+ <div class="ui message" v-else>
+ No devices yet. Create one to begin.
+ </div>
+ </div>
+ </div>
+ <div class="six wide column">
+ <div class="ui warning message">
+ <div class="header">How to log in</div>
+ <ul class="list">
+ <li>Step 1: Create a device to get <code>device_id</code>.</li>
+ <li>Step 2: Send <code>X-Device-Id: device_id</code> on REST calls.</li>
+ <li>Step 3: Open Login card to pair (QR or code).</li>
+ <li>WebSocket URL: <code>{{ wsBasePath }}/ws?device_id=&lt;device_id&gt;</code></li>
+ </ul>
+ </div>
+ </div>
+
+ <!-- Delete Device Confirmation Modal -->
+ <div class="ui small modal" id="deleteDeviceModal">
+ <div class="header">
+ <i class="trash alternate icon"></i>
+ Confirm Delete Device
+ </div>
+ <div class="content">
+ <p>Are you sure you want to delete this device?</p>
+ <div class="ui segment">
+ <p><strong>Device ID:</strong> <code>{{ deviceToDelete.id }}</code></p>
+ <p v-if="deviceToDelete.jid"><strong>JID:</strong> <code>{{ deviceToDelete.jid }}</code></p>
+ </div>
+ <div class="ui warning message">
+ <div class="header">Warning</div>
+ <p>This action will permanently delete the device and all associated data including chats and messages. This cannot be undone.</p>
+ </div>
+ </div>
+ <div class="actions">
+ <button class="ui cancel button">Cancel</button>
+ <button class="ui red approve button" :class="{loading: isDeleting}">
+ <i class="trash icon"></i>
+ Delete Device
+ </button>
+ </div>
+ </div>
+ </div>
+ `
+}
diff --git a/src/views/components/GroupList.js b/src/views/components/GroupList.js
index 6bad95d6..64508148 100644
--- a/src/views/components/GroupList.js
+++ b/src/views/components/GroupList.js
@@ -15,31 +15,48 @@ export default {
},
computed: {
currentUserId() {
+ // connected can be array of objects with device/id or may be undefined
if (!this.connected || this.connected.length === 0) return null;
- const device = this.connected[0].device;
- return device.split('@')[0].split(':')[0];
+ const entry = this.connected[0];
+ const raw = entry.device || entry.id || '';
+ if (!raw || typeof raw !== 'string') return null;
+ return raw.split('@')[0].split(':')[0];
}
},
methods: {
async openModal() {
try {
- this.dtClear()
+ this.dtClear();
+ // Reset groups before fetching new data
+ this.groups = [];
await this.submitApi();
$('#modalGroupList').modal('show');
- this.dtRebuild()
+ // Wait a bit for modal animation to complete before initializing DataTable
+ await new Promise(resolve => setTimeout(resolve, 100));
+ await this.dtRebuild();
showSuccessInfo("Groups fetched")
} catch (err) {
showErrorInfo(err)
}
},
dtClear() {
- $('#account_groups_table').DataTable().destroy();
+ const table = $('#account_groups_table');
+ if ($.fn.DataTable.isDataTable(table)) {
+ table.DataTable().clear().destroy();
+ }
},
- dtRebuild() {
- $('#account_groups_table').DataTable({
- "pageLength": 100,
- "reloadData": true,
- }).draw();
+ async dtRebuild() {
+ // Wait for Vue to render the new data
+ await this.$nextTick();
+ // Additional delay to ensure DOM is fully updated after Vue render
+ await new Promise(resolve => setTimeout(resolve, 100));
+ const table = $('#account_groups_table');
+ if ($.fn.DataTable.isDataTable(table)) {
+ table.DataTable().destroy();
+ }
+ table.DataTable({
+ pageLength: 100,
+ });
},
async handleLeaveGroup(group_id) {
try {
@@ -71,7 +88,8 @@ export default {
async submitApi() {
try {
let response = await window.http.get(`/user/my/groups`)
- this.groups = response.data.results.data;
+ // Ensure groups is always an array, even if null/undefined
+ this.groups = response.data.results.data || [];
} catch (error) {
if (error.response) {
throw new Error(error.response.data.message);
@@ -207,8 +225,8 @@ export default {
<th>Action</th>
</tr>
</thead>
- <tbody v-if="groups != null">
- <tr v-for="g in groups">
+ <tbody>
+ <tr v-for="g in groups" :key="g.JID">
<td>{{ g.JID.split('@')[0] }}</td>
<td>{{ g.Name }}</td>
<td>{{ g.Participants.length }}</td>
diff --git a/src/views/index.html b/src/views/index.html
index 45ef9fb5..6811ddcc 100644
--- a/src/views/index.html
+++ b/src/views/index.html
@@ -42,25 +42,38 @@
</h1>
</div>
- <div class="ui success message" v-if="connected_devices != null">
+ <div class="ui info message" v-if="selectedDeviceId">
<div class="header">
- <i class="check circle icon"></i>
- Device Connected Successfully
+ <i class="linkify icon"></i>
+ Device context active
</div>
<p>
- Device ID: <b>[[ connected_devices[0].device ]]</b>
+ Using device: <b>[[ selectedDeviceId ]]</b>.
+ REST/WebSocket send <code>X-Device-Id</code> (or <code>?device_id=</code> for WS).
</p>
</div>
+ <device-manager
+ ref="deviceManager"
+ ws-base-path="{{ .AppBasePath }}"
+ @device-selected="handleDeviceSelected"
+ @devices-updated="handleDevicesUpdated">
+ </device-manager>
+
<div class="ui horizontal divider">
App
</div>
- <div class="ui three column stackable grid cards">
- <app-login :connected="connected_devices"></app-login>
+ <div class="ui warning message" v-if="!selectedDeviceId">
+ <div class="header">Device required</div>
+ <p>Select or create a device above. Provide <code>X-Device-Id</code> on REST calls.</p>
+ </div>
+
+ <div class="ui three column stackable grid cards" :class="{disabled: !selectedDeviceId}">
+ <app-login :logged-in="isSelectedDeviceLoggedIn"></app-login>
<app-logout @reload-devices="handleReloadDevice"></app-logout>
<app-reconnect @reload-devices="handleReloadDevice"></app-reconnect>
- <app-login-with-code :connected="connected_devices"></app-login-with-code>
+ <app-login-with-code :logged-in="isSelectedDeviceLoggedIn"></app-login-with-code>
</div>
<div class="ui horizontal divider">
@@ -177,8 +190,10 @@
}
+ const baseHost = `${window.location.protocol}//${window.location.hostname}${window.location.port ? ':' + window.location.port : ''}`;
+ const DEVICE_ID_HEADER = 'X-Device-Id';
window.http = axios.create({
- baseURL: `${window.location.protocol}//${window.location.hostname}${window.location.port ? ':' + window.location.port : ''}{{ .AppBasePath }}`
+ baseURL: `${baseHost}{{ .AppBasePath }}`
});
{{ if isEnableBasicAuth .BasicAuthToken }}
window.http.defaults.headers.common['Authorization'] = "{{ .BasicAuthToken }}";
@@ -231,6 +246,7 @@
import ChatDisappearingManager from "{{ .AppBasePath }}/components/ChatDisappearingManager.js";
import ChatList from "{{ .AppBasePath }}/components/ChatList.js";
import ChatMessages from "{{ .AppBasePath }}/components/ChatMessages.js";
+ import DeviceManager from "{{ .AppBasePath }}/components/DeviceManager.js";
const showErrorInfo = (message) => {
$('body').toast({
@@ -251,13 +267,6 @@
});
}
- const constructWebSocketURL = () => {
- const protocol = location.protocol === 'https:' ? 'wss://' : 'ws://';
- const basePath = '{{ .AppBasePath }}';
-
- return `${protocol}${location.host}${basePath}/ws`;
- };
-
Vue.createApp({
components: {
AppLogin, AppLoginWithCode, AppLogout, AppReconnect,
@@ -266,48 +275,93 @@
GroupList, GroupCreate, GroupJoinWithLink, GroupInfoFromLink, GroupAddParticipants, GroupSetPhoto, GroupSetName, GroupSetLocked, GroupSetAnnounce, GroupSetTopic, GroupGetInviteLink, GroupInfo,
NewsletterList,
AccountAvatar, AccountUserInfo, AccountPrivacy, AccountChangeAvatar, AccountContact, AccountChangePushName, AccountUserCheck, AccountBusinessProfile,
- ChatPinManager, ChatDisappearingManager, ChatList, ChatMessages
+ ChatPinManager, ChatDisappearingManager, ChatList, ChatMessages,
+ DeviceManager
},
delimiters: ['[[', ']]'],
data() {
return {
app_ws: null,
connected_devices: null,
+ deviceList: [],
+ selectedDeviceId: '',
}
},
+ computed: {
+ selectedDevice() {
+ if (!this.selectedDeviceId) return null;
+ return this.deviceList.find(d => (d.id || d.device) === this.selectedDeviceId) || null;
+ },
+ isSelectedDeviceLoggedIn() {
+ return this.selectedDevice?.state === 'logged_in';
+ },
+ },
methods: {
+ applyDeviceHeader(id) {
+ if (id) {
+ window.http.defaults.headers.common[DEVICE_ID_HEADER] = id;
+ } else {
+ delete window.http.defaults.headers.common[DEVICE_ID_HEADER];
+ if (this.app_ws) {
+ this.app_ws.close();
+ this.app_ws = null;
+ }
+ }
+ },
+ constructWebSocketURL() {
+ if (!this.selectedDeviceId) return '';
+ const protocol = location.protocol === 'https:' ? 'wss://' : 'ws://';
+ const basePath = '{{ .AppBasePath }}';
+ const deviceQuery = encodeURIComponent(this.selectedDeviceId);
+ const pathPrefix = basePath || '';
+ return `${protocol}${location.host}${pathPrefix}/ws?device_id=${deviceQuery}`;
+ },
handleReloadDevice() {
- this.app_ws.send(JSON.stringify({"code": "FETCH_DEVICES"}))
- }
- },
- mounted() {
- // Initialize app container as hidden
- document.getElementById('app').style.display = 'none';
-
- if (window["WebSocket"]) {
- this.app_ws = new WebSocket(constructWebSocketURL());
+ if (this.$refs.deviceManager) {
+ this.$refs.deviceManager.refresh();
+ }
+ if (this.app_ws) {
+ this.app_ws.send(JSON.stringify({"code": "FETCH_DEVICES"}));
+ }
+ },
+ handleDeviceSelected(id) {
+ this.selectedDeviceId = id;
+ this.applyDeviceHeader(id);
+ if (id) {
+ this.connectWebSocket();
+ }
+ },
+ handleDevicesUpdated(devices) {
+ this.deviceList = devices;
+ this.connected_devices = devices;
+ },
+ connectWebSocket() {
+ if (!this.selectedDeviceId) {
+ return;
+ }
+
+ if (this.app_ws) {
+ this.app_ws.close();
+ this.app_ws = null;
+ }
+
+ const wsURL = this.constructWebSocketURL();
+ if (!wsURL) {
+ return;
+ }
+
+ this.app_ws = new WebSocket(wsURL);
this.app_ws.onopen = (evt) => {
- this.app_ws.send(JSON.stringify({
- "code": "FETCH_DEVICES",
- "message": "List device"
- }));
-
- // Show app container and hide splash screen with a slight delay
- setTimeout(() => {
- document.getElementById('app').style.display = 'block';
- document.getElementById('splash-screen').classList.add('fade-out');
- }, 1000);
+ this.handleReloadDevice();
};
this.app_ws.onerror = (error) => {
- console.error('WebSocket error:', error);
- showErrorInfo('Connection error occurred. Please refresh the page.');
- // Hide splash screen and show error state
- setTimeout(() => {
- document.getElementById('app').style.display = 'block';
- document.getElementById('splash-screen').classList.add('fade-out');
- }, 1000);
+ console.error('WebSocket error:', error);
+ // Only show error notification if the device is logged in
+ if (this.isSelectedDeviceLoggedIn) {
+ showErrorInfo('Connection error occurred. Please refresh or re-select the device.');
+ }
};
this.app_ws.onmessage = (evt) => {
@@ -330,15 +384,41 @@
// Optionally refresh the device list
this.handleReloadDevice()
break;
+ case 'DEVICE_REMOVED': {
+ const removedId = message.result?.device_id;
+ const devices = message.result?.devices;
+ showSuccessInfo('βœ… ' + (message.message || 'Device removed'));
+
+ if (Array.isArray(devices)) {
+ this.deviceList = devices;
+ this.connected_devices = devices;
+
+ if (removedId && this.selectedDeviceId === removedId) {
+ this.selectedDeviceId = '';
+ this.applyDeviceHeader('');
+ }
+
+ if (!this.selectedDeviceId && this.deviceList.length > 0) {
+ const first = this.deviceList[0].id || this.deviceList[0].device;
+ this.setDeviceContext(first);
+ }
+ } else {
+ this.handleReloadDevice();
+ }
+ break;
+ }
default:
console.log(message)
}
};
- } else {
- console.error('Your browser does not support WebSockets');
- // Hide splash screen if WebSocket is not supported
+ },
+ },
+ mounted() {
+ // Show app container and hide splash once initial data fetched
+ setTimeout(() => {
+ document.getElementById('app').style.display = 'block';
document.getElementById('splash-screen').classList.add('fade-out');
- }
+ }, 800);
},
}).mount('#app')
</script>