Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
495857ee41 | ||
|
|
e04e55c4c5 | ||
|
|
743e740860 | ||
|
|
65623ec1ea | ||
|
|
72a301c579 | ||
|
|
f35fd8d7c6 | ||
|
|
0594ca0709 | ||
|
|
4e5ebab97e | ||
|
|
ba976138b7 | ||
|
|
bb3328f5a3 | ||
|
|
6db12d7913 | ||
|
|
d968fa90f1 | ||
|
|
06c874fea5 | ||
|
|
d2b7d94607 | ||
|
|
c8f067229b | ||
|
|
798d782869 | ||
|
|
f70bcd0b53 | ||
|
|
17a7764b97 | ||
|
|
58affc9fe2 | ||
|
|
3678cb4392 | ||
|
|
6eda96908f | ||
|
|
ddf161bb2b | ||
|
|
5659dc7296 | ||
|
|
bca90199f1 | ||
|
|
bd263b071c | ||
|
|
e54603085c | ||
|
|
7f7857141e | ||
|
|
3b19dc3a61 | ||
|
|
06e5951c68 | ||
|
|
bcf4ed07d8 | ||
|
|
f711fcca98 | ||
|
|
32e57cab98 | ||
|
|
b092d2bfe1 | ||
|
|
f655f715d0 | ||
|
|
e5c77c60f2 | ||
|
|
a38d4145c2 | ||
|
|
2c47b784b3 | ||
|
|
724dc61717 | ||
|
|
9c44256209 | ||
|
|
1fb82c7678 | ||
|
|
55f7d4dac7 | ||
|
|
10e8869903 | ||
|
|
554d2bc6bc | ||
|
|
99aabb0957 | ||
|
|
055b014c41 | ||
|
|
172676ae6f | ||
|
|
0056951485 | ||
|
|
8c91792473 | ||
|
|
a26e89a2b7 | ||
|
|
7674c4ca67 | ||
|
|
cc7c11e2fd | ||
|
|
9f3c28b6ac | ||
|
|
3ca9545a58 | ||
|
|
4d08cffeab | ||
|
|
241340e0a0 | ||
|
|
556f0fa775 | ||
|
|
975cf2f580 | ||
|
|
90795a7eaf | ||
|
|
e64b60ef3a | ||
|
|
03e9588581 | ||
|
|
393f5ef7da | ||
|
|
f778678514 | ||
|
|
e4f88771a8 | ||
|
|
e885ea8e95 | ||
|
|
f8a9ed7d06 | ||
|
|
d89e9105d0 | ||
|
|
3ba92dec04 | ||
|
|
441ebbd525 | ||
|
|
690c43c245 | ||
|
|
26d8591a6c | ||
|
|
ac63c097ec | ||
|
|
d29e4f8351 | ||
|
|
615ccda4c3 | ||
|
|
d52eb71c76 | ||
|
|
8edd81a765 | ||
|
|
5830cee384 | ||
|
|
20f15b4370 | ||
|
|
8432cd4f8d | ||
|
|
55870b88bf | ||
|
|
6acf4373f4 | ||
|
|
2381f0843f | ||
|
|
b4e6f5e722 | ||
|
|
415bee3e8e | ||
|
|
aad924be79 | ||
|
|
81083e7f82 | ||
|
|
f8e52959a4 | ||
|
|
8eb542f49e | ||
|
|
45ae263ab9 | ||
|
|
f066f982bf | ||
|
|
0888640741 | ||
|
|
bde3722f5c | ||
|
|
0cd3df117a | ||
|
|
4c9525cc9f | ||
|
|
c14fe1e67d | ||
|
|
d1e3b209e7 | ||
|
|
f37bf62a30 | ||
|
|
538bfe0e24 | ||
|
|
93cd5307d9 | ||
|
|
b697f37b1e | ||
|
|
96a9cd8cbb | ||
|
|
a21b9a11a9 | ||
|
|
213b51e598 | ||
|
|
faf3c77508 | ||
|
|
e6fdfb88ca | ||
|
|
99746df626 | ||
|
|
43aeeb55e8 | ||
|
|
4f89f49d44 | ||
|
|
be583e7e40 | ||
|
|
e8c8f89733 | ||
|
|
13b6d3ddf7 | ||
|
|
5e97fb74b1 | ||
|
|
cc47321cad | ||
|
|
607dff8f7a | ||
|
|
0a74f8dbcd | ||
|
|
796befcf87 | ||
|
|
2c5610dd01 | ||
|
|
43d110fa31 | ||
|
|
bf52dd4874 | ||
|
|
f8268180bf | ||
|
|
04cf9bc8c0 | ||
|
|
ff38cf7660 | ||
|
|
4c0b44c4b5 | ||
|
|
e75c29d57f | ||
|
|
f8329c29b1 | ||
|
|
52222a6b98 | ||
|
|
99a0a19d8c | ||
|
|
48ed33bc94 | ||
|
|
b234e134bf | ||
|
|
f6004fd294 | ||
|
|
91d541387b | ||
|
|
9dbd45da6e | ||
|
|
adc1c3960c | ||
|
|
ff742d2e84 | ||
|
|
10bd4d6271 | ||
|
|
874cafe114 | ||
|
|
0ce2c4b9fa | ||
|
|
a8a7988bfa | ||
|
|
2940d93b81 | ||
|
|
88707cf72b | ||
|
|
b0f883c6a8 | ||
|
|
4cddb766c2 | ||
|
|
6675492901 | ||
|
|
a9d030af2a | ||
|
|
2782a188a9 | ||
|
|
256688497e | ||
|
|
4def193c57 | ||
|
|
7f3a2e6aa5 | ||
|
|
60e4f13b67 | ||
|
|
2d6cfeb0fa | ||
|
|
03e85434df | ||
|
|
0ce4c01c48 | ||
|
|
0e95890ca4 | ||
|
|
072f4b2ab0 | ||
|
|
47a91ef669 | ||
|
|
5143bd1ef8 | ||
|
|
0efc0751c9 | ||
|
|
51dda739cb | ||
|
|
3b28826679 | ||
|
|
81646bbaa2 | ||
|
|
d8d84107fb | ||
|
|
58d917d374 | ||
|
|
f8f0063975 | ||
|
|
73faf330e3 | ||
|
|
5a1ebb186d | ||
|
|
54d6d715b0 | ||
|
|
5d9d6e29e2 | ||
|
|
cf3385f624 | ||
|
|
0346c5e7b9 | ||
|
|
443652b0a7 | ||
|
|
1e73c3dc6a | ||
|
|
afa9d4208f | ||
|
|
64eda25b5d | ||
|
|
cfc6c931a3 | ||
|
|
35bc56c948 | ||
|
|
371bde4c3e | ||
|
|
9497e2900e | ||
|
|
51bbc9998a | ||
|
|
057f7bce56 | ||
|
|
52412fb4cc | ||
|
|
a57f3443de | ||
|
|
9b2537e7c7 | ||
|
|
a378ad4c3d |
No files matched your search
@@ -0,0 +1,15 @@
|
|||||||
|
{
|
||||||
|
"permissions": {
|
||||||
|
"allow": [
|
||||||
|
"Bash(yarn build:*)",
|
||||||
|
"Bash(cat:*)",
|
||||||
|
"Bash(node:*)",
|
||||||
|
"Bash(npm show:*)",
|
||||||
|
"Bash(python3:*)",
|
||||||
|
"Bash(yarn test:unit:*)",
|
||||||
|
"Bash(npx tsc:*)",
|
||||||
|
"Bash(pre-commit run:*)",
|
||||||
|
"Bash(yarn test:*)"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -21,7 +21,10 @@ WHATSAPP_SWAGGER_ENABLED=True
|
|||||||
# ==================
|
# ==================
|
||||||
# WhatsApp engine (WEBJS is default, GOWS or NOWEB for better performance)
|
# WhatsApp engine (WEBJS is default, GOWS or NOWEB for better performance)
|
||||||
WHATSAPP_DEFAULT_ENGINE=WEBJS
|
WHATSAPP_DEFAULT_ENGINE=WEBJS
|
||||||
|
# So you don't have to create sessions/apps when switching between engines
|
||||||
|
WAHA_NAMESPACE=all
|
||||||
|
|
||||||
|
# "Firefox (YourApp)" in Linked Devices
|
||||||
# WAHA_CLIENT_DEVICE_NAME=YourApp
|
# WAHA_CLIENT_DEVICE_NAME=YourApp
|
||||||
|
|
||||||
# Base URL for the API (used for webhooks, file URLs, etc.)
|
# Base URL for the API (used for webhooks, file URLs, etc.)
|
||||||
|
|||||||
@@ -12,10 +12,11 @@ jobs:
|
|||||||
${{ matrix.engine }} - ${{ matrix.browser }} - ${{ matrix.platform }} -
|
${{ matrix.engine }} - ${{ matrix.browser }} - ${{ matrix.platform }} -
|
||||||
${{ matrix.tag }}
|
${{ matrix.tag }}
|
||||||
strategy:
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
matrix:
|
matrix:
|
||||||
include:
|
include:
|
||||||
# Chromium - x86
|
# Chromium - x86
|
||||||
- runner: 'buildjet-4vcpu-ubuntu-2204'
|
- runner: 'ubuntu-latest'
|
||||||
tag: 'latest'
|
tag: 'latest'
|
||||||
platform: 'amd64'
|
platform: 'amd64'
|
||||||
browser: 'chromium'
|
browser: 'chromium'
|
||||||
@@ -23,7 +24,7 @@ jobs:
|
|||||||
goss: 'goss-linux-amd64'
|
goss: 'goss-linux-amd64'
|
||||||
|
|
||||||
# Chromium - ARM
|
# Chromium - ARM
|
||||||
- runner: 'buildjet-4vcpu-ubuntu-2204-arm'
|
- runner: 'ubuntu-24.04-arm'
|
||||||
tag: 'arm'
|
tag: 'arm'
|
||||||
platform: 'linux/arm64'
|
platform: 'linux/arm64'
|
||||||
browser: 'chromium'
|
browser: 'chromium'
|
||||||
@@ -31,7 +32,7 @@ jobs:
|
|||||||
goss: 'goss-linux-arm'
|
goss: 'goss-linux-arm'
|
||||||
|
|
||||||
# Chrome - x86
|
# Chrome - x86
|
||||||
- runner: 'buildjet-4vcpu-ubuntu-2204'
|
- runner: 'ubuntu-latest'
|
||||||
tag: 'chrome'
|
tag: 'chrome'
|
||||||
platform: 'amd64'
|
platform: 'amd64'
|
||||||
browser: 'chrome'
|
browser: 'chrome'
|
||||||
@@ -39,14 +40,14 @@ jobs:
|
|||||||
goss: 'goss-linux-amd64'
|
goss: 'goss-linux-amd64'
|
||||||
|
|
||||||
# Chrome - ARM (Chrome is not available for ARM)
|
# Chrome - ARM (Chrome is not available for ARM)
|
||||||
#- runner: "buildjet-4vcpu-ubuntu-2204-arm"
|
#- runner: "ubuntu-24.04-arm"
|
||||||
# tag: "chrome-arm"
|
# tag: "chrome-arm"
|
||||||
# platform: "linux/arm64"
|
# platform: "linux/arm64"
|
||||||
# browser: "chrome"
|
# browser: "chrome"
|
||||||
# goss: 'goss-linux-arm'
|
# goss: 'goss-linux-arm'
|
||||||
|
|
||||||
# NOWEB - x86
|
# NOWEB - x86
|
||||||
- runner: 'buildjet-4vcpu-ubuntu-2204'
|
- runner: 'ubuntu-latest'
|
||||||
tag: 'noweb'
|
tag: 'noweb'
|
||||||
platform: 'amd64'
|
platform: 'amd64'
|
||||||
browser: 'none'
|
browser: 'none'
|
||||||
@@ -54,7 +55,7 @@ jobs:
|
|||||||
goss: 'goss-linux-amd64'
|
goss: 'goss-linux-amd64'
|
||||||
|
|
||||||
# NOWEB - ARM
|
# NOWEB - ARM
|
||||||
- runner: 'buildjet-4vcpu-ubuntu-2204-arm'
|
- runner: 'ubuntu-24.04-arm'
|
||||||
tag: 'noweb-arm'
|
tag: 'noweb-arm'
|
||||||
platform: 'linux/arm64'
|
platform: 'linux/arm64'
|
||||||
browser: 'none'
|
browser: 'none'
|
||||||
@@ -62,7 +63,7 @@ jobs:
|
|||||||
goss: 'goss-linux-arm'
|
goss: 'goss-linux-arm'
|
||||||
|
|
||||||
# GOWS - x86
|
# GOWS - x86
|
||||||
- runner: 'buildjet-4vcpu-ubuntu-2204'
|
- runner: 'ubuntu-latest'
|
||||||
tag: 'gows'
|
tag: 'gows'
|
||||||
platform: 'amd64'
|
platform: 'amd64'
|
||||||
browser: 'none'
|
browser: 'none'
|
||||||
@@ -70,7 +71,7 @@ jobs:
|
|||||||
goss: 'goss-linux-amd64'
|
goss: 'goss-linux-amd64'
|
||||||
|
|
||||||
# No browser - ARM
|
# No browser - ARM
|
||||||
- runner: 'buildjet-4vcpu-ubuntu-2204-arm'
|
- runner: 'ubuntu-24.04-arm'
|
||||||
tag: 'gows-arm'
|
tag: 'gows-arm'
|
||||||
platform: 'linux/arm64'
|
platform: 'linux/arm64'
|
||||||
browser: 'none'
|
browser: 'none'
|
||||||
@@ -100,7 +101,51 @@ jobs:
|
|||||||
username: ${{ secrets.DOCKER_USER }}
|
username: ${{ secrets.DOCKER_USER }}
|
||||||
password: ${{ secrets.DOCKER_TOKEN }}
|
password: ${{ secrets.DOCKER_TOKEN }}
|
||||||
|
|
||||||
- name: Build
|
- name: Build (attempt 1)
|
||||||
|
id: build1
|
||||||
|
continue-on-error: true
|
||||||
|
uses: docker/build-push-action@v4
|
||||||
|
with:
|
||||||
|
context: .
|
||||||
|
file: Dockerfile
|
||||||
|
platforms: ${{ matrix.platform }}
|
||||||
|
build-args: |
|
||||||
|
USE_BROWSER=${{ matrix.browser }}
|
||||||
|
WHATSAPP_DEFAULT_ENGINE=${{ matrix.engine }}
|
||||||
|
push: false
|
||||||
|
load: true
|
||||||
|
tags: ${{ steps.meta.outputs.tags }}
|
||||||
|
labels: ${{ steps.meta.outputs.labels }}
|
||||||
|
|
||||||
|
- name: Wait to retry build
|
||||||
|
if: steps.build1.outcome == 'failure'
|
||||||
|
run: |
|
||||||
|
sleep 10
|
||||||
|
|
||||||
|
- name: Build (attempt 2)
|
||||||
|
id: build2
|
||||||
|
if: steps.build1.outcome == 'failure'
|
||||||
|
continue-on-error: true
|
||||||
|
uses: docker/build-push-action@v4
|
||||||
|
with:
|
||||||
|
context: .
|
||||||
|
file: Dockerfile
|
||||||
|
platforms: ${{ matrix.platform }}
|
||||||
|
build-args: |
|
||||||
|
USE_BROWSER=${{ matrix.browser }}
|
||||||
|
WHATSAPP_DEFAULT_ENGINE=${{ matrix.engine }}
|
||||||
|
push: false
|
||||||
|
load: true
|
||||||
|
tags: ${{ steps.meta.outputs.tags }}
|
||||||
|
labels: ${{ steps.meta.outputs.labels }}
|
||||||
|
|
||||||
|
- name: Wait to retry build
|
||||||
|
if: steps.build2.outcome == 'failure'
|
||||||
|
run: |
|
||||||
|
sleep 10
|
||||||
|
|
||||||
|
- name: Build (attempt 3)
|
||||||
|
if: steps.build2.outcome == 'failure'
|
||||||
uses: docker/build-push-action@v4
|
uses: docker/build-push-action@v4
|
||||||
with:
|
with:
|
||||||
context: .
|
context: .
|
||||||
|
|||||||
@@ -6,8 +6,37 @@ on:
|
|||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
|
# unit-tests:
|
||||||
|
# if: github.repository == 'devlikeapro/waha-plus'
|
||||||
|
# runs-on: ubuntu-22.04
|
||||||
|
# name: Unit tests
|
||||||
|
# steps:
|
||||||
|
# - name: Checkout
|
||||||
|
# uses: actions/checkout@v4
|
||||||
|
# with:
|
||||||
|
# fetch-depth: 0
|
||||||
|
#
|
||||||
|
# - name: Set up Node
|
||||||
|
# uses: actions/setup-node@v4
|
||||||
|
# with:
|
||||||
|
# node-version: 22
|
||||||
|
#
|
||||||
|
# - name: Enable Corepack
|
||||||
|
# run: |
|
||||||
|
# corepack enable
|
||||||
|
# corepack prepare yarn@4.9.2 --activate
|
||||||
|
#
|
||||||
|
# - name: Install dependencies
|
||||||
|
# run: |
|
||||||
|
# unset GIT_CONFIG_PARAMETERS
|
||||||
|
# yarn install --immutable
|
||||||
|
#
|
||||||
|
# - name: Run unit tests
|
||||||
|
# run: yarn test:unit
|
||||||
|
|
||||||
docker-build:
|
docker-build:
|
||||||
if: github.repository == 'devlikeapro/waha-plus'
|
if: github.repository == 'devlikeapro/waha-plus'
|
||||||
|
# needs: unit-tests
|
||||||
runs-on: ${{ matrix.runner }}
|
runs-on: ${{ matrix.runner }}
|
||||||
name:
|
name:
|
||||||
${{ matrix.engine }} - ${{ matrix.browser }} - ${{ matrix.platform }} -
|
${{ matrix.engine }} - ${{ matrix.browser }} - ${{ matrix.platform }} -
|
||||||
@@ -15,13 +44,24 @@ jobs:
|
|||||||
strategy:
|
strategy:
|
||||||
matrix:
|
matrix:
|
||||||
include:
|
include:
|
||||||
- runner: 'buildjet-4vcpu-ubuntu-2204'
|
# Chromium - x86
|
||||||
|
- runner: 'ubuntu-latest'
|
||||||
tag: 'dev'
|
tag: 'dev'
|
||||||
platform: 'amd64'
|
platform: 'amd64'
|
||||||
browser: 'chromium'
|
browser: 'chromium'
|
||||||
engine: 'WEBJS'
|
engine: 'WEBJS'
|
||||||
goss: 'goss-linux-amd64'
|
goss: 'goss-linux-amd64'
|
||||||
- runner: 'buildjet-4vcpu-ubuntu-2204-arm'
|
|
||||||
|
# Chrome - x86
|
||||||
|
- runner: 'ubuntu-latest'
|
||||||
|
tag: 'dev-chrome'
|
||||||
|
platform: 'amd64'
|
||||||
|
browser: 'chrome'
|
||||||
|
engine: 'WEBJS'
|
||||||
|
goss: 'goss-linux-amd64'
|
||||||
|
|
||||||
|
# Chromium - ARM
|
||||||
|
- runner: 'ubuntu-24.04-arm'
|
||||||
tag: 'dev-arm'
|
tag: 'dev-arm'
|
||||||
platform: 'linux/arm64'
|
platform: 'linux/arm64'
|
||||||
browser: 'chromium'
|
browser: 'chromium'
|
||||||
@@ -71,8 +111,60 @@ jobs:
|
|||||||
username: ${{ secrets.DOCKER_USER }}
|
username: ${{ secrets.DOCKER_USER }}
|
||||||
password: ${{ secrets.DOCKER_TOKEN }}
|
password: ${{ secrets.DOCKER_TOKEN }}
|
||||||
|
|
||||||
- name: Build
|
- name: Build (attempt 1)
|
||||||
|
id: build1
|
||||||
if: ${{ steps.recent.outputs.has_recent == 'true' }}
|
if: ${{ steps.recent.outputs.has_recent == 'true' }}
|
||||||
|
continue-on-error: true
|
||||||
|
uses: docker/build-push-action@v4
|
||||||
|
with:
|
||||||
|
context: .
|
||||||
|
file: Dockerfile
|
||||||
|
platforms: ${{ matrix.platform }}
|
||||||
|
build-args: |
|
||||||
|
USE_BROWSER=${{ matrix.browser }}
|
||||||
|
WHATSAPP_DEFAULT_ENGINE=${{ matrix.engine }}
|
||||||
|
push: false
|
||||||
|
load: true
|
||||||
|
tags: ${{ steps.meta.outputs.tags }}
|
||||||
|
labels: ${{ steps.meta.outputs.labels }}
|
||||||
|
|
||||||
|
- name: Wait to retry build
|
||||||
|
if:
|
||||||
|
${{ steps.recent.outputs.has_recent == 'true' && steps.build1.outcome
|
||||||
|
== 'failure' }}
|
||||||
|
run: |
|
||||||
|
sleep 10
|
||||||
|
|
||||||
|
- name: Build (attempt 2)
|
||||||
|
id: build2
|
||||||
|
if:
|
||||||
|
${{ steps.recent.outputs.has_recent == 'true' && steps.build1.outcome
|
||||||
|
== 'failure' }}
|
||||||
|
continue-on-error: true
|
||||||
|
uses: docker/build-push-action@v4
|
||||||
|
with:
|
||||||
|
context: .
|
||||||
|
file: Dockerfile
|
||||||
|
platforms: ${{ matrix.platform }}
|
||||||
|
build-args: |
|
||||||
|
USE_BROWSER=${{ matrix.browser }}
|
||||||
|
WHATSAPP_DEFAULT_ENGINE=${{ matrix.engine }}
|
||||||
|
push: false
|
||||||
|
load: true
|
||||||
|
tags: ${{ steps.meta.outputs.tags }}
|
||||||
|
labels: ${{ steps.meta.outputs.labels }}
|
||||||
|
|
||||||
|
- name: Wait to retry build
|
||||||
|
if:
|
||||||
|
${{ steps.recent.outputs.has_recent == 'true' && steps.build2.outcome
|
||||||
|
== 'failure' }}
|
||||||
|
run: |
|
||||||
|
sleep 10
|
||||||
|
|
||||||
|
- name: Build (attempt 3)
|
||||||
|
if:
|
||||||
|
${{ steps.recent.outputs.has_recent == 'true' && steps.build2.outcome
|
||||||
|
== 'failure' }}
|
||||||
uses: docker/build-push-action@v4
|
uses: docker/build-push-action@v4
|
||||||
with:
|
with:
|
||||||
context: .
|
context: .
|
||||||
|
|||||||
+20
@@ -3,3 +3,23 @@ compressionLevel: mixed
|
|||||||
enableGlobalCache: false
|
enableGlobalCache: false
|
||||||
|
|
||||||
nodeLinker: node-modules
|
nodeLinker: node-modules
|
||||||
|
|
||||||
|
supportedArchitectures:
|
||||||
|
cpu:
|
||||||
|
- arm
|
||||||
|
- arm64
|
||||||
|
- ia32
|
||||||
|
- loong64
|
||||||
|
- mips
|
||||||
|
- mipsel
|
||||||
|
- ppc64
|
||||||
|
- riscv64
|
||||||
|
- s390
|
||||||
|
- s390x
|
||||||
|
- x64
|
||||||
|
- wasm32
|
||||||
|
os:
|
||||||
|
- current
|
||||||
|
- darwin
|
||||||
|
- linux
|
||||||
|
- win32
|
||||||
@@ -3,6 +3,11 @@
|
|||||||
This guide summarizes how to explore, modify, and validate the WhatsApp HTTP API
|
This guide summarizes how to explore, modify, and validate the WhatsApp HTTP API
|
||||||
(WAHA) codebase when assisting as an automation or coding agent.
|
(WAHA) codebase when assisting as an automation or coding agent.
|
||||||
|
|
||||||
|
- When you asked to refactor or "apply new lib" instead of current one - do not
|
||||||
|
change the behavior, make a minimum amount of changes possible. If you see
|
||||||
|
some edge case during that process that haven't been covered - tell it,
|
||||||
|
suggest fix, but don't change the code.
|
||||||
|
|
||||||
## Product & Variants
|
## Product & Variants
|
||||||
|
|
||||||
- WAHA ships in **Core** and **Plus** editions. Core lives under `src/core` and
|
- WAHA ships in **Core** and **Plus** editions. Core lives under `src/core` and
|
||||||
@@ -32,6 +37,10 @@ This guide summarizes how to explore, modify, and validate the WhatsApp HTTP API
|
|||||||
- **Utilities**: RxJS streams (`SwitchObservable`, `DefaultMap`) drive webhook
|
- **Utilities**: RxJS streams (`SwitchObservable`, `DefaultMap`) drive webhook
|
||||||
event fan-out. Prefer existing helpers in `src/utils` and `src/core/utils`
|
event fan-out. Prefer existing helpers in `src/utils` and `src/core/utils`
|
||||||
before adding bespoke logic.
|
before adding bespoke logic.
|
||||||
|
- **OS** - the project works on any OS inside the Docker container; the base
|
||||||
|
image is defined in `Dockerfile`.
|
||||||
|
- **CPU** - the image must run on both `x86_64` (including pre-v2 CPUs without
|
||||||
|
SSE4.2) and `aarch64`.
|
||||||
|
|
||||||
## Repository Landmarks
|
## Repository Landmarks
|
||||||
|
|
||||||
@@ -70,8 +79,14 @@ This guide summarizes how to explore, modify, and validate the WhatsApp HTTP API
|
|||||||
`src/utils/logging.ts`. `console.log` is blocked by pre-commit.
|
`src/utils/logging.ts`. `console.log` is blocked by pre-commit.
|
||||||
- Respect path aliases (`@waha/...`) defined in `tsconfig.json`; keep imports
|
- Respect path aliases (`@waha/...`) defined in `tsconfig.json`; keep imports
|
||||||
consistent (use absolute aliases, not relative `../../../`).
|
consistent (use absolute aliases, not relative `../../../`).
|
||||||
|
- Prefer named function declarations over `const` arrow functions when possible.
|
||||||
- Avoid naming unused variables with a leading underscore; if a parameter is
|
- Avoid naming unused variables with a leading underscore; if a parameter is
|
||||||
required by a signature, explicitly `void` it instead.
|
required by a signature, explicitly `void` it instead.
|
||||||
|
- Do not write verbose ternaries like
|
||||||
|
`condition !== undefined ? condition : default`; use idiomatic helpers such as
|
||||||
|
`??` (nullish coalescing) or existing boolean parsers so flags stay readable.
|
||||||
|
- Do not place `await` or other async calls inside ternary expressions (`?:`);
|
||||||
|
use explicit `if/else` blocks instead.
|
||||||
- For configs, prefer runtime configurability over constants. Environment keys
|
- For configs, prefer runtime configurability over constants. Environment keys
|
||||||
follow `WAHA_*` for global values and `WAHA_SESSION_CONFIG_*` /
|
follow `WAHA_*` for global values and `WAHA_SESSION_CONFIG_*` /
|
||||||
`session.config.*` for per-session overrides. If both env and config are
|
`session.config.*` for per-session overrides. If both env and config are
|
||||||
@@ -102,8 +117,7 @@ This guide summarizes how to explore, modify, and validate the WhatsApp HTTP API
|
|||||||
3. After edits run:
|
3. After edits run:
|
||||||
- `pre-commit run --all-files`
|
- `pre-commit run --all-files`
|
||||||
- `yarn build`
|
- `yarn build`
|
||||||
- `yarn test` Use Node 22. Address lint or formatting issues before
|
- `yarn test --watchman=false`
|
||||||
proceeding.
|
|
||||||
4. Do **not** start the application yourself; ask the user to run it if runtime
|
4. Do **not** start the application yourself; ask the user to run it if runtime
|
||||||
validation is required.
|
validation is required.
|
||||||
5. Capture any assumptions or open questions for the user, especially when
|
5. Capture any assumptions or open questions for the user, especially when
|
||||||
@@ -120,14 +134,80 @@ This guide summarizes how to explore, modify, and validate the WhatsApp HTTP API
|
|||||||
- Keep docs and code ASCII unless a file already uses other characters. When
|
- Keep docs and code ASCII unless a file already uses other characters. When
|
||||||
updating documentation, mirror the concise, actionable tone used here.
|
updating documentation, mirror the concise, actionable tone used here.
|
||||||
|
|
||||||
|
## Yes No
|
||||||
|
|
||||||
|
Always define key for objects (and in return too)
|
||||||
|
|
||||||
|
```js
|
||||||
|
// NO
|
||||||
|
const variable = 123;
|
||||||
|
const b = { variable };
|
||||||
|
|
||||||
|
// YES
|
||||||
|
const variable = 123;
|
||||||
|
const b = { variable: variable };
|
||||||
|
```
|
||||||
|
|
||||||
|
Use the three-line comment style for section headers inside files:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// NO
|
||||||
|
// ─── Section name ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
// YES
|
||||||
|
//
|
||||||
|
// Section name
|
||||||
|
//
|
||||||
|
```
|
||||||
|
|
||||||
## Related Sources Code
|
## Related Sources Code
|
||||||
|
|
||||||
You can find related source code in the following paths:
|
You can find and read related source code in the following paths:
|
||||||
|
|
||||||
- WEBJS: `../whatsapp-web.js`
|
- WEBJS: `../whatsapp-web.js`
|
||||||
- NOWEB: `../WhiskeySockets-Baileys`
|
- NOWEB: `../WhiskeySockets-Baileys`
|
||||||
- GOWS: `../gows` + `../whatsmeow`
|
- whatsapp-rust-bridge - `../whatsapp-rust-bridge`
|
||||||
|
- GOWS: `../gows`
|
||||||
|
- whatsmeow - `../whatsmeow`
|
||||||
|
- WPP: `../wa-js`, `../wppconnect`, `../wppconnect-server`
|
||||||
- ChatWoot: `../chatwoot`
|
- ChatWoot: `../chatwoot`
|
||||||
|
|
||||||
Following this playbook keeps contributions aligned with WAHA’s structure,
|
Following this playbook keeps contributions aligned with WAHA’s structure,
|
||||||
automation hooks, and release process.
|
automation hooks, and release process.
|
||||||
|
|
||||||
|
## How to run API
|
||||||
|
|
||||||
|
You can run the project outside of sandbox using the below command, then run
|
||||||
|
queries against `default` session (if not asked to do something different) using
|
||||||
|
`curl` and `X-Api-Key: 666` header.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
export DEBUG=1
|
||||||
|
export WAHA_API_KEY=666
|
||||||
|
export WAHA_DASHBOARD_PASSWORD=666
|
||||||
|
export WAHA_DASHBOARD_USERNAME=admin
|
||||||
|
export WWHATSAPP_SWAGGER_USERNAME=admin
|
||||||
|
export WHATSAPP_SWAGGER_PASSWORD=666
|
||||||
|
export WHATSAPP_DEFAULT_ENGINE={WEBJS|WPP|NOWEB|GOWS}
|
||||||
|
export WAHA_DEBUG_MODE=True
|
||||||
|
export WAHA_HTTP_STRICT_MODE=1
|
||||||
|
export WAHA_MEDIA_STORAGE=LOCAL
|
||||||
|
export WHATSAPP_FILES_FOLDER=./.media
|
||||||
|
|
||||||
|
npm run start
|
||||||
|
```
|
||||||
|
|
||||||
|
- Ask user before running the server.
|
||||||
|
- Before executing some queries make sure the session is in `WORKING` status.
|
||||||
|
- If it's `FAILED` or `SCAN_QR_CODE` ask user to scan QR code or fix failed
|
||||||
|
session.
|
||||||
|
|
||||||
|
## Code
|
||||||
|
|
||||||
|
### @Activity Decorator and Presence Tracking
|
||||||
|
|
||||||
|
Add `@Activity()` (from `src/core/abc/activity.ts`) to every engine method that
|
||||||
|
makes a network call to WhatsApp servers. It triggers `maintainPresenceOnline()`
|
||||||
|
before the method runs, keeping the session ONLINE during API activity and
|
||||||
|
scheduling an OFFLINE transition after an idle period. Skip it on methods that
|
||||||
|
only throw `NotImplementedByEngineError` / `AvailableInPlusVersion`.
|
||||||
+18
-1
@@ -8,7 +8,9 @@ FROM node:${NODE_IMAGE_TAG} AS build
|
|||||||
ENV PUPPETEER_SKIP_DOWNLOAD=True
|
ENV PUPPETEER_SKIP_DOWNLOAD=True
|
||||||
|
|
||||||
# git + build toolchain for git deps
|
# git + build toolchain for git deps
|
||||||
RUN apt-get update && apt-get install -y git python3 build-essential && rm -rf /var/lib/apt/lists/*
|
RUN apt-get update && \
|
||||||
|
apt-get install -y --no-install-recommends git python3 build-essential curl ca-certificates unzip && \
|
||||||
|
rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
# npm packages
|
# npm packages
|
||||||
WORKDIR /git
|
WORKDIR /git
|
||||||
@@ -26,6 +28,21 @@ ADD . /git
|
|||||||
RUN yarn install
|
RUN yarn install
|
||||||
RUN yarn build && find ./dist -name "*.d.ts" -delete
|
RUN yarn build && find ./dist -name "*.d.ts" -delete
|
||||||
|
|
||||||
|
# Rebuild sharp from source on x86-64 so it runs on pre-v2 CPUs (no SSE4.2 requirement).
|
||||||
|
# The prebuilt @img/sharp-linux-x64 binary requires x86-64-v2; -march=x86-64 limits
|
||||||
|
# code generation to baseline x86-64 (SSE2 only). ARM64 prebuilts have no such
|
||||||
|
# constraint, so no rebuild is needed there.
|
||||||
|
# We call sharp's own install/build.js (not npm rebuild) so it first generates config.gypi
|
||||||
|
# with include/lib paths pointing to its bundled @img/sharp-libvips-linux-x64 package,
|
||||||
|
# then invokes node-gyp with those paths. Without this step node-gyp cannot find vips headers.
|
||||||
|
RUN if [ "$(uname -m)" = "x86_64" ]; then \
|
||||||
|
LIBVIPS_DEV_VER=$(node -e "require('/git/node_modules/sharp/package.json').devDependencies['@img/sharp-libvips-dev']" | tr -d '^') && \
|
||||||
|
npm install --prefix /tmp/sharp-dev --no-package-lock "@img/sharp-libvips-dev@${LIBVIPS_DEV_VER}" && \
|
||||||
|
cp -r /tmp/sharp-dev/node_modules/@img/sharp-libvips-dev /git/node_modules/@img/ && \
|
||||||
|
cd /git/node_modules/sharp && \
|
||||||
|
PATH="/git/node_modules/.bin:$PATH" CFLAGS="-march=x86-64" CXXFLAGS="-march=x86-64" node install/build.js; \
|
||||||
|
fi
|
||||||
|
|
||||||
#
|
#
|
||||||
# Dashboard
|
# Dashboard
|
||||||
#
|
#
|
||||||
|
|||||||
@@ -32,16 +32,23 @@ push:
|
|||||||
docker push devlikeapro/waha
|
docker push devlikeapro/waha
|
||||||
|
|
||||||
for-swagger:
|
for-swagger:
|
||||||
WHATSAPP_SWAGGER_CONFIG_ADVANCED=true WHATSAPP_SWAGGER_PASSWORD=666 nvm exec yarn start
|
export WHATSAPP_SWAGGER_CONFIG_ADVANCED=true && export WHATSAPP_SWAGGER_PASSWORD=666 && yarn start
|
||||||
|
|
||||||
up-noweb:
|
up-noweb:
|
||||||
yarn up @adiwajshing/baileys@github:devlikeapro/Baileys#fork-master-2025-12-17
|
yarn up @adiwajshing/baileys@github:devlikeapro/Baileys#fork-master-2026-02-11
|
||||||
|
|
||||||
up-noweb-libsignal:
|
up-noweb-libsignal:
|
||||||
yarn up libsignal@github:devlikeapro/libsignal-node#fork-master
|
yarn up libsignal@github:devlikeapro/libsignal-node#fork-master
|
||||||
|
|
||||||
up-webjs:
|
up-webjs:
|
||||||
yarn up whatsapp-web.js@github:devlikeapro/whatsapp-web.js#fork-main-2025-12-17
|
yarn up whatsapp-web.js@github:devlikeapro/whatsapp-web.js#fork-main-2026-02-18
|
||||||
|
|
||||||
|
up-wpp:
|
||||||
|
yarn up @wppconnect-team/wppconnect
|
||||||
|
yarn up @wppconnect/wa-js
|
||||||
|
|
||||||
|
up-rust-bridge:
|
||||||
|
yarn up -R whatsapp-rust-bridge
|
||||||
|
|
||||||
start-proxy:
|
start-proxy:
|
||||||
docker run --rm -d --name squid-container -e TZ=UTC -p 3128:3128 ubuntu/squid:5.2-22.04_beta
|
docker run --rm -d --name squid-container -e TZ=UTC -p 3128:3128 ubuntu/squid:5.2-22.04_beta
|
||||||
@@ -51,10 +58,12 @@ proto-gows:
|
|||||||
|
|
||||||
gows:
|
gows:
|
||||||
cd ../gows && \
|
cd ../gows && \
|
||||||
export PATH=${HOME}/go/bin:${PATH} && \
|
(export PATH=${HOME}/go/bin:${PATH} || echo failed) && \
|
||||||
make all
|
make all
|
||||||
|
|
||||||
|
up-dashboard:
|
||||||
|
node scripts/up-dashboard.js
|
||||||
|
|
||||||
copy-dashboard:
|
copy-dashboard:
|
||||||
cd ../waha-hub/ui && \
|
cd ../waha-hub/ui && \
|
||||||
make copy-waha
|
make copy-waha
|
||||||
|
|
||||||
@@ -147,7 +147,18 @@ curl -d "{\"chatId\": \"${PHONE}@c.us\", \"text\": \"Hello from WhatsApp HTTP AP
|
|||||||
## Start the project
|
## Start the project
|
||||||
1. Clone the repository
|
1. Clone the repository
|
||||||
2. Make sure you're using node>=22 (check [.nvmrc](/.nvmrc) to get the version)
|
2. Make sure you're using node>=22 (check [.nvmrc](/.nvmrc) to get the version)
|
||||||
3. Run the following commands:
|
3. Install the **whatsapp-rust-bridge prerequisites**:
|
||||||
|
```bash
|
||||||
|
# Bun runtime used by whatsapp-rust-bridge prepare scripts
|
||||||
|
curl -fsSL https://bun.sh/install | bash -s -- bun-v1.3.9
|
||||||
|
|
||||||
|
# Rust nightly toolchain used for whatsapp-rust-bridge
|
||||||
|
curl -fsSL https://sh.rustup.rs | bash -s -- -y --default-toolchain nightly-2026-01-30
|
||||||
|
rustup target add wasm32-unknown-unknown
|
||||||
|
cargo install wasm-pack --vers 0.14.0 --locked
|
||||||
|
```
|
||||||
|
|
||||||
|
4. Run the following commands:
|
||||||
```bash
|
```bash
|
||||||
# Install dependencies
|
# Install dependencies
|
||||||
yarn install
|
yarn install
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ services:
|
|||||||
- 8.8.8.8
|
- 8.8.8.8
|
||||||
|
|
||||||
base: &base
|
base: &base
|
||||||
image: chatwoot/chatwoot:v4.7.0
|
image: chatwoot/chatwoot:v4.12.1
|
||||||
env_file: .chatwoot.env ## Change this file for customized env variables
|
env_file: .chatwoot.env ## Change this file for customized env variables
|
||||||
volumes:
|
volumes:
|
||||||
- chatwoot_storage:/app/storage
|
- chatwoot_storage:/app/storage
|
||||||
@@ -75,7 +75,6 @@ services:
|
|||||||
- POSTGRES_USER=postgres
|
- POSTGRES_USER=postgres
|
||||||
# Please provide your own password.
|
# Please provide your own password.
|
||||||
- POSTGRES_PASSWORD=postgres
|
- POSTGRES_PASSWORD=postgres
|
||||||
- POSTGRES_HOST_AUTH_METHOD=trust
|
|
||||||
|
|
||||||
redis:
|
redis:
|
||||||
image: redis:alpine
|
image: redis:alpine
|
||||||
|
|||||||
+59
-24
@@ -16,23 +16,27 @@
|
|||||||
"start:prod-exit": "node dist/main",
|
"start:prod-exit": "node dist/main",
|
||||||
"lint": "oxlint --deny-warnings",
|
"lint": "oxlint --deny-warnings",
|
||||||
"lint-fix": "oxlint --fix --deny-warnings",
|
"lint-fix": "oxlint --fix --deny-warnings",
|
||||||
"test": "jest",
|
"test": "yarn test:unit",
|
||||||
"test:watch": "jest --watch",
|
"test:watch": "jest --selectProjects unit --watch",
|
||||||
"test:cov": "jest --coverage",
|
"test:cov": "jest --selectProjects unit --coverage",
|
||||||
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
|
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --selectProjects unit --runInBand",
|
||||||
"test:e2e": "jest --config ./test/jest-e2e.json",
|
"test:unit": "jest --selectProjects unit",
|
||||||
|
"test:e2e": "jest --selectProjects e2e",
|
||||||
|
"test:e8e": "yarn test:e2e",
|
||||||
|
"test:all": "yarn test:unit && yarn test:e8e",
|
||||||
"gows:proto:fetch": "node scripts/gows-proto.js fetch",
|
"gows:proto:fetch": "node scripts/gows-proto.js fetch",
|
||||||
"gows:proto:build": "node scripts/gows-proto.js build",
|
"gows:proto:build": "node scripts/gows-proto.js build",
|
||||||
"gows:proto": "yarn gows:proto:fetch && yarn gows:proto:build"
|
"gows:proto": "yarn gows:proto:fetch && yarn gows:proto:build"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@adiwajshing/baileys": "github:devlikeapro/Baileys#fork-master-2025-12-17",
|
"@adiwajshing/baileys": "github:devlikeapro/Baileys#fork-master-2026-02-11",
|
||||||
"@adiwajshing/keyed-db": "^0.2.4",
|
"@adiwajshing/keyed-db": "^0.2.4",
|
||||||
"@aws-sdk/client-s3": "^3.633.0",
|
"@aws-sdk/client-s3": "^3.633.0",
|
||||||
"@aws-sdk/s3-request-presigner": "^3.633.0",
|
"@aws-sdk/s3-request-presigner": "^3.633.0",
|
||||||
"@bull-board/api": "^6.9.1",
|
"@bull-board/api": "^6.9.1",
|
||||||
"@bull-board/express": "^6.9.1",
|
"@bull-board/express": "^6.9.1",
|
||||||
"@bull-board/nestjs": "^6.9.1",
|
"@bull-board/nestjs": "^6.9.1",
|
||||||
|
"@casl/ability": "^6.8.0",
|
||||||
"@figuro/chatwoot-sdk": "^1.1.17",
|
"@figuro/chatwoot-sdk": "^1.1.17",
|
||||||
"@liaoliaots/nestjs-redis": "^9",
|
"@liaoliaots/nestjs-redis": "^9",
|
||||||
"@nestjs/axios": "^3.0.2",
|
"@nestjs/axios": "^3.0.2",
|
||||||
@@ -53,6 +57,8 @@
|
|||||||
"@types/passport": "^1.0.17",
|
"@types/passport": "^1.0.17",
|
||||||
"@types/sqlite3": "^5.1.0",
|
"@types/sqlite3": "^5.1.0",
|
||||||
"@types/ws": "^8.5.4",
|
"@types/ws": "^8.5.4",
|
||||||
|
"@wppconnect-team/wppconnect": "^1.41.1",
|
||||||
|
"@wppconnect/wa-js": "^3.23.3",
|
||||||
"adm-zip": "0.5.10",
|
"adm-zip": "0.5.10",
|
||||||
"agentkeepalive": "^4.5.0",
|
"agentkeepalive": "^4.5.0",
|
||||||
"async-lock": "^1.4.1",
|
"async-lock": "^1.4.1",
|
||||||
@@ -100,14 +106,15 @@
|
|||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^4.3.0",
|
"rimraf": "^4.3.0",
|
||||||
"rxjs": "^7.8.1",
|
"rxjs": "^7.8.1",
|
||||||
"sharp": "^0.33.4",
|
"sharp": "^0.34.5",
|
||||||
"shell-quote": "^1.8.3",
|
"shell-quote": "^1.8.3",
|
||||||
"sqlite3": "^5.1.7",
|
"sqlite3": "^5.1.7",
|
||||||
"swagger-ui-express": "^4.1.4",
|
"swagger-ui-express": "^4.1.4",
|
||||||
"ulid": "^2.3.0",
|
"ulid": "^2.3.0",
|
||||||
"undici": "^7.16.0",
|
"undici": "^7.16.0",
|
||||||
"uniqid": "^5.4.0",
|
"uniqid": "^5.4.0",
|
||||||
"whatsapp-web.js": "github:devlikeapro/whatsapp-web.js#fork-main-2025-12-17",
|
"user-agents": "^1.1.669",
|
||||||
|
"whatsapp-web.js": "github:devlikeapro/whatsapp-web.js#fork-main-2026-02-18",
|
||||||
"write-file-atomic": "^6.0.0",
|
"write-file-atomic": "^6.0.0",
|
||||||
"yaml": "^2.7.1"
|
"yaml": "^2.7.1"
|
||||||
},
|
},
|
||||||
@@ -120,7 +127,8 @@
|
|||||||
"ws": "^8.18.0",
|
"ws": "^8.18.0",
|
||||||
"puppeteer": "^24.31.0",
|
"puppeteer": "^24.31.0",
|
||||||
"whatwg-url": "13.0.0",
|
"whatwg-url": "13.0.0",
|
||||||
"axios": "^1.9.0"
|
"axios": "^1.9.0",
|
||||||
|
"whatsapp-rust-bridge": "npm:@devlikeapro/whatsapp-rust-bridge@0.5.2"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@grpc/grpc-js": "^1.14.1",
|
"@grpc/grpc-js": "^1.14.1",
|
||||||
@@ -134,6 +142,7 @@
|
|||||||
"@types/node-fetch": "^2.6.13",
|
"@types/node-fetch": "^2.6.13",
|
||||||
"@types/semver": "^7.7.0",
|
"@types/semver": "^7.7.0",
|
||||||
"@types/supertest": "^2.0.8",
|
"@types/supertest": "^2.0.8",
|
||||||
|
"@types/user-agents": "^1",
|
||||||
"dotenv": "^17.2.3",
|
"dotenv": "^17.2.3",
|
||||||
"grpc-tools": "^1.13.0",
|
"grpc-tools": "^1.13.0",
|
||||||
"jest": "^29.7.0",
|
"jest": "^29.7.0",
|
||||||
@@ -148,21 +157,47 @@
|
|||||||
"typescript": "5.9.2"
|
"typescript": "5.9.2"
|
||||||
},
|
},
|
||||||
"jest": {
|
"jest": {
|
||||||
"moduleFileExtensions": [
|
"projects": [
|
||||||
"js",
|
{
|
||||||
"json",
|
"displayName": "unit",
|
||||||
"ts"
|
"moduleFileExtensions": [
|
||||||
],
|
"js",
|
||||||
"rootDir": "src",
|
"json",
|
||||||
"moduleNameMapper": {
|
"ts"
|
||||||
"^@waha/(.*)$": "<rootDir>/$1"
|
],
|
||||||
},
|
"rootDir": "src",
|
||||||
"testRegex": ".test.ts$",
|
"moduleNameMapper": {
|
||||||
"transform": {
|
"^@waha/(.*)$": "<rootDir>/$1"
|
||||||
"^.+\\.(t|j)s$": "ts-jest"
|
},
|
||||||
},
|
"testRegex": ".test.ts$",
|
||||||
"coverageDirectory": "../coverage",
|
"testPathIgnorePatterns": [
|
||||||
"testEnvironment": "node"
|
"/__tests__/e2e/"
|
||||||
|
],
|
||||||
|
"transform": {
|
||||||
|
"^.+\\.(t|j)s$": "ts-jest"
|
||||||
|
},
|
||||||
|
"coverageDirectory": "../coverage",
|
||||||
|
"testEnvironment": "node"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"displayName": "e2e",
|
||||||
|
"moduleFileExtensions": [
|
||||||
|
"js",
|
||||||
|
"json",
|
||||||
|
"ts"
|
||||||
|
],
|
||||||
|
"rootDir": "src",
|
||||||
|
"moduleNameMapper": {
|
||||||
|
"^@waha/(.*)$": "<rootDir>/$1"
|
||||||
|
},
|
||||||
|
"testRegex": "__tests__/e2e/.*\\.test\\.ts$",
|
||||||
|
"transform": {
|
||||||
|
"^.+\\.(t|j)s$": "ts-jest"
|
||||||
|
},
|
||||||
|
"coverageDirectory": "../coverage",
|
||||||
|
"testEnvironment": "node"
|
||||||
|
}
|
||||||
|
]
|
||||||
},
|
},
|
||||||
"packageManager": "yarn@4.9.2"
|
"packageManager": "yarn@4.9.2"
|
||||||
}
|
}
|
||||||
+17
-3
@@ -76,17 +76,31 @@ const updatedContent = exampleContent
|
|||||||
|
|
||||||
fs.writeFileSync(targetPath, updatedContent, { encoding: 'utf8' });
|
fs.writeFileSync(targetPath, updatedContent, { encoding: 'utf8' });
|
||||||
|
|
||||||
|
const generatedEnvValues = [
|
||||||
|
`WAHA_API_KEY=${apiKey}`,
|
||||||
|
`WAHA_API_KEY_PLAIN=${apiKey}`,
|
||||||
|
'WAHA_DASHBOARD_USERNAME=admin',
|
||||||
|
`WAHA_DASHBOARD_PASSWORD=${adminPassword}`,
|
||||||
|
'WHATSAPP_SWAGGER_USERNAME=admin',
|
||||||
|
`WHATSAPP_SWAGGER_PASSWORD=${adminPassword}`,
|
||||||
|
];
|
||||||
|
|
||||||
const lines = [
|
const lines = [
|
||||||
'Credentials generated.',
|
'Credentials generated.',
|
||||||
'',
|
'',
|
||||||
'Dashboard and Swagger:',
|
'Generated env values:',
|
||||||
|
...generatedEnvValues.map((line) => ` - ${line}`),
|
||||||
|
'',
|
||||||
|
'Use these credentials to login in Dashboard or Swagger:',
|
||||||
' - Username: admin',
|
' - Username: admin',
|
||||||
` - Password: ${adminPassword}`,
|
` - Password: ${adminPassword}`,
|
||||||
'',
|
'',
|
||||||
'API key: ',
|
'Use this API key in the x-api-key header:',
|
||||||
` - ${apiKey}`,
|
` - ${apiKey}`,
|
||||||
'',
|
'',
|
||||||
'Use it in the Dashboard connection flow: https://waha.devlike.pro/docs/how-to/dashboard/#api-key',
|
'Read more:',
|
||||||
|
' - https://waha.devlike.pro/docs/how-to/dashboard/#api-key',
|
||||||
|
' - https://waha.devlike.pro/docs/how-to/security/',
|
||||||
];
|
];
|
||||||
|
|
||||||
console.log(lines.join('\n'));
|
console.log(lines.join('\n'));
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||||
|
const fs = require('fs');
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||||
|
const { execSync } = require('child_process');
|
||||||
|
|
||||||
|
const CONFIG_FILE = 'waha.config.json';
|
||||||
|
|
||||||
|
const config = JSON.parse(fs.readFileSync(CONFIG_FILE, 'utf8'));
|
||||||
|
const { repo } = config.waha.dashboard;
|
||||||
|
if (!repo) {
|
||||||
|
console.error(`Missing dashboard.repo in ${CONFIG_FILE}`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const branch = 'gh-pages';
|
||||||
|
console.log(`Fetching latest commit for ${repo}@${branch}...`);
|
||||||
|
|
||||||
|
const output = execSync(
|
||||||
|
`git ls-remote https://github.com/${repo} refs/heads/${branch}`,
|
||||||
|
{ encoding: 'utf8' },
|
||||||
|
);
|
||||||
|
|
||||||
|
const sha = output.split('\t')[0].trim();
|
||||||
|
if (!sha) {
|
||||||
|
console.error(`Could not resolve ref ${branch} for ${repo}`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
config.waha.dashboard.ref = sha;
|
||||||
|
fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2) + '\n', 'utf8');
|
||||||
|
console.log(`Updated ${CONFIG_FILE}: dashboard.ref = ${sha}`);
|
||||||
@@ -0,0 +1,391 @@
|
|||||||
|
import axios from 'axios';
|
||||||
|
import WebSocket = require('ws');
|
||||||
|
|
||||||
|
const VALID_API_KEY = '666';
|
||||||
|
const VALID_USERNAME = 'admin';
|
||||||
|
const VALID_PASSWORD = '666';
|
||||||
|
const VALID_SESSION_API_KEY = 'key_0fQfI3n3rFVsczBbBfknLXKUreY2my6J';
|
||||||
|
|
||||||
|
const BASE_URL = (process.env.WAHA_BASE_URL ?? 'http://localhost:3000').replace(
|
||||||
|
/\/$/,
|
||||||
|
'',
|
||||||
|
);
|
||||||
|
const WS_BASE_URL = BASE_URL.replace(/^http/, 'ws');
|
||||||
|
|
||||||
|
const HTTP_OK = 200;
|
||||||
|
const HTTP_CREATED = 201;
|
||||||
|
const HTTP_UNAUTHORIZED = 401;
|
||||||
|
const HTTP_FORBIDDEN = 403;
|
||||||
|
const HTTP_NOT_FOUND = 404;
|
||||||
|
const HTTP_UNPROCESSABLE = 422;
|
||||||
|
const WS_POLICY_VIOLATION = 1008;
|
||||||
|
const WS_OK_CODES = [1000, 1005];
|
||||||
|
|
||||||
|
describe('admin - GET /api/sessions/{name}', () => {
|
||||||
|
test('no api key is unauthorized', async () => {
|
||||||
|
const response = await axios.get(`${BASE_URL}/api/sessions/default`, {
|
||||||
|
validateStatus: () => true,
|
||||||
|
});
|
||||||
|
expect(response.status).toBe(HTTP_UNAUTHORIZED);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('valid api key is ok', async () => {
|
||||||
|
const response = await axios.get(`${BASE_URL}/api/sessions/default`, {
|
||||||
|
headers: { 'X-Api-Key': VALID_API_KEY },
|
||||||
|
validateStatus: () => true,
|
||||||
|
});
|
||||||
|
expect(response.status).toBe(HTTP_OK);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('invalid api key is unauthorized', async () => {
|
||||||
|
const response = await axios.get(`${BASE_URL}/api/sessions/default`, {
|
||||||
|
headers: { 'X-Api-Key': '123' },
|
||||||
|
validateStatus: () => true,
|
||||||
|
});
|
||||||
|
expect(response.status).toBe(HTTP_UNAUTHORIZED);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('admin - POST /api/sessions', () => {
|
||||||
|
test('admin key can create a session without name and remove it', async () => {
|
||||||
|
const createResponse = await axios.post(
|
||||||
|
`${BASE_URL}/api/sessions`,
|
||||||
|
{},
|
||||||
|
{
|
||||||
|
headers: { 'X-Api-Key': VALID_API_KEY },
|
||||||
|
validateStatus: () => true,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
expect(createResponse.status).toBe(HTTP_CREATED);
|
||||||
|
expect(createResponse.data?.name).toBeTruthy();
|
||||||
|
|
||||||
|
const deleteResponse = await axios.delete(
|
||||||
|
`${BASE_URL}/api/sessions/${createResponse.data.name}`,
|
||||||
|
{
|
||||||
|
headers: { 'X-Api-Key': VALID_API_KEY },
|
||||||
|
validateStatus: () => true,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
expect(deleteResponse.status).toBe(HTTP_OK);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('GET /api/sessions?all=true', () => {
|
||||||
|
beforeAll(async () => {
|
||||||
|
const createResponse = await axios.post(
|
||||||
|
`${BASE_URL}/api/sessions`,
|
||||||
|
{ name: 'another' },
|
||||||
|
{
|
||||||
|
headers: { 'X-Api-Key': VALID_API_KEY },
|
||||||
|
validateStatus: () => true,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
if (![HTTP_CREATED, HTTP_UNPROCESSABLE].includes(createResponse.status)) {
|
||||||
|
throw new Error(
|
||||||
|
`Unexpected status for creating "another" session: ${createResponse.status}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
const deleteResponse = await axios.delete(
|
||||||
|
`${BASE_URL}/api/sessions/another`,
|
||||||
|
{
|
||||||
|
headers: { 'X-Api-Key': VALID_API_KEY },
|
||||||
|
validateStatus: () => true,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
if (![HTTP_OK, HTTP_NOT_FOUND].includes(deleteResponse.status)) {
|
||||||
|
throw new Error(
|
||||||
|
`Unexpected status for deleting "another" session: ${deleteResponse.status}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('admin key returns two sessions', async () => {
|
||||||
|
const response = await axios.get(`${BASE_URL}/api/sessions?all=true`, {
|
||||||
|
headers: { 'X-Api-Key': VALID_API_KEY },
|
||||||
|
validateStatus: () => true,
|
||||||
|
});
|
||||||
|
expect(response.status).toBe(HTTP_OK);
|
||||||
|
expect(response.data).toHaveLength(2);
|
||||||
|
expect(response.data.map((session) => session.name).sort()).toEqual([
|
||||||
|
'another',
|
||||||
|
'default',
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('no api key is unauthorized', async () => {
|
||||||
|
const response = await axios.get(`${BASE_URL}/api/sessions?all=true`, {
|
||||||
|
validateStatus: () => true,
|
||||||
|
});
|
||||||
|
expect(response.status).toBe(HTTP_UNAUTHORIZED);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('session key returns one session', async () => {
|
||||||
|
const response = await axios.get(`${BASE_URL}/api/sessions?all=true`, {
|
||||||
|
headers: { 'X-Api-Key': VALID_SESSION_API_KEY },
|
||||||
|
validateStatus: () => true,
|
||||||
|
});
|
||||||
|
expect(response.status).toBe(HTTP_OK);
|
||||||
|
expect(response.data).toHaveLength(1);
|
||||||
|
expect(response.data[0]?.name).toBe('default');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('GET /api/server/version', () => {
|
||||||
|
test('no api key is unauthorized', async () => {
|
||||||
|
const response = await axios.get(`${BASE_URL}/api/server/version`, {
|
||||||
|
validateStatus: () => true,
|
||||||
|
});
|
||||||
|
expect(response.status).toBe(HTTP_UNAUTHORIZED);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('admin api key is ok', async () => {
|
||||||
|
const response = await axios.get(`${BASE_URL}/api/server/version`, {
|
||||||
|
headers: { 'X-Api-Key': VALID_API_KEY },
|
||||||
|
validateStatus: () => true,
|
||||||
|
});
|
||||||
|
expect(response.status).toBe(HTTP_OK);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('session api key is ok', async () => {
|
||||||
|
const response = await axios.get(`${BASE_URL}/api/server/version`, {
|
||||||
|
headers: { 'X-Api-Key': VALID_SESSION_API_KEY },
|
||||||
|
validateStatus: () => true,
|
||||||
|
});
|
||||||
|
expect(response.status).toBe(HTTP_OK);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('GET /api/server/environment', () => {
|
||||||
|
test('no api key is unauthorized', async () => {
|
||||||
|
const response = await axios.get(`${BASE_URL}/api/server/environment`, {
|
||||||
|
validateStatus: () => true,
|
||||||
|
});
|
||||||
|
expect(response.status).toBe(HTTP_UNAUTHORIZED);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('admin api key is ok', async () => {
|
||||||
|
const response = await axios.get(`${BASE_URL}/api/server/environment`, {
|
||||||
|
headers: { 'X-Api-Key': VALID_API_KEY },
|
||||||
|
validateStatus: () => true,
|
||||||
|
});
|
||||||
|
expect(response.status).toBe(HTTP_OK);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('session api key is forbidden', async () => {
|
||||||
|
const response = await axios.get(`${BASE_URL}/api/server/environment`, {
|
||||||
|
headers: { 'X-Api-Key': VALID_SESSION_API_KEY },
|
||||||
|
validateStatus: () => true,
|
||||||
|
});
|
||||||
|
expect(response.status).toBe(HTTP_FORBIDDEN);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('admin - GET /health', () => {
|
||||||
|
test('no api key is unauthorized', async () => {
|
||||||
|
const response = await axios.get(`${BASE_URL}/health`, {
|
||||||
|
validateStatus: () => true,
|
||||||
|
});
|
||||||
|
expect(response.status).toBe(HTTP_UNAUTHORIZED);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('valid api key is ok', async () => {
|
||||||
|
const response = await axios.get(`${BASE_URL}/health`, {
|
||||||
|
headers: { 'X-Api-Key': VALID_API_KEY },
|
||||||
|
validateStatus: () => true,
|
||||||
|
});
|
||||||
|
expect(response.status).toBe(HTTP_OK);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('invalid api key is unauthorized', async () => {
|
||||||
|
const response = await axios.get(`${BASE_URL}/health`, {
|
||||||
|
headers: { 'X-Api-Key': '123' },
|
||||||
|
validateStatus: () => true,
|
||||||
|
});
|
||||||
|
expect(response.status).toBe(HTTP_UNAUTHORIZED);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('/ws', () => {
|
||||||
|
const buildWsUrl = (apiKey?: string) => {
|
||||||
|
const wsUrl = new URL('/ws', WS_BASE_URL);
|
||||||
|
wsUrl.searchParams.set('session', '*');
|
||||||
|
wsUrl.searchParams.set('events', '*');
|
||||||
|
if (apiKey) {
|
||||||
|
wsUrl.searchParams.set('x-api-key', apiKey);
|
||||||
|
}
|
||||||
|
return wsUrl.toString();
|
||||||
|
};
|
||||||
|
|
||||||
|
const waitForOpen = (socket: WebSocket, timeoutMs = 5_000) =>
|
||||||
|
new Promise<void>((resolve, reject) => {
|
||||||
|
const timeout = setTimeout(() => {
|
||||||
|
reject(new Error('WebSocket open timeout'));
|
||||||
|
}, timeoutMs);
|
||||||
|
socket.once('open', () => {
|
||||||
|
clearTimeout(timeout);
|
||||||
|
resolve();
|
||||||
|
});
|
||||||
|
socket.once('error', (error) => {
|
||||||
|
clearTimeout(timeout);
|
||||||
|
reject(error);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
const waitForClose = (socket: WebSocket, timeoutMs = 5_000) =>
|
||||||
|
new Promise<{ code: number; reason: string }>((resolve, reject) => {
|
||||||
|
const timeout = setTimeout(() => {
|
||||||
|
reject(new Error('WebSocket close timeout'));
|
||||||
|
}, timeoutMs);
|
||||||
|
socket.once('close', (code, reason) => {
|
||||||
|
clearTimeout(timeout);
|
||||||
|
resolve({ code, reason: reason.toString() });
|
||||||
|
});
|
||||||
|
socket.once('error', (error) => {
|
||||||
|
clearTimeout(timeout);
|
||||||
|
reject(error);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('no api key is unauthorized', async () => {
|
||||||
|
const socket = new WebSocket(buildWsUrl());
|
||||||
|
const { code } = await waitForClose(socket);
|
||||||
|
expect(code).toBe(WS_POLICY_VIOLATION);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('admin api key is ok', async () => {
|
||||||
|
const socket = new WebSocket(buildWsUrl(VALID_API_KEY));
|
||||||
|
await waitForOpen(socket);
|
||||||
|
socket.close();
|
||||||
|
const { code } = await waitForClose(socket);
|
||||||
|
expect(WS_OK_CODES).toContain(code);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('GET /api/files/test.txt', () => {
|
||||||
|
// create "test.txt" in current dir/.media/test.txt
|
||||||
|
let file = null;
|
||||||
|
beforeAll(() => {
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
const mediaDir = path.resolve('./.media');
|
||||||
|
if (!fs.existsSync(mediaDir)) {
|
||||||
|
fs.mkdirSync(mediaDir);
|
||||||
|
}
|
||||||
|
const filePath = path.join(mediaDir, 'test.txt');
|
||||||
|
fs.writeFileSync(filePath, 'This is a test file.');
|
||||||
|
file = filePath;
|
||||||
|
});
|
||||||
|
test('no api key is unauthorized', async () => {
|
||||||
|
const response = await axios.get(`${BASE_URL}/api/files/test.txt`, {
|
||||||
|
validateStatus: () => true,
|
||||||
|
});
|
||||||
|
expect(response.status).toBe(HTTP_UNAUTHORIZED);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('valid api key is ok', async () => {
|
||||||
|
const response = await axios.get(`${BASE_URL}/api/files/test.txt`, {
|
||||||
|
headers: { 'X-Api-Key': VALID_API_KEY },
|
||||||
|
validateStatus: () => true,
|
||||||
|
});
|
||||||
|
expect(response.status).toBe(HTTP_OK);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('invalid api key is unauthorized', async () => {
|
||||||
|
const response = await axios.get(`${BASE_URL}/api/files/test.txt`, {
|
||||||
|
headers: { 'X-Api-Key': '123' },
|
||||||
|
validateStatus: () => true,
|
||||||
|
});
|
||||||
|
expect(response.status).toBe(HTTP_UNAUTHORIZED);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('GET /', () => {
|
||||||
|
test('no auth is unauthorized', async () => {
|
||||||
|
const response = await axios.get(`${BASE_URL}/`, {
|
||||||
|
validateStatus: () => true,
|
||||||
|
});
|
||||||
|
expect(response.status).toBe(HTTP_UNAUTHORIZED);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('valid auth is ok', async () => {
|
||||||
|
const response = await axios.get(`${BASE_URL}/`, {
|
||||||
|
auth: { username: VALID_USERNAME, password: VALID_PASSWORD },
|
||||||
|
validateStatus: () => true,
|
||||||
|
});
|
||||||
|
expect(response.status).toBe(HTTP_OK);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('wrong auth is unauthorized', async () => {
|
||||||
|
const response = await axios.get(`${BASE_URL}/`, {
|
||||||
|
auth: { username: VALID_USERNAME, password: 'password-another' },
|
||||||
|
validateStatus: () => true,
|
||||||
|
});
|
||||||
|
expect(response.status).toBe(HTTP_UNAUTHORIZED);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('GET /dashboard', () => {
|
||||||
|
test('no auth is unauthorized', async () => {
|
||||||
|
const response = await axios.get(`${BASE_URL}/dashboard/`, {
|
||||||
|
validateStatus: () => true,
|
||||||
|
});
|
||||||
|
expect(response.status).toBe(HTTP_UNAUTHORIZED);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('valid auth is ok', async () => {
|
||||||
|
const response = await axios.get(`${BASE_URL}/dashboard/`, {
|
||||||
|
auth: { username: VALID_USERNAME, password: VALID_PASSWORD },
|
||||||
|
validateStatus: () => true,
|
||||||
|
});
|
||||||
|
expect(response.status).toBe(HTTP_OK);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('wrong auth is unauthorized', async () => {
|
||||||
|
const response = await axios.get(`${BASE_URL}/dashboard/`, {
|
||||||
|
auth: { username: VALID_USERNAME, password: 'password-another' },
|
||||||
|
validateStatus: () => true,
|
||||||
|
});
|
||||||
|
expect(response.status).toBe(HTTP_UNAUTHORIZED);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('session key - GET /api/sessions/{name}', () => {
|
||||||
|
test('default key - default session - is authorized', async () => {
|
||||||
|
const response = await axios.get(`${BASE_URL}/api/sessions/default`, {
|
||||||
|
headers: { 'X-Api-Key': VALID_SESSION_API_KEY },
|
||||||
|
validateStatus: () => true,
|
||||||
|
});
|
||||||
|
expect(response.status).toBe(HTTP_OK);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('default key - create a new sessions - forbidden', async () => {
|
||||||
|
const response = await axios.post(
|
||||||
|
`${BASE_URL}/api/sessions`,
|
||||||
|
{ name: 'newone' },
|
||||||
|
{
|
||||||
|
headers: { 'X-Api-Key': VALID_SESSION_API_KEY },
|
||||||
|
validateStatus: () => true,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
expect(response.status).toBe(HTTP_FORBIDDEN);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('another key - default session - unauthorized', async () => {
|
||||||
|
const response = await axios.get(`${BASE_URL}/api/sessions/default`, {
|
||||||
|
headers: { 'X-Api-Key': 'key_another' },
|
||||||
|
validateStatus: () => true,
|
||||||
|
});
|
||||||
|
expect(response.status).toBe(HTTP_UNAUTHORIZED);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('default key - another session - forbidden', async () => {
|
||||||
|
const response = await axios.get(`${BASE_URL}/api/sessions/another`, {
|
||||||
|
headers: { 'X-Api-Key': VALID_SESSION_API_KEY },
|
||||||
|
validateStatus: () => true,
|
||||||
|
});
|
||||||
|
expect(response.status).toBe(HTTP_FORBIDDEN);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,139 @@
|
|||||||
|
import {
|
||||||
|
Body,
|
||||||
|
Controller,
|
||||||
|
Delete,
|
||||||
|
Get,
|
||||||
|
NotFoundException,
|
||||||
|
Param,
|
||||||
|
Post,
|
||||||
|
Put,
|
||||||
|
UnprocessableEntityException,
|
||||||
|
UseGuards,
|
||||||
|
UsePipes,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { ApiOperation, ApiSecurity, ApiTags } from '@nestjs/swagger';
|
||||||
|
import { SessionManager } from '@waha/core/abc/manager.abc';
|
||||||
|
import { Action } from '@waha/core/auth/casl.types';
|
||||||
|
import { CanServer } from '@waha/core/auth/policies';
|
||||||
|
import { CheckPolicies } from '@waha/core/auth/policies.decorator';
|
||||||
|
import { PoliciesGuard } from '@waha/core/auth/policies.guard';
|
||||||
|
import { ApiKey, CheckInvariant } from '@waha/core/storage/IApiKeyRepository';
|
||||||
|
import { WAHAValidationPipe } from '@waha/nestjs/pipes/WAHAValidationPipe';
|
||||||
|
import { ApiKeyDTO, ApiKeyRequest } from '@waha/structures/apikeys.dto';
|
||||||
|
import { generatePrefixedId, generateSecret } from '@waha/utils/ids';
|
||||||
|
|
||||||
|
@ApiSecurity('api_key')
|
||||||
|
@Controller('api/keys')
|
||||||
|
@ApiTags('🔑 Api Keys')
|
||||||
|
@UseGuards(PoliciesGuard)
|
||||||
|
@CheckPolicies(CanServer(Action.Manage))
|
||||||
|
export class ApiKeysController {
|
||||||
|
constructor(private manager: SessionManager) {}
|
||||||
|
|
||||||
|
@Post('/')
|
||||||
|
@ApiOperation({ summary: 'Create a new API key' })
|
||||||
|
@UsePipes(new WAHAValidationPipe())
|
||||||
|
async create(@Body() body: ApiKeyRequest): Promise<ApiKeyDTO> {
|
||||||
|
CheckInvariant(body);
|
||||||
|
if (body.session) {
|
||||||
|
const exists = await this.manager.exists(body.session);
|
||||||
|
if (!exists) {
|
||||||
|
throw new UnprocessableEntityException(
|
||||||
|
`Session "${body.session}" does not exist`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let apikey: ApiKey | null = null;
|
||||||
|
// Try 5 times to check there's no conflict on id and key
|
||||||
|
for (let i = 0; i < 5; i++) {
|
||||||
|
apikey = {
|
||||||
|
id: generatePrefixedId('key_id'),
|
||||||
|
key: `key_${generateSecret(32)}`,
|
||||||
|
isActive: body.isActive,
|
||||||
|
isAdmin: body.isAdmin,
|
||||||
|
session: body.session,
|
||||||
|
rules: null,
|
||||||
|
};
|
||||||
|
const idExists = await this.manager.apiKeyRepository.getById(apikey.id);
|
||||||
|
if (idExists) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const keyExists = await this.manager.apiKeyRepository.getByKey(
|
||||||
|
apikey.key,
|
||||||
|
);
|
||||||
|
if (keyExists) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (!apikey) {
|
||||||
|
throw new UnprocessableEntityException(
|
||||||
|
`Failed to generate API key, try again`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
CheckInvariant(apikey);
|
||||||
|
await this.manager.apiKeyRepository.upsert(apikey);
|
||||||
|
return ApiKeyToDTO(apikey);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get('/')
|
||||||
|
@ApiOperation({ summary: 'Get all API keys' })
|
||||||
|
async list(): Promise<ApiKeyDTO[]> {
|
||||||
|
const keys = await this.manager.apiKeyRepository.list();
|
||||||
|
return keys.map((key) => ApiKeyToDTO(key));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Put('/:id')
|
||||||
|
@ApiOperation({ summary: 'Update an API key' })
|
||||||
|
@UsePipes(new WAHAValidationPipe())
|
||||||
|
async update(
|
||||||
|
@Param('id') id: string,
|
||||||
|
@Body() body: ApiKeyRequest,
|
||||||
|
): Promise<ApiKeyDTO> {
|
||||||
|
const existing = await this.manager.apiKeyRepository.getById(id);
|
||||||
|
if (!existing) {
|
||||||
|
throw new NotFoundException('API key not found');
|
||||||
|
}
|
||||||
|
|
||||||
|
const apikey: ApiKey = {
|
||||||
|
...existing,
|
||||||
|
isActive: body.isActive,
|
||||||
|
isAdmin: body.isAdmin,
|
||||||
|
session: body.session,
|
||||||
|
};
|
||||||
|
CheckInvariant(apikey);
|
||||||
|
if (apikey.session) {
|
||||||
|
const exists = await this.manager.exists(apikey.session);
|
||||||
|
if (!exists) {
|
||||||
|
throw new UnprocessableEntityException(
|
||||||
|
`Session "${apikey.session}" does not exist`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
CheckInvariant(apikey);
|
||||||
|
await this.manager.apiKeyRepository.upsert(apikey);
|
||||||
|
return ApiKeyToDTO(apikey);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Delete('/:id')
|
||||||
|
@ApiOperation({ summary: 'Delete an API key' })
|
||||||
|
async delete(@Param('id') id: string): Promise<{ result: true }> {
|
||||||
|
const existing = await this.manager.apiKeyRepository.getById(id);
|
||||||
|
if (!existing) {
|
||||||
|
throw new NotFoundException('API key not found');
|
||||||
|
}
|
||||||
|
await this.manager.apiKeyRepository.deleteById(id);
|
||||||
|
return { result: true };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function ApiKeyToDTO(apikey: ApiKey): ApiKeyDTO {
|
||||||
|
return {
|
||||||
|
id: apikey.id,
|
||||||
|
key: apikey.key,
|
||||||
|
isActive: apikey.isActive,
|
||||||
|
isAdmin: apikey.isAdmin,
|
||||||
|
session: apikey.session,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -5,6 +5,7 @@ import {
|
|||||||
Post,
|
Post,
|
||||||
Query,
|
Query,
|
||||||
UseInterceptors,
|
UseInterceptors,
|
||||||
|
UseGuards,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { ApiOperation, ApiSecurity, ApiTags } from '@nestjs/swagger';
|
import { ApiOperation, ApiSecurity, ApiTags } from '@nestjs/swagger';
|
||||||
import { ApiFileAcceptHeader } from '@waha/nestjs/ApiFileAcceptHeader';
|
import { ApiFileAcceptHeader } from '@waha/nestjs/ApiFileAcceptHeader';
|
||||||
@@ -24,10 +25,17 @@ import {
|
|||||||
RequestCodeRequest,
|
RequestCodeRequest,
|
||||||
} from '../structures/auth.dto';
|
} from '../structures/auth.dto';
|
||||||
import { Base64File } from '../structures/files.dto';
|
import { Base64File } from '../structures/files.dto';
|
||||||
|
import { PoliciesGuard } from '@waha/core/auth/policies.guard';
|
||||||
|
import { CheckPolicies } from '@waha/core/auth/policies.decorator';
|
||||||
|
import { CanSession, FromParam } from '@waha/core/auth/policies';
|
||||||
|
|
||||||
|
import { Action } from '@waha/core/auth/casl.types';
|
||||||
|
|
||||||
@ApiSecurity('api_key')
|
@ApiSecurity('api_key')
|
||||||
@Controller('api/:session/auth')
|
@Controller('api/:session/auth')
|
||||||
@ApiTags('🔑 Auth')
|
@ApiTags('📱 Pairing')
|
||||||
|
@UseGuards(PoliciesGuard)
|
||||||
|
@CheckPolicies(CanSession(Action.Use, FromParam('session')))
|
||||||
class AuthController {
|
class AuthController {
|
||||||
constructor(private manager: SessionManager) {}
|
constructor(private manager: SessionManager) {}
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import {
|
|||||||
Body,
|
Body,
|
||||||
Controller,
|
Controller,
|
||||||
Post,
|
Post,
|
||||||
|
UseGuards,
|
||||||
UsePipes,
|
UsePipes,
|
||||||
ValidationPipe,
|
ValidationPipe,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
@@ -14,10 +15,17 @@ import {
|
|||||||
import { SessionManager } from '../core/abc/manager.abc';
|
import { SessionManager } from '../core/abc/manager.abc';
|
||||||
import { WhatsappSession } from '../core/abc/session.abc';
|
import { WhatsappSession } from '../core/abc/session.abc';
|
||||||
import { RejectCallRequest } from '../structures/calls.dto';
|
import { RejectCallRequest } from '../structures/calls.dto';
|
||||||
|
import { PoliciesGuard } from '@waha/core/auth/policies.guard';
|
||||||
|
import { CheckPolicies } from '@waha/core/auth/policies.decorator';
|
||||||
|
import { CanSession, FromParam } from '@waha/core/auth/policies';
|
||||||
|
|
||||||
|
import { Action } from '@waha/core/auth/casl.types';
|
||||||
|
|
||||||
@ApiSecurity('api_key')
|
@ApiSecurity('api_key')
|
||||||
@Controller('api/:session/calls')
|
@Controller('api/:session/calls')
|
||||||
@ApiTags('📞 Calls')
|
@ApiTags('📞 Calls')
|
||||||
|
@UseGuards(PoliciesGuard)
|
||||||
|
@CheckPolicies(CanSession(Action.Use, FromParam('session')))
|
||||||
export class CallsController {
|
export class CallsController {
|
||||||
constructor(private manager: SessionManager) {}
|
constructor(private manager: SessionManager) {}
|
||||||
|
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import {
|
|||||||
Param,
|
Param,
|
||||||
Post,
|
Post,
|
||||||
Query,
|
Query,
|
||||||
|
UseGuards,
|
||||||
UsePipes,
|
UsePipes,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { ApiOperation, ApiParam, ApiSecurity, ApiTags } from '@nestjs/swagger';
|
import { ApiOperation, ApiParam, ApiSecurity, ApiTags } from '@nestjs/swagger';
|
||||||
@@ -39,10 +40,17 @@ import {
|
|||||||
parseChannelInviteLink,
|
parseChannelInviteLink,
|
||||||
WhatsappSession,
|
WhatsappSession,
|
||||||
} from '../core/abc/session.abc';
|
} from '../core/abc/session.abc';
|
||||||
|
import { PoliciesGuard } from '@waha/core/auth/policies.guard';
|
||||||
|
import { CheckPolicies } from '@waha/core/auth/policies.decorator';
|
||||||
|
import { CanSession, FromParam } from '@waha/core/auth/policies';
|
||||||
|
|
||||||
|
import { Action } from '@waha/core/auth/casl.types';
|
||||||
|
|
||||||
@ApiSecurity('api_key')
|
@ApiSecurity('api_key')
|
||||||
@Controller('api/:session/channels')
|
@Controller('api/:session/channels')
|
||||||
@ApiTags('📢 Channels')
|
@ApiTags('📢 Channels')
|
||||||
|
@UseGuards(PoliciesGuard)
|
||||||
|
@CheckPolicies(CanSession(Action.Use, FromParam('session')))
|
||||||
export class ChannelsController {
|
export class ChannelsController {
|
||||||
constructor(
|
constructor(
|
||||||
private manager: SessionManager,
|
private manager: SessionManager,
|
||||||
@@ -123,14 +131,15 @@ export class ChannelsController {
|
|||||||
})
|
})
|
||||||
async previewChannelMessages(
|
async previewChannelMessages(
|
||||||
@WorkingSessionParam session: WhatsappSession,
|
@WorkingSessionParam session: WhatsappSession,
|
||||||
@Param('id') code: string,
|
@Param('id') codeOrId: string,
|
||||||
@Query() query: PreviewChannelMessages,
|
@Query() query: PreviewChannelMessages,
|
||||||
): Promise<ChannelMessage[]> {
|
): Promise<ChannelMessage[]> {
|
||||||
if (isJidNewsletter(code)) {
|
let code = null;
|
||||||
const channel = await session.channelsGetChannel(code);
|
if (isJidNewsletter(codeOrId)) {
|
||||||
|
const channel = await session.channelsGetChannel(codeOrId);
|
||||||
code = parseChannelInviteLink(channel.invite);
|
code = parseChannelInviteLink(channel.invite);
|
||||||
}
|
}
|
||||||
const inviteCode = parseChannelInviteLink(code);
|
const inviteCode = parseChannelInviteLink(code || codeOrId);
|
||||||
return session.previewChannelMessages(inviteCode, query);
|
return session.previewChannelMessages(inviteCode, query);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import {
|
|||||||
Post,
|
Post,
|
||||||
Put,
|
Put,
|
||||||
Query,
|
Query,
|
||||||
|
UseGuards,
|
||||||
UsePipes,
|
UsePipes,
|
||||||
ValidationPipe,
|
ValidationPipe,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
@@ -24,15 +25,15 @@ import { WhatsappSession } from '../core/abc/session.abc';
|
|||||||
import {
|
import {
|
||||||
ChatPictureQuery,
|
ChatPictureQuery,
|
||||||
ChatPictureResponse,
|
ChatPictureResponse,
|
||||||
ChatsPaginationParams,
|
|
||||||
ChatSummary,
|
ChatSummary,
|
||||||
GetChatMessageQuery,
|
GetChatMessageQuery,
|
||||||
GetChatMessagesFilter,
|
GetChatMessagesFilter,
|
||||||
GetChatMessagesQuery,
|
GetChatMessagesQuery,
|
||||||
|
GetChatsOverviewParams,
|
||||||
|
GetChatsParams,
|
||||||
MessageSortField,
|
MessageSortField,
|
||||||
OverviewBodyRequest,
|
OverviewBodyRequest,
|
||||||
OverviewFilter,
|
OverviewFilter,
|
||||||
OverviewPaginationParams,
|
|
||||||
PinMessageRequest,
|
PinMessageRequest,
|
||||||
ReadChatMessagesQuery,
|
ReadChatMessagesQuery,
|
||||||
ReadChatMessagesResponse,
|
ReadChatMessagesResponse,
|
||||||
@@ -40,11 +41,18 @@ import {
|
|||||||
} from '../structures/chats.dto';
|
} from '../structures/chats.dto';
|
||||||
import { EditMessageRequest } from '../structures/chatting.dto';
|
import { EditMessageRequest } from '../structures/chatting.dto';
|
||||||
import { SortOrder } from '@waha/structures/pagination.dto';
|
import { SortOrder } from '@waha/structures/pagination.dto';
|
||||||
|
import { PoliciesGuard } from '@waha/core/auth/policies.guard';
|
||||||
|
import { CheckPolicies } from '@waha/core/auth/policies.decorator';
|
||||||
|
import { CanSession, FromParam } from '@waha/core/auth/policies';
|
||||||
|
|
||||||
|
import { Action } from '@waha/core/auth/casl.types';
|
||||||
|
|
||||||
@ApiSecurity('api_key')
|
@ApiSecurity('api_key')
|
||||||
@Controller('api/:session/chats')
|
@Controller('api/:session/chats')
|
||||||
@ApiTags('💬 Chats')
|
@ApiTags('💬 Chats')
|
||||||
@UsePipes(new ValidationPipe({ transform: true }))
|
@UsePipes(new ValidationPipe({ transform: true }))
|
||||||
|
@UseGuards(PoliciesGuard)
|
||||||
|
@CheckPolicies(CanSession(Action.Use, FromParam('session')))
|
||||||
class ChatsController {
|
class ChatsController {
|
||||||
constructor(private manager: SessionManager) {}
|
constructor(private manager: SessionManager) {}
|
||||||
|
|
||||||
@@ -53,7 +61,7 @@ class ChatsController {
|
|||||||
@ApiOperation({ summary: 'Get chats' })
|
@ApiOperation({ summary: 'Get chats' })
|
||||||
getChats(
|
getChats(
|
||||||
@WorkingSessionParam session: WhatsappSession,
|
@WorkingSessionParam session: WhatsappSession,
|
||||||
@Query() pagination: ChatsPaginationParams,
|
@Query() pagination: GetChatsParams,
|
||||||
) {
|
) {
|
||||||
return session.getChats(pagination);
|
return session.getChats(pagination);
|
||||||
}
|
}
|
||||||
@@ -67,7 +75,7 @@ class ChatsController {
|
|||||||
@UsePipes(new ValidationPipe({ transform: true, whitelist: true }))
|
@UsePipes(new ValidationPipe({ transform: true, whitelist: true }))
|
||||||
getChatsOverview(
|
getChatsOverview(
|
||||||
@WorkingSessionParam session: WhatsappSession,
|
@WorkingSessionParam session: WhatsappSession,
|
||||||
@Query() pagination: OverviewPaginationParams,
|
@Query() pagination: GetChatsOverviewParams,
|
||||||
@Query() filter: OverviewFilter,
|
@Query() filter: OverviewFilter,
|
||||||
): Promise<ChatSummary[]> {
|
): Promise<ChatSummary[]> {
|
||||||
return session.getChatsOverview(pagination, filter);
|
return session.getChatsOverview(pagination, filter);
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import {
|
|||||||
Post,
|
Post,
|
||||||
Put,
|
Put,
|
||||||
Query,
|
Query,
|
||||||
|
UseGuards,
|
||||||
UsePipes,
|
UsePipes,
|
||||||
ValidationPipe,
|
ValidationPipe,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
@@ -48,15 +49,22 @@ import {
|
|||||||
mentionsAll,
|
mentionsAll,
|
||||||
validateRequestMentions,
|
validateRequestMentions,
|
||||||
} from '@waha/core/utils/mentions.all';
|
} from '@waha/core/utils/mentions.all';
|
||||||
|
import { PoliciesGuard } from '@waha/core/auth/policies.guard';
|
||||||
|
import { CheckPolicies } from '@waha/core/auth/policies.decorator';
|
||||||
|
import { CanSession, FromBody, FromQuery } from '@waha/core/auth/policies';
|
||||||
|
|
||||||
|
import { Action } from '@waha/core/auth/casl.types';
|
||||||
|
|
||||||
@ApiSecurity('api_key')
|
@ApiSecurity('api_key')
|
||||||
@Controller('api')
|
@Controller('api')
|
||||||
@ApiTags('📤 Chatting')
|
@ApiTags('📤 Chatting')
|
||||||
|
@UseGuards(PoliciesGuard)
|
||||||
export class ChattingController {
|
export class ChattingController {
|
||||||
constructor(private manager: SessionManager) {}
|
constructor(private manager: SessionManager) {}
|
||||||
|
|
||||||
@Post('/sendText')
|
@Post('/sendText')
|
||||||
@ApiOperation({ summary: 'Send a text message' })
|
@ApiOperation({ summary: 'Send a text message' })
|
||||||
|
@CheckPolicies(CanSession(Action.Use, FromBody('session')))
|
||||||
async sendText(@Body() request: MessageTextRequest): Promise<WAMessage> {
|
async sendText(@Body() request: MessageTextRequest): Promise<WAMessage> {
|
||||||
const whatsapp = await this.manager.getWorkingSession(request.session);
|
const whatsapp = await this.manager.getWorkingSession(request.session);
|
||||||
if (mentionsAll(request)) {
|
if (mentionsAll(request)) {
|
||||||
@@ -72,6 +80,7 @@ export class ChattingController {
|
|||||||
description:
|
description:
|
||||||
'Either from an URL or base64 data - look at the request schemas for details.',
|
'Either from an URL or base64 data - look at the request schemas for details.',
|
||||||
})
|
})
|
||||||
|
@CheckPolicies(CanSession(Action.Use, FromBody('session')))
|
||||||
async sendImage(@Body() request: MessageImageRequest) {
|
async sendImage(@Body() request: MessageImageRequest) {
|
||||||
const whatsapp = await this.manager.getWorkingSession(request.session);
|
const whatsapp = await this.manager.getWorkingSession(request.session);
|
||||||
if (mentionsAll(request)) {
|
if (mentionsAll(request)) {
|
||||||
@@ -87,6 +96,7 @@ export class ChattingController {
|
|||||||
description:
|
description:
|
||||||
'Either from an URL or base64 data - look at the request schemas for details.',
|
'Either from an URL or base64 data - look at the request schemas for details.',
|
||||||
})
|
})
|
||||||
|
@CheckPolicies(CanSession(Action.Use, FromBody('session')))
|
||||||
async sendFile(@Body() request: MessageFileRequest) {
|
async sendFile(@Body() request: MessageFileRequest) {
|
||||||
const whatsapp = await this.manager.getWorkingSession(request.session);
|
const whatsapp = await this.manager.getWorkingSession(request.session);
|
||||||
if (mentionsAll(request)) {
|
if (mentionsAll(request)) {
|
||||||
@@ -102,6 +112,7 @@ export class ChattingController {
|
|||||||
description:
|
description:
|
||||||
'Either from an URL or base64 data - look at the request schemas for details.',
|
'Either from an URL or base64 data - look at the request schemas for details.',
|
||||||
})
|
})
|
||||||
|
@CheckPolicies(CanSession(Action.Use, FromBody('session')))
|
||||||
async sendVoice(@Body() request: MessageVoiceRequest) {
|
async sendVoice(@Body() request: MessageVoiceRequest) {
|
||||||
const whatsapp = await this.manager.getWorkingSession(request.session);
|
const whatsapp = await this.manager.getWorkingSession(request.session);
|
||||||
return whatsapp.sendVoice(request);
|
return whatsapp.sendVoice(request);
|
||||||
@@ -113,6 +124,7 @@ export class ChattingController {
|
|||||||
description:
|
description:
|
||||||
'Either from an URL or base64 data - look at the request schemas for details.',
|
'Either from an URL or base64 data - look at the request schemas for details.',
|
||||||
})
|
})
|
||||||
|
@CheckPolicies(CanSession(Action.Use, FromBody('session')))
|
||||||
async sendVideo(@Body() request: MessageVideoRequest) {
|
async sendVideo(@Body() request: MessageVideoRequest) {
|
||||||
const whatsapp = await this.manager.getWorkingSession(request.session);
|
const whatsapp = await this.manager.getWorkingSession(request.session);
|
||||||
if (mentionsAll(request)) {
|
if (mentionsAll(request)) {
|
||||||
@@ -128,6 +140,7 @@ export class ChattingController {
|
|||||||
description:
|
description:
|
||||||
'You can use regular /api/sendText if you wanna send auto-generated link preview.',
|
'You can use regular /api/sendText if you wanna send auto-generated link preview.',
|
||||||
})
|
})
|
||||||
|
@CheckPolicies(CanSession(Action.Use, FromBody('session')))
|
||||||
@UsePipes(new WAHAValidationPipe())
|
@UsePipes(new WAHAValidationPipe())
|
||||||
async sendLinkCustomPreview(
|
async sendLinkCustomPreview(
|
||||||
@Body() request: MessageLinkCustomPreviewRequest,
|
@Body() request: MessageLinkCustomPreviewRequest,
|
||||||
@@ -147,6 +160,7 @@ export class ChattingController {
|
|||||||
description: 'Send Buttons',
|
description: 'Send Buttons',
|
||||||
deprecated: true,
|
deprecated: true,
|
||||||
})
|
})
|
||||||
|
@CheckPolicies(CanSession(Action.Use, FromBody('session')))
|
||||||
@UsePipes(new WAHAValidationPipe())
|
@UsePipes(new WAHAValidationPipe())
|
||||||
async sendButtons(@Body() request: SendButtonsRequest) {
|
async sendButtons(@Body() request: SendButtonsRequest) {
|
||||||
const whatsapp = await this.manager.getWorkingSession(request.session);
|
const whatsapp = await this.manager.getWorkingSession(request.session);
|
||||||
@@ -158,6 +172,7 @@ export class ChattingController {
|
|||||||
summary: 'Send a list message (interactive)',
|
summary: 'Send a list message (interactive)',
|
||||||
description: 'Send a List message with sections and rows',
|
description: 'Send a List message with sections and rows',
|
||||||
})
|
})
|
||||||
|
@CheckPolicies(CanSession(Action.Use, FromBody('session')))
|
||||||
@UsePipes(new WAHAValidationPipe())
|
@UsePipes(new WAHAValidationPipe())
|
||||||
async sendList(@Body() request: SendListRequest) {
|
async sendList(@Body() request: SendListRequest) {
|
||||||
const whatsapp = await this.manager.getWorkingSession(request.session);
|
const whatsapp = await this.manager.getWorkingSession(request.session);
|
||||||
@@ -165,6 +180,7 @@ export class ChattingController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Post('/forwardMessage')
|
@Post('/forwardMessage')
|
||||||
|
@CheckPolicies(CanSession(Action.Use, FromBody('session')))
|
||||||
async forwardMessage(
|
async forwardMessage(
|
||||||
@Body() request: MessageForwardRequest,
|
@Body() request: MessageForwardRequest,
|
||||||
): Promise<WAMessage> {
|
): Promise<WAMessage> {
|
||||||
@@ -173,6 +189,7 @@ export class ChattingController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Post('/sendSeen')
|
@Post('/sendSeen')
|
||||||
|
@CheckPolicies(CanSession(Action.Use, FromBody('session')))
|
||||||
async sendSeen(@Body() chat: SendSeenRequest) {
|
async sendSeen(@Body() chat: SendSeenRequest) {
|
||||||
const hasMessageId = chat.messageIds?.length > 0 || Boolean(chat.messageId);
|
const hasMessageId = chat.messageIds?.length > 0 || Boolean(chat.messageId);
|
||||||
if (!hasMessageId) {
|
if (!hasMessageId) {
|
||||||
@@ -188,6 +205,7 @@ export class ChattingController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Post('/startTyping')
|
@Post('/startTyping')
|
||||||
|
@CheckPolicies(CanSession(Action.Use, FromBody('session')))
|
||||||
async startTyping(@Body() chat: ChatRequest) {
|
async startTyping(@Body() chat: ChatRequest) {
|
||||||
// It's infinitive action
|
// It's infinitive action
|
||||||
const whatsapp = await this.manager.getWorkingSession(chat.session);
|
const whatsapp = await this.manager.getWorkingSession(chat.session);
|
||||||
@@ -196,6 +214,7 @@ export class ChattingController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Post('/stopTyping')
|
@Post('/stopTyping')
|
||||||
|
@CheckPolicies(CanSession(Action.Use, FromBody('session')))
|
||||||
async stopTyping(@Body() chat: ChatRequest) {
|
async stopTyping(@Body() chat: ChatRequest) {
|
||||||
const whatsapp = await this.manager.getWorkingSession(chat.session);
|
const whatsapp = await this.manager.getWorkingSession(chat.session);
|
||||||
await whatsapp.stopTyping(chat);
|
await whatsapp.stopTyping(chat);
|
||||||
@@ -204,6 +223,7 @@ export class ChattingController {
|
|||||||
|
|
||||||
@Put('/reaction')
|
@Put('/reaction')
|
||||||
@ApiOperation({ summary: 'React to a message with an emoji' })
|
@ApiOperation({ summary: 'React to a message with an emoji' })
|
||||||
|
@CheckPolicies(CanSession(Action.Use, FromBody('session')))
|
||||||
async setReaction(@Body() request: MessageReactionRequest) {
|
async setReaction(@Body() request: MessageReactionRequest) {
|
||||||
const whatsapp = await this.manager.getWorkingSession(request.session);
|
const whatsapp = await this.manager.getWorkingSession(request.session);
|
||||||
return whatsapp.setReaction(request);
|
return whatsapp.setReaction(request);
|
||||||
@@ -211,6 +231,7 @@ export class ChattingController {
|
|||||||
|
|
||||||
@Put('/star')
|
@Put('/star')
|
||||||
@ApiOperation({ summary: 'Star or unstar a message' })
|
@ApiOperation({ summary: 'Star or unstar a message' })
|
||||||
|
@CheckPolicies(CanSession(Action.Use, FromBody('session')))
|
||||||
async setStar(@Body() request: MessageStarRequest) {
|
async setStar(@Body() request: MessageStarRequest) {
|
||||||
const whatsapp = await this.manager.getWorkingSession(request.session);
|
const whatsapp = await this.manager.getWorkingSession(request.session);
|
||||||
await whatsapp.setStar(request);
|
await whatsapp.setStar(request);
|
||||||
@@ -222,6 +243,7 @@ export class ChattingController {
|
|||||||
summary: 'Send a poll with options',
|
summary: 'Send a poll with options',
|
||||||
description: 'You can use it as buttons or list replacement',
|
description: 'You can use it as buttons or list replacement',
|
||||||
})
|
})
|
||||||
|
@CheckPolicies(CanSession(Action.Use, FromBody('session')))
|
||||||
async sendPoll(@Body() request: MessagePollRequest) {
|
async sendPoll(@Body() request: MessagePollRequest) {
|
||||||
const whatsapp = await this.manager.getWorkingSession(request.session);
|
const whatsapp = await this.manager.getWorkingSession(request.session);
|
||||||
return whatsapp.sendPoll(request);
|
return whatsapp.sendPoll(request);
|
||||||
@@ -232,6 +254,7 @@ export class ChattingController {
|
|||||||
summary: 'Vote on a poll',
|
summary: 'Vote on a poll',
|
||||||
description: 'Cast vote(s) on an existing poll message',
|
description: 'Cast vote(s) on an existing poll message',
|
||||||
})
|
})
|
||||||
|
@CheckPolicies(CanSession(Action.Use, FromBody('session')))
|
||||||
@UsePipes(new WAHAValidationPipe())
|
@UsePipes(new WAHAValidationPipe())
|
||||||
async sendPollVote(@Body() request: MessagePollVoteRequest) {
|
async sendPollVote(@Body() request: MessagePollVoteRequest) {
|
||||||
const whatsapp = await this.manager.getWorkingSession(request.session);
|
const whatsapp = await this.manager.getWorkingSession(request.session);
|
||||||
@@ -239,12 +262,14 @@ export class ChattingController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Post('/sendLocation')
|
@Post('/sendLocation')
|
||||||
|
@CheckPolicies(CanSession(Action.Use, FromBody('session')))
|
||||||
async sendLocation(@Body() request: MessageLocationRequest) {
|
async sendLocation(@Body() request: MessageLocationRequest) {
|
||||||
const whatsapp = await this.manager.getWorkingSession(request.session);
|
const whatsapp = await this.manager.getWorkingSession(request.session);
|
||||||
return whatsapp.sendLocation(request);
|
return whatsapp.sendLocation(request);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Post('/sendContactVcard')
|
@Post('/sendContactVcard')
|
||||||
|
@CheckPolicies(CanSession(Action.Use, FromBody('session')))
|
||||||
async sendContactVcard(@Body() request: MessageContactVcardRequest) {
|
async sendContactVcard(@Body() request: MessageContactVcardRequest) {
|
||||||
const whatsapp = await this.manager.getWorkingSession(request.session);
|
const whatsapp = await this.manager.getWorkingSession(request.session);
|
||||||
return whatsapp.sendContactVCard(request);
|
return whatsapp.sendContactVCard(request);
|
||||||
@@ -254,6 +279,7 @@ export class ChattingController {
|
|||||||
@ApiOperation({
|
@ApiOperation({
|
||||||
summary: 'Reply on a button message',
|
summary: 'Reply on a button message',
|
||||||
})
|
})
|
||||||
|
@CheckPolicies(CanSession(Action.Use, FromBody('session')))
|
||||||
@UsePipes(new ValidationPipe({ transform: true, whitelist: true }))
|
@UsePipes(new ValidationPipe({ transform: true, whitelist: true }))
|
||||||
async sendButtonsReply(@Body() request: MessageButtonReply) {
|
async sendButtonsReply(@Body() request: MessageButtonReply) {
|
||||||
const whatsapp = await this.manager.getWorkingSession(request.session);
|
const whatsapp = await this.manager.getWorkingSession(request.session);
|
||||||
@@ -262,6 +288,7 @@ export class ChattingController {
|
|||||||
|
|
||||||
@Get('/sendText')
|
@Get('/sendText')
|
||||||
@ApiOperation({ summary: 'Send a text message', deprecated: true })
|
@ApiOperation({ summary: 'Send a text message', deprecated: true })
|
||||||
|
@CheckPolicies(CanSession(Action.Use, FromQuery('session')))
|
||||||
async sendTextGet(@Query() query: MessageTextQuery) {
|
async sendTextGet(@Query() query: MessageTextQuery) {
|
||||||
const whatsapp = await this.manager.getWorkingSession(query.session);
|
const whatsapp = await this.manager.getWorkingSession(query.session);
|
||||||
const msg = new MessageTextRequest();
|
const msg = new MessageTextRequest();
|
||||||
@@ -276,6 +303,7 @@ export class ChattingController {
|
|||||||
description: 'DEPRECATED. Use "GET /api/chats/{id}/messages" instead',
|
description: 'DEPRECATED. Use "GET /api/chats/{id}/messages" instead',
|
||||||
deprecated: true,
|
deprecated: true,
|
||||||
})
|
})
|
||||||
|
@CheckPolicies(CanSession(Action.Use, FromQuery('session')))
|
||||||
@UsePipes(new ValidationPipe({ transform: true, whitelist: true }))
|
@UsePipes(new ValidationPipe({ transform: true, whitelist: true }))
|
||||||
async getMessages(
|
async getMessages(
|
||||||
@Query() query: GetMessageQuery,
|
@Query() query: GetMessageQuery,
|
||||||
@@ -292,6 +320,7 @@ export class ChattingController {
|
|||||||
description: 'DEPRECATED. Use "POST /contacts/check-exists" instead',
|
description: 'DEPRECATED. Use "POST /contacts/check-exists" instead',
|
||||||
deprecated: true,
|
deprecated: true,
|
||||||
})
|
})
|
||||||
|
@CheckPolicies(CanSession(Action.Use, FromQuery('session')))
|
||||||
async DEPRECATED_checkNumberStatus(
|
async DEPRECATED_checkNumberStatus(
|
||||||
@Query() request: CheckNumberStatusQuery,
|
@Query() request: CheckNumberStatusQuery,
|
||||||
): Promise<WANumberExistResult> {
|
): Promise<WANumberExistResult> {
|
||||||
@@ -305,6 +334,7 @@ export class ChattingController {
|
|||||||
'DEPRECATED - you can set "reply_to" field when sending text, image, etc',
|
'DEPRECATED - you can set "reply_to" field when sending text, image, etc',
|
||||||
deprecated: true,
|
deprecated: true,
|
||||||
})
|
})
|
||||||
|
@CheckPolicies(CanSession(Action.Use, FromBody('session')))
|
||||||
async reply(@Body() request: MessageReplyRequest) {
|
async reply(@Body() request: MessageReplyRequest) {
|
||||||
const whatsapp = await this.manager.getWorkingSession(request.session);
|
const whatsapp = await this.manager.getWorkingSession(request.session);
|
||||||
return whatsapp.reply(request);
|
return whatsapp.reply(request);
|
||||||
@@ -312,6 +342,7 @@ export class ChattingController {
|
|||||||
|
|
||||||
@Post('/sendLinkPreview')
|
@Post('/sendLinkPreview')
|
||||||
@ApiOperation({ deprecated: true })
|
@ApiOperation({ deprecated: true })
|
||||||
|
@CheckPolicies(CanSession(Action.Use, FromBody('session')))
|
||||||
async sendLinkPreview_DEPRECATED(@Body() request: MessageLinkPreviewRequest) {
|
async sendLinkPreview_DEPRECATED(@Body() request: MessageLinkPreviewRequest) {
|
||||||
const whatsapp = await this.manager.getWorkingSession(request.session);
|
const whatsapp = await this.manager.getWorkingSession(request.session);
|
||||||
return whatsapp.sendLinkPreview(request);
|
return whatsapp.sendLinkPreview(request);
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import {
|
|||||||
Get,
|
Get,
|
||||||
Post,
|
Post,
|
||||||
Query,
|
Query,
|
||||||
|
UseGuards,
|
||||||
UsePipes,
|
UsePipes,
|
||||||
ValidationPipe,
|
ValidationPipe,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
@@ -21,15 +22,22 @@ import {
|
|||||||
ContactRequest,
|
ContactRequest,
|
||||||
ContactsPaginationParams,
|
ContactsPaginationParams,
|
||||||
} from '../structures/contacts.dto';
|
} from '../structures/contacts.dto';
|
||||||
|
import { PoliciesGuard } from '@waha/core/auth/policies.guard';
|
||||||
|
import { CheckPolicies } from '@waha/core/auth/policies.decorator';
|
||||||
|
import { CanSession, FromBody, FromQuery } from '@waha/core/auth/policies';
|
||||||
|
|
||||||
|
import { Action } from '@waha/core/auth/casl.types';
|
||||||
|
|
||||||
@ApiSecurity('api_key')
|
@ApiSecurity('api_key')
|
||||||
@Controller('api/contacts')
|
@Controller('api/contacts')
|
||||||
@ApiTags('👤 Contacts')
|
@ApiTags('👤 Contacts')
|
||||||
|
@UseGuards(PoliciesGuard)
|
||||||
export class ContactsController {
|
export class ContactsController {
|
||||||
constructor(private manager: SessionManager) {}
|
constructor(private manager: SessionManager) {}
|
||||||
|
|
||||||
@Get('/all')
|
@Get('/all')
|
||||||
@ApiOperation({ summary: 'Get all contacts' })
|
@ApiOperation({ summary: 'Get all contacts' })
|
||||||
|
@CheckPolicies(CanSession(Action.Use, FromQuery('session')))
|
||||||
@UsePipes(new ValidationPipe({ transform: true, whitelist: true }))
|
@UsePipes(new ValidationPipe({ transform: true, whitelist: true }))
|
||||||
async getAll(
|
async getAll(
|
||||||
@Query() query: SessionQuery,
|
@Query() query: SessionQuery,
|
||||||
@@ -45,6 +53,7 @@ export class ContactsController {
|
|||||||
description:
|
description:
|
||||||
'The method always return result, even if the phone number is not registered in WhatsApp. For that - use /contacts/check-exists endpoint below.',
|
'The method always return result, even if the phone number is not registered in WhatsApp. For that - use /contacts/check-exists endpoint below.',
|
||||||
})
|
})
|
||||||
|
@CheckPolicies(CanSession(Action.Use, FromQuery('session')))
|
||||||
async get(@Query() query: ContactQuery) {
|
async get(@Query() query: ContactQuery) {
|
||||||
const whatsapp = await this.manager.getWorkingSession(query.session);
|
const whatsapp = await this.manager.getWorkingSession(query.session);
|
||||||
return whatsapp.getContact(query);
|
return whatsapp.getContact(query);
|
||||||
@@ -52,6 +61,7 @@ export class ContactsController {
|
|||||||
|
|
||||||
@Get('/check-exists')
|
@Get('/check-exists')
|
||||||
@ApiOperation({ summary: 'Check phone number is registered in WhatsApp.' })
|
@ApiOperation({ summary: 'Check phone number is registered in WhatsApp.' })
|
||||||
|
@CheckPolicies(CanSession(Action.Use, FromQuery('session')))
|
||||||
async checkExists(
|
async checkExists(
|
||||||
@Query() request: CheckNumberStatusQuery,
|
@Query() request: CheckNumberStatusQuery,
|
||||||
): Promise<WANumberExistResult> {
|
): Promise<WANumberExistResult> {
|
||||||
@@ -65,6 +75,7 @@ export class ContactsController {
|
|||||||
description:
|
description:
|
||||||
'Returns null if you do not have permission to read their status.',
|
'Returns null if you do not have permission to read their status.',
|
||||||
})
|
})
|
||||||
|
@CheckPolicies(CanSession(Action.Use, FromQuery('session')))
|
||||||
async getAbout(@Query() query: ContactQuery) {
|
async getAbout(@Query() query: ContactQuery) {
|
||||||
const whatsapp = await this.manager.getWorkingSession(query.session);
|
const whatsapp = await this.manager.getWorkingSession(query.session);
|
||||||
return whatsapp.getContactAbout(query);
|
return whatsapp.getContactAbout(query);
|
||||||
@@ -76,6 +87,7 @@ export class ContactsController {
|
|||||||
description:
|
description:
|
||||||
'If privacy settings do not allow to get the picture, the method will return null.',
|
'If privacy settings do not allow to get the picture, the method will return null.',
|
||||||
})
|
})
|
||||||
|
@CheckPolicies(CanSession(Action.Use, FromQuery('session')))
|
||||||
@UsePipes(new ValidationPipe({ transform: true, whitelist: true }))
|
@UsePipes(new ValidationPipe({ transform: true, whitelist: true }))
|
||||||
async getProfilePicture(@Query() query: ContactProfilePictureQuery) {
|
async getProfilePicture(@Query() query: ContactProfilePictureQuery) {
|
||||||
const whatsapp = await this.manager.getWorkingSession(query.session);
|
const whatsapp = await this.manager.getWorkingSession(query.session);
|
||||||
@@ -88,6 +100,7 @@ export class ContactsController {
|
|||||||
|
|
||||||
@Post('/block')
|
@Post('/block')
|
||||||
@ApiOperation({ summary: 'Block contact' })
|
@ApiOperation({ summary: 'Block contact' })
|
||||||
|
@CheckPolicies(CanSession(Action.Use, FromBody('session')))
|
||||||
async block(@Body() request: ContactRequest) {
|
async block(@Body() request: ContactRequest) {
|
||||||
const whatsapp = await this.manager.getWorkingSession(request.session);
|
const whatsapp = await this.manager.getWorkingSession(request.session);
|
||||||
return whatsapp.blockContact(request);
|
return whatsapp.blockContact(request);
|
||||||
@@ -95,6 +108,7 @@ export class ContactsController {
|
|||||||
|
|
||||||
@Post('/unblock')
|
@Post('/unblock')
|
||||||
@ApiOperation({ summary: 'Unblock contact' })
|
@ApiOperation({ summary: 'Unblock contact' })
|
||||||
|
@CheckPolicies(CanSession(Action.Use, FromBody('session')))
|
||||||
async unblock(@Body() request: ContactRequest) {
|
async unblock(@Body() request: ContactRequest) {
|
||||||
const whatsapp = await this.manager.getWorkingSession(request.session);
|
const whatsapp = await this.manager.getWorkingSession(request.session);
|
||||||
return whatsapp.unblockContact(request);
|
return whatsapp.unblockContact(request);
|
||||||
|
|||||||
@@ -0,0 +1,73 @@
|
|||||||
|
import {
|
||||||
|
Body,
|
||||||
|
Controller,
|
||||||
|
Get,
|
||||||
|
Param,
|
||||||
|
Put,
|
||||||
|
UseGuards,
|
||||||
|
UsePipes,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { ApiOperation, ApiParam, ApiSecurity, ApiTags } from '@nestjs/swagger';
|
||||||
|
import { PoliciesGuard } from '@waha/core/auth/policies.guard';
|
||||||
|
import { CheckPolicies } from '@waha/core/auth/policies.decorator';
|
||||||
|
import { CanSession, FromParam } from '@waha/core/auth/policies';
|
||||||
|
import { WhatsappSession } from '@waha/core/abc/session.abc';
|
||||||
|
import { ChatIdApiParam } from '@waha/nestjs/params/ChatIdApiParam';
|
||||||
|
import {
|
||||||
|
SessionApiParam,
|
||||||
|
WorkingSessionParam,
|
||||||
|
} from '@waha/nestjs/params/SessionApiParam';
|
||||||
|
import { WAHAValidationPipe } from '@waha/nestjs/pipes/WAHAValidationPipe';
|
||||||
|
|
||||||
|
import { SessionManager } from '../core/abc/manager.abc';
|
||||||
|
import { Result } from '../structures/base.dto';
|
||||||
|
import { ContactUpdateBody } from '../structures/contacts.dto';
|
||||||
|
import { Action } from '@waha/core/auth/casl.types';
|
||||||
|
|
||||||
|
@ApiSecurity('api_key')
|
||||||
|
@Controller('api/:session/contacts')
|
||||||
|
@ApiTags('👤 Contacts')
|
||||||
|
@UseGuards(PoliciesGuard)
|
||||||
|
@CheckPolicies(CanSession(Action.Use, FromParam('session')))
|
||||||
|
export class ContactsSessionController {
|
||||||
|
constructor(private manager: SessionManager) {}
|
||||||
|
|
||||||
|
@Get('/:id')
|
||||||
|
@SessionApiParam
|
||||||
|
@ApiParam({
|
||||||
|
name: 'id',
|
||||||
|
required: true,
|
||||||
|
type: 'string',
|
||||||
|
description: 'Contact ID',
|
||||||
|
example: '123456789@c.us',
|
||||||
|
})
|
||||||
|
@ApiOperation({
|
||||||
|
summary: 'Get contact basic info',
|
||||||
|
description:
|
||||||
|
'The method always return result, even if the phone number is not registered in WhatsApp. For that - use /contacts/check-exists endpoint below.',
|
||||||
|
})
|
||||||
|
async get(
|
||||||
|
@WorkingSessionParam session: WhatsappSession,
|
||||||
|
@Param('id') id: string,
|
||||||
|
) {
|
||||||
|
return session.getContact({ session: session.name, contactId: id });
|
||||||
|
}
|
||||||
|
|
||||||
|
@Put('/:chatId')
|
||||||
|
@SessionApiParam
|
||||||
|
@ChatIdApiParam
|
||||||
|
@ApiOperation({
|
||||||
|
summary: 'Create or update contact',
|
||||||
|
description:
|
||||||
|
'Create or update contact on the phone address book. May not work if you have installed many WhatsApp apps on the same phone',
|
||||||
|
})
|
||||||
|
@UsePipes(new WAHAValidationPipe())
|
||||||
|
async put(
|
||||||
|
@WorkingSessionParam session: WhatsappSession,
|
||||||
|
@Param('chatId') chatId: string,
|
||||||
|
@Body() body: ContactUpdateBody,
|
||||||
|
): Promise<Result> {
|
||||||
|
await session.upsertContact(chatId, body);
|
||||||
|
return { success: true };
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ import {
|
|||||||
Controller,
|
Controller,
|
||||||
Param,
|
Param,
|
||||||
Post,
|
Post,
|
||||||
|
UseGuards,
|
||||||
UsePipes,
|
UsePipes,
|
||||||
ValidationPipe,
|
ValidationPipe,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
@@ -19,10 +20,17 @@ import {
|
|||||||
EventMessageRequest,
|
EventMessageRequest,
|
||||||
} from '../structures/events.dto';
|
} from '../structures/events.dto';
|
||||||
import { WAMessage } from '../structures/responses.dto';
|
import { WAMessage } from '../structures/responses.dto';
|
||||||
|
import { PoliciesGuard } from '@waha/core/auth/policies.guard';
|
||||||
|
import { CheckPolicies } from '@waha/core/auth/policies.decorator';
|
||||||
|
import { CanSession, FromParam } from '@waha/core/auth/policies';
|
||||||
|
|
||||||
|
import { Action } from '@waha/core/auth/casl.types';
|
||||||
|
|
||||||
@ApiSecurity('api_key')
|
@ApiSecurity('api_key')
|
||||||
@Controller('api/:session/events')
|
@Controller('api/:session/events')
|
||||||
@ApiTags('📅 Events')
|
@ApiTags('📅 Events')
|
||||||
|
@UseGuards(PoliciesGuard)
|
||||||
|
@CheckPolicies(CanSession(Action.Use, FromParam('session')))
|
||||||
export class EventsController {
|
export class EventsController {
|
||||||
constructor(private manager: SessionManager) {}
|
constructor(private manager: SessionManager) {}
|
||||||
|
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import {
|
|||||||
Post,
|
Post,
|
||||||
Put,
|
Put,
|
||||||
Query,
|
Query,
|
||||||
|
UseGuards,
|
||||||
UsePipes,
|
UsePipes,
|
||||||
ValidationPipe,
|
ValidationPipe,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
@@ -40,10 +41,17 @@ import {
|
|||||||
SettingsSecurityChangeInfo,
|
SettingsSecurityChangeInfo,
|
||||||
SubjectRequest,
|
SubjectRequest,
|
||||||
} from '../structures/groups.dto';
|
} from '../structures/groups.dto';
|
||||||
|
import { PoliciesGuard } from '@waha/core/auth/policies.guard';
|
||||||
|
import { CheckPolicies } from '@waha/core/auth/policies.decorator';
|
||||||
|
import { CanSession, FromParam } from '@waha/core/auth/policies';
|
||||||
|
|
||||||
|
import { Action } from '@waha/core/auth/casl.types';
|
||||||
|
|
||||||
@ApiSecurity('api_key')
|
@ApiSecurity('api_key')
|
||||||
@Controller('api/:session/groups')
|
@Controller('api/:session/groups')
|
||||||
@ApiTags('👥 Groups')
|
@ApiTags('👥 Groups')
|
||||||
|
@UseGuards(PoliciesGuard)
|
||||||
|
@CheckPolicies(CanSession(Action.Use, FromParam('session')))
|
||||||
export class GroupsController {
|
export class GroupsController {
|
||||||
constructor(private manager: SessionManager) {}
|
constructor(private manager: SessionManager) {}
|
||||||
|
|
||||||
|
|||||||
@@ -1,12 +1,19 @@
|
|||||||
import { Controller, Get } from '@nestjs/common';
|
import { Controller, Get, UseGuards } from '@nestjs/common';
|
||||||
import { ApiOperation, ApiSecurity, ApiTags } from '@nestjs/swagger';
|
import { ApiOperation, ApiSecurity, ApiTags } from '@nestjs/swagger';
|
||||||
import { HealthCheck } from '@nestjs/terminus';
|
import { HealthCheck } from '@nestjs/terminus';
|
||||||
|
|
||||||
import { WAHAHealthCheckService } from '../core/abc/WAHAHealthCheckService';
|
import { WAHAHealthCheckService } from '../core/abc/WAHAHealthCheckService';
|
||||||
|
import { PoliciesGuard } from '@waha/core/auth/policies.guard';
|
||||||
|
import { CheckPolicies } from '@waha/core/auth/policies.decorator';
|
||||||
|
import { CanServer } from '@waha/core/auth/policies';
|
||||||
|
|
||||||
|
import { Action } from '@waha/core/auth/casl.types';
|
||||||
|
|
||||||
@ApiSecurity('api_key')
|
@ApiSecurity('api_key')
|
||||||
@Controller('health')
|
@Controller('health')
|
||||||
@ApiTags('🔍 Observability')
|
@ApiTags('🔍 Observability')
|
||||||
|
@UseGuards(PoliciesGuard)
|
||||||
|
@CheckPolicies(CanServer(Action.Manage))
|
||||||
export class HealthController {
|
export class HealthController {
|
||||||
constructor(private wahaHealth: WAHAHealthCheckService) {}
|
constructor(private wahaHealth: WAHAHealthCheckService) {}
|
||||||
|
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import {
|
|||||||
Post,
|
Post,
|
||||||
Put,
|
Put,
|
||||||
UnprocessableEntityException,
|
UnprocessableEntityException,
|
||||||
|
UseGuards,
|
||||||
UsePipes,
|
UsePipes,
|
||||||
ValidationPipe,
|
ValidationPipe,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
@@ -26,10 +27,17 @@ import {
|
|||||||
import * as lodash from 'lodash';
|
import * as lodash from 'lodash';
|
||||||
|
|
||||||
import { SessionManager } from '../core/abc/manager.abc';
|
import { SessionManager } from '../core/abc/manager.abc';
|
||||||
|
import { PoliciesGuard } from '@waha/core/auth/policies.guard';
|
||||||
|
import { CheckPolicies } from '@waha/core/auth/policies.decorator';
|
||||||
|
import { CanSession, FromParam } from '@waha/core/auth/policies';
|
||||||
|
|
||||||
|
import { Action } from '@waha/core/auth/casl.types';
|
||||||
|
|
||||||
@ApiSecurity('api_key')
|
@ApiSecurity('api_key')
|
||||||
@Controller('api/:session/labels')
|
@Controller('api/:session/labels')
|
||||||
@ApiTags('🏷️ Labels')
|
@ApiTags('🏷️ Labels')
|
||||||
|
@UseGuards(PoliciesGuard)
|
||||||
|
@CheckPolicies(CanSession(Action.Use, FromParam('session')))
|
||||||
export class LabelsController {
|
export class LabelsController {
|
||||||
constructor(private manager: SessionManager) {}
|
constructor(private manager: SessionManager) {}
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import {
|
|||||||
Param,
|
Param,
|
||||||
Query,
|
Query,
|
||||||
UnprocessableEntityException,
|
UnprocessableEntityException,
|
||||||
|
UseGuards,
|
||||||
UsePipes,
|
UsePipes,
|
||||||
ValidationPipe,
|
ValidationPipe,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
@@ -22,10 +23,17 @@ import { PaginationParams, SortOrder } from '@waha/structures/pagination.dto';
|
|||||||
|
|
||||||
import { SessionManager } from '../core/abc/manager.abc';
|
import { SessionManager } from '../core/abc/manager.abc';
|
||||||
import { isLidUser } from '@waha/core/utils/jids';
|
import { isLidUser } from '@waha/core/utils/jids';
|
||||||
|
import { PoliciesGuard } from '@waha/core/auth/policies.guard';
|
||||||
|
import { CheckPolicies } from '@waha/core/auth/policies.decorator';
|
||||||
|
import { CanSession, FromParam } from '@waha/core/auth/policies';
|
||||||
|
|
||||||
|
import { Action } from '@waha/core/auth/casl.types';
|
||||||
|
|
||||||
@ApiSecurity('api_key')
|
@ApiSecurity('api_key')
|
||||||
@Controller('api/:session/lids')
|
@Controller('api/:session/lids')
|
||||||
@ApiTags('👤 Contacts')
|
@ApiTags('👤 Contacts')
|
||||||
|
@UseGuards(PoliciesGuard)
|
||||||
|
@CheckPolicies(CanSession(Action.Use, FromParam('session')))
|
||||||
export class LidsController {
|
export class LidsController {
|
||||||
constructor(private manager: SessionManager) {}
|
constructor(private manager: SessionManager) {}
|
||||||
|
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import {
|
|||||||
Controller,
|
Controller,
|
||||||
Post,
|
Post,
|
||||||
UnprocessableEntityException,
|
UnprocessableEntityException,
|
||||||
|
UseGuards,
|
||||||
UseInterceptors,
|
UseInterceptors,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { ApiOperation, ApiSecurity, ApiTags } from '@nestjs/swagger';
|
import { ApiOperation, ApiSecurity, ApiTags } from '@nestjs/swagger';
|
||||||
@@ -21,10 +22,17 @@ import {
|
|||||||
|
|
||||||
import { WhatsappSession } from '../core/abc/session.abc';
|
import { WhatsappSession } from '../core/abc/session.abc';
|
||||||
import { BufferResponseInterceptor } from '../nestjs/BufferResponseInterceptor';
|
import { BufferResponseInterceptor } from '../nestjs/BufferResponseInterceptor';
|
||||||
|
import { PoliciesGuard } from '@waha/core/auth/policies.guard';
|
||||||
|
import { CheckPolicies } from '@waha/core/auth/policies.decorator';
|
||||||
|
import { CanSession, FromParam } from '@waha/core/auth/policies';
|
||||||
|
|
||||||
|
import { Action } from '@waha/core/auth/casl.types';
|
||||||
|
|
||||||
@ApiSecurity('api_key')
|
@ApiSecurity('api_key')
|
||||||
@Controller('api/:session/media')
|
@Controller('api/:session/media')
|
||||||
@ApiTags('🖼️ Media')
|
@ApiTags('🖼️ Media')
|
||||||
|
@UseGuards(PoliciesGuard)
|
||||||
|
@CheckPolicies(CanSession(Action.Use, FromParam('session')))
|
||||||
class MediaController {
|
class MediaController {
|
||||||
constructor(private manager: SessionManager) {}
|
constructor(private manager: SessionManager) {}
|
||||||
|
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import {
|
|||||||
Get,
|
Get,
|
||||||
Param,
|
Param,
|
||||||
Post,
|
Post,
|
||||||
|
UseGuards,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { ApiOperation, ApiSecurity, ApiTags } from '@nestjs/swagger';
|
import { ApiOperation, ApiSecurity, ApiTags } from '@nestjs/swagger';
|
||||||
import { ChatIdApiParam } from '@waha/nestjs/params/ChatIdApiParam';
|
import { ChatIdApiParam } from '@waha/nestjs/params/ChatIdApiParam';
|
||||||
@@ -20,10 +21,17 @@ import {
|
|||||||
WAHAChatPresences,
|
WAHAChatPresences,
|
||||||
WAHASessionPresence,
|
WAHASessionPresence,
|
||||||
} from '../structures/presence.dto';
|
} from '../structures/presence.dto';
|
||||||
|
import { PoliciesGuard } from '@waha/core/auth/policies.guard';
|
||||||
|
import { CheckPolicies } from '@waha/core/auth/policies.decorator';
|
||||||
|
import { CanSession, FromParam } from '@waha/core/auth/policies';
|
||||||
|
|
||||||
|
import { Action } from '@waha/core/auth/casl.types';
|
||||||
|
|
||||||
@ApiSecurity('api_key')
|
@ApiSecurity('api_key')
|
||||||
@Controller('api/:session/presence')
|
@Controller('api/:session/presence')
|
||||||
@ApiTags('✅ Presence')
|
@ApiTags('✅ Presence')
|
||||||
|
@UseGuards(PoliciesGuard)
|
||||||
|
@CheckPolicies(CanSession(Action.Use, FromParam('session')))
|
||||||
export class PresenceController {
|
export class PresenceController {
|
||||||
constructor(private manager: SessionManager) {}
|
constructor(private manager: SessionManager) {}
|
||||||
|
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import {
|
|||||||
Get,
|
Get,
|
||||||
Put,
|
Put,
|
||||||
UnprocessableEntityException,
|
UnprocessableEntityException,
|
||||||
|
UseGuards,
|
||||||
UsePipes,
|
UsePipes,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { ApiOperation, ApiSecurity, ApiTags } from '@nestjs/swagger';
|
import { ApiOperation, ApiSecurity, ApiTags } from '@nestjs/swagger';
|
||||||
@@ -22,10 +23,17 @@ import {
|
|||||||
ProfilePictureRequest,
|
ProfilePictureRequest,
|
||||||
ProfileStatusRequest,
|
ProfileStatusRequest,
|
||||||
} from '@waha/structures/profile.dto';
|
} from '@waha/structures/profile.dto';
|
||||||
|
import { PoliciesGuard } from '@waha/core/auth/policies.guard';
|
||||||
|
import { CheckPolicies } from '@waha/core/auth/policies.decorator';
|
||||||
|
import { CanSession, FromParam } from '@waha/core/auth/policies';
|
||||||
|
|
||||||
|
import { Action } from '@waha/core/auth/casl.types';
|
||||||
|
|
||||||
@ApiSecurity('api_key')
|
@ApiSecurity('api_key')
|
||||||
@Controller('api/:session/profile')
|
@Controller('api/:session/profile')
|
||||||
@ApiTags('🆔 Profile')
|
@ApiTags('🆔 Profile')
|
||||||
|
@UseGuards(PoliciesGuard)
|
||||||
|
@CheckPolicies(CanSession(Action.Use, FromParam('session')))
|
||||||
export class ProfileController {
|
export class ProfileController {
|
||||||
constructor(private manager: SessionManager) {}
|
constructor(private manager: SessionManager) {}
|
||||||
|
|
||||||
|
|||||||
@@ -4,23 +4,35 @@ import {
|
|||||||
Query,
|
Query,
|
||||||
Res,
|
Res,
|
||||||
StreamableFile,
|
StreamableFile,
|
||||||
|
UseGuards,
|
||||||
UseInterceptors,
|
UseInterceptors,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { ApiSecurity, ApiTags } from '@nestjs/swagger';
|
import { ApiOperation, ApiSecurity, ApiTags } from '@nestjs/swagger';
|
||||||
import { ApiFileAcceptHeader } from '@waha/nestjs/ApiFileAcceptHeader';
|
import { ApiFileAcceptHeader } from '@waha/nestjs/ApiFileAcceptHeader';
|
||||||
import { Response } from 'express';
|
import { Response } from 'express';
|
||||||
|
|
||||||
import { SessionManager } from '../core/abc/manager.abc';
|
import { SessionManager } from '../core/abc/manager.abc';
|
||||||
import { BufferResponseInterceptor } from '../nestjs/BufferResponseInterceptor';
|
import { BufferResponseInterceptor } from '../nestjs/BufferResponseInterceptor';
|
||||||
import { SessionQuery } from '../structures/base.dto';
|
import { SessionQuery } from '../structures/base.dto';
|
||||||
|
import { PoliciesGuard } from '@waha/core/auth/policies.guard';
|
||||||
|
import { CheckPolicies } from '@waha/core/auth/policies.decorator';
|
||||||
|
import { CanSession, FromQuery } from '@waha/core/auth/policies';
|
||||||
|
|
||||||
|
import { Action } from '@waha/core/auth/casl.types';
|
||||||
|
|
||||||
@ApiSecurity('api_key')
|
@ApiSecurity('api_key')
|
||||||
@Controller('api')
|
@Controller('api')
|
||||||
@ApiTags('🖼️ Screenshot')
|
@ApiTags('📱 Pairing')
|
||||||
|
@UseGuards(PoliciesGuard)
|
||||||
|
@CheckPolicies(CanSession(Action.Use, FromQuery('session')))
|
||||||
export class ScreenshotController {
|
export class ScreenshotController {
|
||||||
constructor(private manager: SessionManager) {}
|
constructor(private manager: SessionManager) {}
|
||||||
|
|
||||||
@Get('/screenshot')
|
@Get('/screenshot')
|
||||||
|
@ApiOperation({
|
||||||
|
summary:
|
||||||
|
'Get a screenshot of the current WhatsApp session (**WEBJS/WPP** only)',
|
||||||
|
})
|
||||||
@UseInterceptors(new BufferResponseInterceptor('image/jpeg'))
|
@UseInterceptors(new BufferResponseInterceptor('image/jpeg'))
|
||||||
@ApiFileAcceptHeader('image/jpeg')
|
@ApiFileAcceptHeader('image/jpeg')
|
||||||
async screenshot(
|
async screenshot(
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import {
|
|||||||
Logger,
|
Logger,
|
||||||
Post,
|
Post,
|
||||||
Query,
|
Query,
|
||||||
|
UseGuards,
|
||||||
UsePipes,
|
UsePipes,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { ApiOperation, ApiSecurity, ApiTags } from '@nestjs/swagger';
|
import { ApiOperation, ApiSecurity, ApiTags } from '@nestjs/swagger';
|
||||||
@@ -22,10 +23,16 @@ import {
|
|||||||
import { sleep } from '@waha/utils/promiseTimeout';
|
import { sleep } from '@waha/utils/promiseTimeout';
|
||||||
import { VERSION } from '@waha/version';
|
import { VERSION } from '@waha/version';
|
||||||
import * as lodash from 'lodash';
|
import * as lodash from 'lodash';
|
||||||
|
import { PoliciesGuard } from '@waha/core/auth/policies.guard';
|
||||||
|
import { CheckPolicies } from '@waha/core/auth/policies.decorator';
|
||||||
|
import { CanServer } from '@waha/core/auth/policies';
|
||||||
|
|
||||||
|
import { Action } from '@waha/core/auth/casl.types';
|
||||||
|
|
||||||
@ApiSecurity('api_key')
|
@ApiSecurity('api_key')
|
||||||
@Controller('api/server')
|
@Controller('api/server')
|
||||||
@ApiTags('🔍 Observability')
|
@ApiTags('🔍 Observability')
|
||||||
|
@UseGuards(PoliciesGuard)
|
||||||
export class ServerController {
|
export class ServerController {
|
||||||
private logger: Logger;
|
private logger: Logger;
|
||||||
|
|
||||||
@@ -35,12 +42,14 @@ export class ServerController {
|
|||||||
|
|
||||||
@Get('version')
|
@Get('version')
|
||||||
@ApiOperation({ summary: 'Get the version of the server' })
|
@ApiOperation({ summary: 'Get the version of the server' })
|
||||||
|
@CheckPolicies(CanServer(Action.Read))
|
||||||
get(): WAHAEnvironment {
|
get(): WAHAEnvironment {
|
||||||
return VERSION;
|
return VERSION;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get('environment')
|
@Get('environment')
|
||||||
@ApiOperation({ summary: 'Get the server environment' })
|
@ApiOperation({ summary: 'Get the server environment' })
|
||||||
|
@CheckPolicies(CanServer(Action.Manage))
|
||||||
environment(
|
environment(
|
||||||
@Query(new WAHAValidationPipe()) query: EnvironmentQuery,
|
@Query(new WAHAValidationPipe()) query: EnvironmentQuery,
|
||||||
// eslint-disable-next-line @typescript-eslint/ban-types
|
// eslint-disable-next-line @typescript-eslint/ban-types
|
||||||
@@ -67,6 +76,7 @@ export class ServerController {
|
|||||||
|
|
||||||
@Get('status')
|
@Get('status')
|
||||||
@ApiOperation({ summary: 'Get the server status' })
|
@ApiOperation({ summary: 'Get the server status' })
|
||||||
|
@CheckPolicies(CanServer(Action.Read))
|
||||||
async status(): Promise<ServerStatusResponse> {
|
async status(): Promise<ServerStatusResponse> {
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
const uptime = Math.floor(process.uptime() * 1000);
|
const uptime = Math.floor(process.uptime() * 1000);
|
||||||
@@ -87,6 +97,7 @@ export class ServerController {
|
|||||||
"If you're using docker, after calling this endpoint Docker will start a new container, " +
|
"If you're using docker, after calling this endpoint Docker will start a new container, " +
|
||||||
'so you can use this endpoint to restart the server',
|
'so you can use this endpoint to restart the server',
|
||||||
})
|
})
|
||||||
|
@CheckPolicies(CanServer(Action.Manage))
|
||||||
@UsePipes(new WAHAValidationPipe())
|
@UsePipes(new WAHAValidationPipe())
|
||||||
async stop(@Body() request: StopRequest): Promise<StopResponse> {
|
async stop(@Body() request: StopRequest): Promise<StopResponse> {
|
||||||
const timeout = 1_000;
|
const timeout = 1_000;
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import {
|
|||||||
NotFoundException,
|
NotFoundException,
|
||||||
Query,
|
Query,
|
||||||
StreamableFile,
|
StreamableFile,
|
||||||
|
UseGuards,
|
||||||
UsePipes,
|
UsePipes,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { ApiOperation, ApiSecurity, ApiTags } from '@nestjs/swagger';
|
import { ApiOperation, ApiSecurity, ApiTags } from '@nestjs/swagger';
|
||||||
@@ -25,10 +26,17 @@ import {
|
|||||||
CpuProfileQuery,
|
CpuProfileQuery,
|
||||||
} from '@waha/structures/server.debug.dto';
|
} from '@waha/structures/server.debug.dto';
|
||||||
import { createReadStream } from 'fs';
|
import { createReadStream } from 'fs';
|
||||||
|
import { PoliciesGuard } from '@waha/core/auth/policies.guard';
|
||||||
|
import { CheckPolicies } from '@waha/core/auth/policies.decorator';
|
||||||
|
import { CanServer } from '@waha/core/auth/policies';
|
||||||
|
|
||||||
|
import { Action } from '@waha/core/auth/casl.types';
|
||||||
|
|
||||||
@ApiSecurity('api_key')
|
@ApiSecurity('api_key')
|
||||||
@Controller('api/server/debug')
|
@Controller('api/server/debug')
|
||||||
@ApiTags('🔍 Observability')
|
@ApiTags('🔍 Observability')
|
||||||
|
@UseGuards(PoliciesGuard)
|
||||||
|
@CheckPolicies(CanServer(Action.Manage))
|
||||||
export class ServerDebugController {
|
export class ServerDebugController {
|
||||||
private logger: Logger;
|
private logger: Logger;
|
||||||
private readonly enabled: boolean;
|
private readonly enabled: boolean;
|
||||||
|
|||||||
@@ -9,10 +9,18 @@ import {
|
|||||||
Post,
|
Post,
|
||||||
Put,
|
Put,
|
||||||
Query,
|
Query,
|
||||||
|
Req,
|
||||||
|
UseGuards,
|
||||||
UsePipes,
|
UsePipes,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { UnprocessableEntityException } from '@nestjs/common/exceptions/unprocessable-entity.exception';
|
import { UnprocessableEntityException } from '@nestjs/common/exceptions/unprocessable-entity.exception';
|
||||||
import { ApiBody, ApiOperation, ApiSecurity, ApiTags } from '@nestjs/swagger';
|
import {
|
||||||
|
ApiBody,
|
||||||
|
ApiOAuth2,
|
||||||
|
ApiOperation,
|
||||||
|
ApiSecurity,
|
||||||
|
ApiTags,
|
||||||
|
} from '@nestjs/swagger';
|
||||||
import {
|
import {
|
||||||
SessionApiParam,
|
SessionApiParam,
|
||||||
SessionParam,
|
SessionParam,
|
||||||
@@ -34,18 +42,24 @@ import { WhatsappSession } from '../core/abc/session.abc';
|
|||||||
import {
|
import {
|
||||||
ListSessionsQuery,
|
ListSessionsQuery,
|
||||||
MeInfo,
|
MeInfo,
|
||||||
SessionExpand,
|
|
||||||
SessionInfoQuery,
|
|
||||||
SessionCreateRequest,
|
SessionCreateRequest,
|
||||||
SessionDTO,
|
SessionDTO,
|
||||||
|
SessionExpand,
|
||||||
SessionInfo,
|
SessionInfo,
|
||||||
|
SessionInfoQuery,
|
||||||
SessionUpdateRequest,
|
SessionUpdateRequest,
|
||||||
} from '../structures/sessions.dto';
|
} from '../structures/sessions.dto';
|
||||||
import { SessionExamples } from './sessions.examples';
|
import { SessionExamples } from './sessions.examples';
|
||||||
|
import { FilterSessions } from '../core/auth/casl.ability';
|
||||||
|
import { CheckPolicies } from '../core/auth/policies.decorator';
|
||||||
|
import { PoliciesGuard } from '../core/auth/policies.guard';
|
||||||
|
import { CanSession, FromBody, FromParam } from '../core/auth/policies';
|
||||||
|
import { Action } from '@waha/core/auth/casl.types';
|
||||||
|
|
||||||
@ApiSecurity('api_key')
|
@ApiSecurity('api_key')
|
||||||
@Controller('api/sessions')
|
@Controller('api/sessions')
|
||||||
@ApiTags('🖥️ Sessions')
|
@ApiTags('🖥️ Sessions')
|
||||||
|
@UseGuards(PoliciesGuard)
|
||||||
class SessionsController {
|
class SessionsController {
|
||||||
constructor(
|
constructor(
|
||||||
private manager: SessionManager,
|
private manager: SessionManager,
|
||||||
@@ -57,11 +71,19 @@ class SessionsController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Get('/')
|
@Get('/')
|
||||||
@ApiOperation({ summary: 'List all sessions' })
|
@ApiOperation({
|
||||||
|
summary: 'List all sessions',
|
||||||
|
})
|
||||||
|
@CheckPolicies(CanSession(Action.List))
|
||||||
|
@ApiOAuth2(['read:items'])
|
||||||
async list(
|
async list(
|
||||||
@Query(new WAHAValidationPipe()) query: ListSessionsQuery,
|
@Query(new WAHAValidationPipe()) query: ListSessionsQuery,
|
||||||
|
@Req() req,
|
||||||
): Promise<SessionInfo[]> {
|
): Promise<SessionInfo[]> {
|
||||||
const sessions = await this.manager.getSessions(query.all);
|
let sessions = await this.manager.getSessions(query.all);
|
||||||
|
if (!req.user?.isAdmin) {
|
||||||
|
sessions = FilterSessions(req.ability, Action.Read, sessions);
|
||||||
|
}
|
||||||
if (query.expand?.includes(SessionExpand.apps)) {
|
if (query.expand?.includes(SessionExpand.apps)) {
|
||||||
for (const session of sessions) {
|
for (const session of sessions) {
|
||||||
session.apps = await this.appsService.list(this.manager, session.name);
|
session.apps = await this.appsService.list(this.manager, session.name);
|
||||||
@@ -73,6 +95,7 @@ class SessionsController {
|
|||||||
@Get('/:session')
|
@Get('/:session')
|
||||||
@ApiOperation({ summary: 'Get session information' })
|
@ApiOperation({ summary: 'Get session information' })
|
||||||
@SessionApiParam
|
@SessionApiParam
|
||||||
|
@CheckPolicies(CanSession(Action.Use, FromParam('session')))
|
||||||
@UsePipes(new WAHAValidationPipe())
|
@UsePipes(new WAHAValidationPipe())
|
||||||
async get(
|
async get(
|
||||||
@Param('session') name: string,
|
@Param('session') name: string,
|
||||||
@@ -91,6 +114,7 @@ class SessionsController {
|
|||||||
@Get(':session/me')
|
@Get(':session/me')
|
||||||
@SessionApiParam
|
@SessionApiParam
|
||||||
@ApiOperation({ summary: 'Get information about the authenticated account' })
|
@ApiOperation({ summary: 'Get information about the authenticated account' })
|
||||||
|
@CheckPolicies(CanSession(Action.Use, FromParam('session')))
|
||||||
getMe(@SessionParam session: WhatsappSession): MeInfo | null {
|
getMe(@SessionParam session: WhatsappSession): MeInfo | null {
|
||||||
return session.getSessionMeInfo();
|
return session.getSessionMeInfo();
|
||||||
}
|
}
|
||||||
@@ -102,6 +126,7 @@ class SessionsController {
|
|||||||
'Create session a new session (and start it at the same time if required).',
|
'Create session a new session (and start it at the same time if required).',
|
||||||
})
|
})
|
||||||
@ApiBody({ type: SessionCreateRequest, examples: SessionExamples })
|
@ApiBody({ type: SessionCreateRequest, examples: SessionExamples })
|
||||||
|
@CheckPolicies(CanSession(Action.Create))
|
||||||
@UsePipes(new WAHAValidationPipe())
|
@UsePipes(new WAHAValidationPipe())
|
||||||
async create(@Body() request: SessionCreateRequest): Promise<SessionDTO> {
|
async create(@Body() request: SessionCreateRequest): Promise<SessionDTO> {
|
||||||
const name = request.name || generatePrefixedId('session');
|
const name = request.name || generatePrefixedId('session');
|
||||||
@@ -139,6 +164,7 @@ class SessionsController {
|
|||||||
})
|
})
|
||||||
@SessionApiParam
|
@SessionApiParam
|
||||||
@ApiBody({ type: SessionUpdateRequest, examples: SessionExamples })
|
@ApiBody({ type: SessionUpdateRequest, examples: SessionExamples })
|
||||||
|
@CheckPolicies(CanSession(Action.Use, FromParam('session')))
|
||||||
@UsePipes(new WAHAValidationPipe({ forbidNonWhitelisted: false }))
|
@UsePipes(new WAHAValidationPipe({ forbidNonWhitelisted: false }))
|
||||||
async update(
|
async update(
|
||||||
@Param('session') name: string,
|
@Param('session') name: string,
|
||||||
@@ -177,6 +203,7 @@ class SessionsController {
|
|||||||
description:
|
description:
|
||||||
'Delete the session with the given name. Stop and logout as well. Idempotent operation.',
|
'Delete the session with the given name. Stop and logout as well. Idempotent operation.',
|
||||||
})
|
})
|
||||||
|
@CheckPolicies(CanSession(Action.Delete, FromParam('session')))
|
||||||
@UsePipes(new WAHAValidationPipe())
|
@UsePipes(new WAHAValidationPipe())
|
||||||
async delete(@Param('session') name: string): Promise<void> {
|
async delete(@Param('session') name: string): Promise<void> {
|
||||||
await this.withLock(name, async () => {
|
await this.withLock(name, async () => {
|
||||||
@@ -195,6 +222,7 @@ class SessionsController {
|
|||||||
description:
|
description:
|
||||||
'Start the session with the given name. The session must exist. Idempotent operation.',
|
'Start the session with the given name. The session must exist. Idempotent operation.',
|
||||||
})
|
})
|
||||||
|
@CheckPolicies(CanSession(Action.Use, FromParam('session')))
|
||||||
@UsePipes(new WAHAValidationPipe())
|
@UsePipes(new WAHAValidationPipe())
|
||||||
async start(@Param('session') name: string): Promise<SessionDTO> {
|
async start(@Param('session') name: string): Promise<SessionDTO> {
|
||||||
await this.withLock(name, async () => {
|
await this.withLock(name, async () => {
|
||||||
@@ -214,6 +242,7 @@ class SessionsController {
|
|||||||
summary: 'Stop the session',
|
summary: 'Stop the session',
|
||||||
description: 'Stop the session with the given name. Idempotent operation.',
|
description: 'Stop the session with the given name. Idempotent operation.',
|
||||||
})
|
})
|
||||||
|
@CheckPolicies(CanSession(Action.Use, FromParam('session')))
|
||||||
@UsePipes(new WAHAValidationPipe())
|
@UsePipes(new WAHAValidationPipe())
|
||||||
async stop(@Param('session') name: string): Promise<SessionDTO> {
|
async stop(@Param('session') name: string): Promise<SessionDTO> {
|
||||||
await this.withLock(name, async () => {
|
await this.withLock(name, async () => {
|
||||||
@@ -229,6 +258,7 @@ class SessionsController {
|
|||||||
summary: 'Logout from the session',
|
summary: 'Logout from the session',
|
||||||
description: 'Logout the session, restart a session if it was not STOPPED',
|
description: 'Logout the session, restart a session if it was not STOPPED',
|
||||||
})
|
})
|
||||||
|
@CheckPolicies(CanSession(Action.Use, FromParam('session')))
|
||||||
@UsePipes(new WAHAValidationPipe())
|
@UsePipes(new WAHAValidationPipe())
|
||||||
async logout(@Param('session') name: string): Promise<SessionDTO> {
|
async logout(@Param('session') name: string): Promise<SessionDTO> {
|
||||||
await this.withLock(name, async () => {
|
await this.withLock(name, async () => {
|
||||||
@@ -253,6 +283,7 @@ class SessionsController {
|
|||||||
summary: 'Restart the session',
|
summary: 'Restart the session',
|
||||||
description: 'Restart the session with the given name.',
|
description: 'Restart the session with the given name.',
|
||||||
})
|
})
|
||||||
|
@CheckPolicies(CanSession(Action.Use, FromParam('session')))
|
||||||
@UsePipes(new WAHAValidationPipe())
|
@UsePipes(new WAHAValidationPipe())
|
||||||
async restart(@Param('session') name: string): Promise<SessionDTO> {
|
async restart(@Param('session') name: string): Promise<SessionDTO> {
|
||||||
await this.manager.restart(name);
|
await this.manager.restart(name);
|
||||||
@@ -266,6 +297,7 @@ class SessionsController {
|
|||||||
'Create session (if not exists) or update a config (if exists) and start it.',
|
'Create session (if not exists) or update a config (if exists) and start it.',
|
||||||
deprecated: true,
|
deprecated: true,
|
||||||
})
|
})
|
||||||
|
@CheckPolicies(CanSession(Action.Use, FromBody('name')))
|
||||||
async DEPRACATED_start(
|
async DEPRACATED_start(
|
||||||
@Body() request: SessionStartDeprecatedRequest,
|
@Body() request: SessionStartDeprecatedRequest,
|
||||||
): Promise<SessionDTO> {
|
): Promise<SessionDTO> {
|
||||||
@@ -292,6 +324,7 @@ class SessionsController {
|
|||||||
description: 'Stop session and Logout by default.',
|
description: 'Stop session and Logout by default.',
|
||||||
deprecated: true,
|
deprecated: true,
|
||||||
})
|
})
|
||||||
|
@CheckPolicies(CanSession(Action.Use, FromBody('name')))
|
||||||
async DEPRECATED_stop(
|
async DEPRECATED_stop(
|
||||||
@Body() request: SessionStopDeprecatedRequest,
|
@Body() request: SessionStopDeprecatedRequest,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
@@ -323,6 +356,7 @@ class SessionsController {
|
|||||||
description: 'Stop, Logout and Delete session.',
|
description: 'Stop, Logout and Delete session.',
|
||||||
deprecated: true,
|
deprecated: true,
|
||||||
})
|
})
|
||||||
|
@CheckPolicies(CanSession(Action.Use, FromBody('name')))
|
||||||
async DEPRECATED_logout(
|
async DEPRECATED_logout(
|
||||||
@Body() request: SessionLogoutDeprecatedRequest,
|
@Body() request: SessionLogoutDeprecatedRequest,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { Body, Controller, Get, Post } from '@nestjs/common';
|
import { Body, Controller, Get, Post, UseGuards } from '@nestjs/common';
|
||||||
import { ApiOperation, ApiSecurity, ApiTags } from '@nestjs/swagger';
|
import { ApiOperation, ApiSecurity, ApiTags } from '@nestjs/swagger';
|
||||||
import {
|
import {
|
||||||
SessionApiParam,
|
SessionApiParam,
|
||||||
@@ -15,10 +15,17 @@ import {
|
|||||||
VideoStatus,
|
VideoStatus,
|
||||||
VoiceStatus,
|
VoiceStatus,
|
||||||
} from '../structures/status.dto';
|
} from '../structures/status.dto';
|
||||||
|
import { PoliciesGuard } from '@waha/core/auth/policies.guard';
|
||||||
|
import { CheckPolicies } from '@waha/core/auth/policies.decorator';
|
||||||
|
import { CanSession, FromParam } from '@waha/core/auth/policies';
|
||||||
|
|
||||||
|
import { Action } from '@waha/core/auth/casl.types';
|
||||||
|
|
||||||
@ApiSecurity('api_key')
|
@ApiSecurity('api_key')
|
||||||
@Controller('api/:session/status')
|
@Controller('api/:session/status')
|
||||||
@ApiTags('🟢 Status')
|
@ApiTags('🟢 Status')
|
||||||
|
@UseGuards(PoliciesGuard)
|
||||||
|
@CheckPolicies(CanSession(Action.Use, FromParam('session')))
|
||||||
class StatusController {
|
class StatusController {
|
||||||
constructor(private manager: SessionManager) {}
|
constructor(private manager: SessionManager) {}
|
||||||
|
|
||||||
|
|||||||
@@ -1,17 +1,19 @@
|
|||||||
import { Controller, Get } from '@nestjs/common';
|
import { Controller, Get, UseGuards } from '@nestjs/common';
|
||||||
import {
|
import { ApiOperation, ApiSecurity, ApiTags } from '@nestjs/swagger';
|
||||||
ApiExtraModels,
|
|
||||||
ApiOperation,
|
|
||||||
ApiSecurity,
|
|
||||||
ApiTags,
|
|
||||||
} from '@nestjs/swagger';
|
|
||||||
|
|
||||||
import { WAHAEnvironment } from '../structures/environment.dto';
|
import { WAHAEnvironment } from '../structures/environment.dto';
|
||||||
import { VERSION } from '../version';
|
import { VERSION } from '../version';
|
||||||
|
import { PoliciesGuard } from '@waha/core/auth/policies.guard';
|
||||||
|
import { CheckPolicies } from '@waha/core/auth/policies.decorator';
|
||||||
|
import { CanServer } from '@waha/core/auth/policies';
|
||||||
|
|
||||||
|
import { Action } from '@waha/core/auth/casl.types';
|
||||||
|
|
||||||
@ApiSecurity('api_key')
|
@ApiSecurity('api_key')
|
||||||
@Controller('api/version')
|
@Controller('api/version')
|
||||||
@ApiTags('🔍 Observability')
|
@ApiTags('🔍 Observability')
|
||||||
|
@UseGuards(PoliciesGuard)
|
||||||
|
@CheckPolicies(CanServer(Action.Read))
|
||||||
export class VersionController {
|
export class VersionController {
|
||||||
@Get('')
|
@Get('')
|
||||||
@ApiOperation({
|
@ApiOperation({
|
||||||
|
|||||||
@@ -19,8 +19,10 @@ import { WAHAEvents, WAHAEventsWild } from '@waha/structures/enums.dto';
|
|||||||
import { EventWildUnmask } from '@waha/utils/events';
|
import { EventWildUnmask } from '@waha/utils/events';
|
||||||
import { generatePrefixedId } from '@waha/utils/ids';
|
import { generatePrefixedId } from '@waha/utils/ids';
|
||||||
import { IncomingMessage } from 'http';
|
import { IncomingMessage } from 'http';
|
||||||
import * as url from 'url';
|
import { URL } from 'url';
|
||||||
import { Server } from 'ws';
|
import { Server } from 'ws';
|
||||||
|
import { CaslAbilityFactory } from '@waha/core/auth/casl.ability';
|
||||||
|
import { Action, session as SessionName } from '@waha/core/auth/casl.types';
|
||||||
|
|
||||||
export enum WebSocketCloseCode {
|
export enum WebSocketCloseCode {
|
||||||
NORMAL = 1000,
|
NORMAL = 1000,
|
||||||
@@ -54,6 +56,7 @@ export class WebsocketGatewayCore
|
|||||||
constructor(
|
constructor(
|
||||||
private manager: SessionManager,
|
private manager: SessionManager,
|
||||||
private auth: WebSocketAuth,
|
private auth: WebSocketAuth,
|
||||||
|
private readonly casl: CaslAbilityFactory,
|
||||||
) {
|
) {
|
||||||
this.logger = new Logger('WebsocketGateway');
|
this.logger = new Logger('WebsocketGateway');
|
||||||
this.heartbeat = new WebsocketHeartbeatJob(
|
this.heartbeat = new WebsocketHeartbeatJob(
|
||||||
@@ -62,11 +65,16 @@ export class WebsocketGatewayCore
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
handleConnection(socket: WebSocket, request: IncomingMessage, ...args): any {
|
async handleConnection(
|
||||||
|
socket: WebSocket,
|
||||||
|
request: IncomingMessage,
|
||||||
|
...args
|
||||||
|
): Promise<any> {
|
||||||
// wsc - websocket client
|
// wsc - websocket client
|
||||||
socket.id = generatePrefixedId('wsc');
|
socket.id = generatePrefixedId('wsc');
|
||||||
|
|
||||||
if (!this.auth.validateRequest(request)) {
|
const user = await this.auth.validateRequest(request);
|
||||||
|
if (!user) {
|
||||||
// Not authorized - close connection
|
// Not authorized - close connection
|
||||||
socket.close(WebSocketCloseCode.POLICY_VIOLATION, 'Unauthorized');
|
socket.close(WebSocketCloseCode.POLICY_VIOLATION, 'Unauthorized');
|
||||||
this.logger.debug(
|
this.logger.debug(
|
||||||
@@ -75,9 +83,20 @@ export class WebsocketGatewayCore
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
this.logger.debug(`New client connected: ${request.url} - ${socket.id}`);
|
|
||||||
const params = this.getParams(request);
|
const params = this.getParams(request);
|
||||||
const session: string = params.session;
|
let session: string = params.session;
|
||||||
|
const ability = this.casl.createForUser(user);
|
||||||
|
if (session == '*' && !ability.can(Action.Use, 'all')) {
|
||||||
|
// Limit user to listen only the session events
|
||||||
|
session = user.session;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!ability.can(Action.Use, new SessionName(session))) {
|
||||||
|
socket.close(WebSocketCloseCode.POLICY_VIOLATION, 'Forbidden');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.logger.debug(`New client connected: ${request.url} - ${socket.id}`);
|
||||||
const events: WAHAEvents[] = params.events;
|
const events: WAHAEvents[] = params.events;
|
||||||
this.logger.debug(
|
this.logger.debug(
|
||||||
`Client connected to session: '${session}', events: ${events}, ${socket.id}`,
|
`Client connected to session: '${session}', events: ${events}, ${socket.id}`,
|
||||||
@@ -86,12 +105,17 @@ export class WebsocketGatewayCore
|
|||||||
const sub = this.manager
|
const sub = this.manager
|
||||||
.getSessionEvents(session, events)
|
.getSessionEvents(session, events)
|
||||||
.subscribe((data) => {
|
.subscribe((data) => {
|
||||||
this.logger.debug(`Sending data to client, event.id: ${data.id}`, data);
|
setImmediate(() => {
|
||||||
socket.send(JSON.stringify(data), (err) => {
|
this.logger.debug(
|
||||||
if (!err) {
|
`Sending data to client, event.id: ${data.id}`,
|
||||||
return;
|
data,
|
||||||
}
|
);
|
||||||
this.logger.error(`Error sending data to client: ${err}`);
|
socket.send(JSON.stringify(data), (err) => {
|
||||||
|
if (!err) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.logger.error(`Error sending data to client: ${err}`);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
socket.on('close', () => {
|
socket.on('close', () => {
|
||||||
@@ -101,14 +125,13 @@ export class WebsocketGatewayCore
|
|||||||
}
|
}
|
||||||
|
|
||||||
private getParams(request: IncomingMessage) {
|
private getParams(request: IncomingMessage) {
|
||||||
const query = url.parse(request.url, true).query;
|
// We need only search params, so localhost is fine here
|
||||||
const session = (query.session as string) || '*';
|
const query = new URL(request.url, 'http://localhost').searchParams;
|
||||||
let paramsEvents = (query.events as string[]) || '*';
|
const session = query.get('session') || '*';
|
||||||
// if params events string - split by ","
|
const paramsEvents = query.getAll('events');
|
||||||
if (typeof paramsEvents === 'string') {
|
const eventsRaw = paramsEvents.length > 0 ? paramsEvents : ['*'];
|
||||||
paramsEvents = paramsEvents.split(',');
|
const eventsList = eventsRaw.flatMap((value) => value.split(','));
|
||||||
}
|
const events = this.eventUnmask.unmask(eventsList);
|
||||||
const events = this.eventUnmask.unmask(paramsEvents);
|
|
||||||
return { session, events };
|
return { session, events };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -40,7 +40,7 @@ export class AxiosLogging {
|
|||||||
|
|
||||||
// Log debug for 2xx/3xx responses
|
// Log debug for 2xx/3xx responses
|
||||||
this.logger.debug(`${methodStr} ${status}:OK ${url}`);
|
this.logger.debug(`${methodStr} ${status}:OK ${url}`);
|
||||||
if (type.startsWith('application/json')) {
|
if (type?.startsWith('application/json')) {
|
||||||
const data = JSON.stringify(response.data);
|
const data = JSON.stringify(response.data);
|
||||||
this.logger.trace(`${methodStr} ${status}:OK ${url} ${data}`);
|
this.logger.trace(`${methodStr} ${status}:OK ${url} ${data}`);
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import {
|
|||||||
Body,
|
Body,
|
||||||
Controller,
|
Controller,
|
||||||
Delete,
|
Delete,
|
||||||
|
ForbiddenException,
|
||||||
Get,
|
Get,
|
||||||
Inject,
|
Inject,
|
||||||
NotFoundException,
|
NotFoundException,
|
||||||
@@ -9,6 +10,8 @@ import {
|
|||||||
Post,
|
Post,
|
||||||
Put,
|
Put,
|
||||||
Query,
|
Query,
|
||||||
|
Req,
|
||||||
|
UseGuards,
|
||||||
UsePipes,
|
UsePipes,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { ApiOperation, ApiSecurity, ApiTags } from '@nestjs/swagger';
|
import { ApiOperation, ApiSecurity, ApiTags } from '@nestjs/swagger';
|
||||||
@@ -17,6 +20,15 @@ import {
|
|||||||
IAppsService,
|
IAppsService,
|
||||||
} from '@waha/apps/app_sdk/services/IAppsService';
|
} from '@waha/apps/app_sdk/services/IAppsService';
|
||||||
import { SessionManager } from '@waha/core/abc/manager.abc';
|
import { SessionManager } from '@waha/core/abc/manager.abc';
|
||||||
|
import { CheckPolicies } from '@waha/core/auth/policies.decorator';
|
||||||
|
import { PoliciesGuard } from '@waha/core/auth/policies.guard';
|
||||||
|
import {
|
||||||
|
CanServer,
|
||||||
|
CanSession,
|
||||||
|
FromBody,
|
||||||
|
FromQuery,
|
||||||
|
} from '@waha/core/auth/policies';
|
||||||
|
import { Action, session as SessionName } from '@waha/core/auth/casl.types';
|
||||||
import { WAHAValidationPipe } from '@waha/nestjs/pipes/WAHAValidationPipe';
|
import { WAHAValidationPipe } from '@waha/nestjs/pipes/WAHAValidationPipe';
|
||||||
|
|
||||||
import { App } from '../dto/app.dto';
|
import { App } from '../dto/app.dto';
|
||||||
@@ -25,6 +37,7 @@ import { ListAppsQuery } from '../dto/query.dto';
|
|||||||
@ApiSecurity('api_key')
|
@ApiSecurity('api_key')
|
||||||
@Controller('api/apps')
|
@Controller('api/apps')
|
||||||
@ApiTags('🧩 Apps')
|
@ApiTags('🧩 Apps')
|
||||||
|
@UseGuards(PoliciesGuard)
|
||||||
export class AppsController {
|
export class AppsController {
|
||||||
constructor(
|
constructor(
|
||||||
@Inject(AppsService)
|
@Inject(AppsService)
|
||||||
@@ -34,6 +47,7 @@ export class AppsController {
|
|||||||
|
|
||||||
@Get('/')
|
@Get('/')
|
||||||
@ApiOperation({ summary: 'List all apps for a session' })
|
@ApiOperation({ summary: 'List all apps for a session' })
|
||||||
|
@CheckPolicies(CanSession(Action.Use, FromQuery('session')))
|
||||||
@UsePipes(new WAHAValidationPipe())
|
@UsePipes(new WAHAValidationPipe())
|
||||||
async list(
|
async list(
|
||||||
@Query(new WAHAValidationPipe()) query: ListAppsQuery,
|
@Query(new WAHAValidationPipe()) query: ListAppsQuery,
|
||||||
@@ -43,6 +57,7 @@ export class AppsController {
|
|||||||
|
|
||||||
@Post('/')
|
@Post('/')
|
||||||
@ApiOperation({ summary: 'Create a new app' })
|
@ApiOperation({ summary: 'Create a new app' })
|
||||||
|
@CheckPolicies(CanSession(Action.Use, FromBody('session')))
|
||||||
@UsePipes(new WAHAValidationPipe())
|
@UsePipes(new WAHAValidationPipe())
|
||||||
async create(@Body() app: App): Promise<App> {
|
async create(@Body() app: App): Promise<App> {
|
||||||
const result = await this.appsService.create(this.manager, app);
|
const result = await this.appsService.create(this.manager, app);
|
||||||
@@ -55,15 +70,39 @@ export class AppsController {
|
|||||||
|
|
||||||
@Get('/:id')
|
@Get('/:id')
|
||||||
@ApiOperation({ summary: 'Get app by ID' })
|
@ApiOperation({ summary: 'Get app by ID' })
|
||||||
|
@CheckPolicies(CanServer(Action.Read))
|
||||||
@UsePipes(new WAHAValidationPipe())
|
@UsePipes(new WAHAValidationPipe())
|
||||||
async get(@Param('id') id: string): Promise<App> {
|
async get(@Param('id') id: string, @Req() req: any): Promise<App> {
|
||||||
return await this.appsService.get(this.manager, id);
|
const app = await this.appsService.get(this.manager, id);
|
||||||
|
if (!app) {
|
||||||
|
throw new NotFoundException(`App '${id}' not found`);
|
||||||
|
}
|
||||||
|
if (!req.ability?.can(Action.Use, new SessionName(app.session))) {
|
||||||
|
throw new ForbiddenException();
|
||||||
|
}
|
||||||
|
return app;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Put('/:id')
|
@Put('/:id')
|
||||||
@ApiOperation({ summary: 'Update an existing app' })
|
@ApiOperation({ summary: 'Update an existing app' })
|
||||||
|
@CheckPolicies(CanServer(Action.Read))
|
||||||
@UsePipes(new WAHAValidationPipe())
|
@UsePipes(new WAHAValidationPipe())
|
||||||
async update(@Param('id') id: string, @Body() app: App): Promise<App> {
|
async update(
|
||||||
|
@Param('id') id: string,
|
||||||
|
@Body() app: App,
|
||||||
|
@Req() req: any,
|
||||||
|
): Promise<App> {
|
||||||
|
const existing = await this.appsService.get(this.manager, id);
|
||||||
|
if (existing) {
|
||||||
|
if (!req.ability?.can(Action.Use, new SessionName(existing.session))) {
|
||||||
|
throw new ForbiddenException();
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (!req.ability?.can(Action.Use, new SessionName(app.session))) {
|
||||||
|
throw new ForbiddenException();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (!app.id) {
|
if (!app.id) {
|
||||||
app.id = id;
|
app.id = id;
|
||||||
} else if (app.id !== id) {
|
} else if (app.id !== id) {
|
||||||
@@ -82,8 +121,16 @@ export class AppsController {
|
|||||||
|
|
||||||
@Delete('/:id')
|
@Delete('/:id')
|
||||||
@ApiOperation({ summary: 'Delete an app' })
|
@ApiOperation({ summary: 'Delete an app' })
|
||||||
|
@CheckPolicies(CanServer(Action.Read))
|
||||||
@UsePipes(new WAHAValidationPipe())
|
@UsePipes(new WAHAValidationPipe())
|
||||||
async delete(@Param('id') id: string): Promise<void> {
|
async delete(@Param('id') id: string, @Req() req: any): Promise<void> {
|
||||||
|
const existing = await this.appsService.get(this.manager, id);
|
||||||
|
if (!existing) {
|
||||||
|
throw new NotFoundException(`App '${id}' not found`);
|
||||||
|
}
|
||||||
|
if (!req.ability?.can(Action.Use, new SessionName(existing.session))) {
|
||||||
|
throw new ForbiddenException();
|
||||||
|
}
|
||||||
const app = await this.appsService.delete(this.manager, id);
|
const app = await this.appsService.delete(this.manager, id);
|
||||||
const isRunning = this.manager.isRunning(app.session);
|
const isRunning = this.manager.isRunning(app.session);
|
||||||
if (isRunning) {
|
if (isRunning) {
|
||||||
|
|||||||
@@ -25,13 +25,18 @@ function jobRemoveOptions() {
|
|||||||
|
|
||||||
export const JobRemoveOptions = jobRemoveOptions();
|
export const JobRemoveOptions = jobRemoveOptions();
|
||||||
|
|
||||||
export const ExponentialRetriesJobOptions: DefaultJobOptions = {
|
function exponentialRetriesJobOptions(): DefaultJobOptions {
|
||||||
attempts: 3,
|
return {
|
||||||
backoff: {
|
attempts: parseInt(process.env.WAHA_APPS_JOBS_ATTEMPTS) || 3,
|
||||||
type: 'exponential',
|
delay: parseInt(process.env.WAHA_APPS_JOBS_DELAY) || 0,
|
||||||
delay: 1000,
|
backoff: {
|
||||||
},
|
type: process.env.WAHA_APPS_JOBS_BACKOFF_TYPE || 'exponential',
|
||||||
};
|
delay: parseInt(process.env.WAHA_APPS_JOBS_BACKOFF_DELAY) || 1000,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export const ExponentialRetriesJobOptions = exponentialRetriesJobOptions();
|
||||||
|
|
||||||
export const NoRetriesJobOptions: DefaultJobOptions = {
|
export const NoRetriesJobOptions: DefaultJobOptions = {
|
||||||
attempts: 1,
|
attempts: 1,
|
||||||
|
|||||||
+33
-5
@@ -1,4 +1,10 @@
|
|||||||
import { parseBool } from '@waha/helpers';
|
import { parseBool } from '@waha/helpers';
|
||||||
|
import { APPS } from '@waha/apps/app_sdk/apps/definition';
|
||||||
|
|
||||||
|
// Apps that don't require queue (Redis) - derived from AppDefinition
|
||||||
|
const IN_MEMORY_APPS = Object.values(APPS)
|
||||||
|
.filter((app) => !app.queue)
|
||||||
|
.map((app) => app.name);
|
||||||
|
|
||||||
function parseCommaSeparatedList(value: string | undefined): string[] {
|
function parseCommaSeparatedList(value: string | undefined): string[] {
|
||||||
if (!value) {
|
if (!value) {
|
||||||
@@ -7,8 +13,30 @@ function parseCommaSeparatedList(value: string | undefined): string[] {
|
|||||||
return value.split(',').map((item) => item.trim());
|
return value.split(',').map((item) => item.trim());
|
||||||
}
|
}
|
||||||
|
|
||||||
export const AppEnv = {
|
function isMongoDB(): boolean {
|
||||||
enabled: parseBool(process.env.WAHA_APPS_ENABLED),
|
return !!process.env.WHATSAPP_SESSIONS_MONGO_URL;
|
||||||
on: parseCommaSeparatedList(process.env.WAHA_APPS_ON),
|
}
|
||||||
off: parseCommaSeparatedList(process.env.WAHA_APPS_OFF),
|
|
||||||
};
|
function buildAppEnv() {
|
||||||
|
const enabled = process.env.WAHA_APPS_ENABLED;
|
||||||
|
const on = process.env.WAHA_APPS_ON;
|
||||||
|
const off = process.env.WAHA_APPS_OFF;
|
||||||
|
|
||||||
|
// Default if not mongodb
|
||||||
|
const isUserConfigured = enabled !== undefined || on !== undefined;
|
||||||
|
if (!isUserConfigured && !isMongoDB()) {
|
||||||
|
return {
|
||||||
|
enabled: true,
|
||||||
|
on: IN_MEMORY_APPS,
|
||||||
|
off: parseCommaSeparatedList(off),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
enabled: parseBool(enabled),
|
||||||
|
on: parseCommaSeparatedList(on),
|
||||||
|
off: parseCommaSeparatedList(off),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export const AppEnv = buildAppEnv();
|
||||||
@@ -21,7 +21,7 @@ export class AppsDisabledService implements IAppsService {
|
|||||||
throw new AppsIsDisabledError();
|
throw new AppsIsDisabledError();
|
||||||
}
|
}
|
||||||
|
|
||||||
async get(manager: SessionManager, appId: string): Promise<App> {
|
async get(manager: SessionManager, appId: string): Promise<App | null> {
|
||||||
throw new AppsIsDisabledError();
|
throw new AppsIsDisabledError();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -90,10 +90,10 @@ export class AppsEnabledService implements IAppsService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const service = this.getAppService(app);
|
const service = this.getAppService(app);
|
||||||
if (!service && !AppRuntimeConfig.HasApp(app.app)) {
|
if (app.enabled && !service && !AppRuntimeConfig.HasApp(app.app)) {
|
||||||
throw new AppDisableError(app.app);
|
throw new AppDisableError(app.app);
|
||||||
}
|
}
|
||||||
service.validate(app);
|
service?.validate(app);
|
||||||
// Only run beforeCreated when app is enabled (default true if omitted)
|
// Only run beforeCreated when app is enabled (default true if omitted)
|
||||||
if (app.enabled !== false) {
|
if (app.enabled !== false) {
|
||||||
await service.beforeCreated(app);
|
await service.beforeCreated(app);
|
||||||
@@ -104,12 +104,12 @@ export class AppsEnabledService implements IAppsService {
|
|||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
async get(manager: SessionManager, appId: string): Promise<App> {
|
async get(manager: SessionManager, appId: string): Promise<App | null> {
|
||||||
const knex = manager.store.getWAHADatabase();
|
const knex = manager.store.getWAHADatabase();
|
||||||
const repo = new AppRepository(knex);
|
const repo = new AppRepository(knex);
|
||||||
const app = await repo.getById(appId);
|
const app = await repo.getById(appId);
|
||||||
if (!app) {
|
if (!app) {
|
||||||
throw new NotFoundException(`App '${appId}' not found`);
|
return null;
|
||||||
}
|
}
|
||||||
delete (app as any).pk;
|
delete (app as any).pk;
|
||||||
return app;
|
return app;
|
||||||
@@ -147,21 +147,21 @@ export class AppsEnabledService implements IAppsService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const service = this.getAppService(app);
|
const service = this.getAppService(app);
|
||||||
if (!service && !AppRuntimeConfig.HasApp(app.app)) {
|
if (app.enabled && !service && !AppRuntimeConfig.HasApp(app.app)) {
|
||||||
throw new AppDisableError(app.app);
|
throw new AppDisableError(app.app);
|
||||||
}
|
}
|
||||||
service.validate(app);
|
service?.validate(app);
|
||||||
|
|
||||||
const hasEnabledChange = savedApp.enabled !== app.enabled;
|
const hasEnabledChange = savedApp.enabled !== app.enabled;
|
||||||
|
|
||||||
if (hasEnabledChange) {
|
if (hasEnabledChange) {
|
||||||
if (app.enabled) {
|
if (app.enabled) {
|
||||||
await service.beforeEnabled(savedApp, app);
|
await service?.beforeEnabled(savedApp, app);
|
||||||
} else {
|
} else {
|
||||||
await service.beforeDisabled(savedApp, app);
|
await service?.beforeDisabled(savedApp, app);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
await service.beforeUpdated(savedApp, app);
|
await service?.beforeUpdated(savedApp, app);
|
||||||
}
|
}
|
||||||
await repo.update(app.id, app);
|
await repo.update(app.id, app);
|
||||||
const updated = await repo.getById(app.id);
|
const updated = await repo.getById(app.id);
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import { Knex } from 'knex';
|
|||||||
export interface IAppsService {
|
export interface IAppsService {
|
||||||
list(manager: SessionManager, session: string): Promise<App[]>;
|
list(manager: SessionManager, session: string): Promise<App[]>;
|
||||||
|
|
||||||
get(manager: SessionManager, appId: string): Promise<App>;
|
get(manager: SessionManager, appId: string): Promise<App | null>;
|
||||||
|
|
||||||
create(manager: SessionManager, app: App): Promise<App>;
|
create(manager: SessionManager, app: App): Promise<App>;
|
||||||
|
|
||||||
|
|||||||
@@ -2,8 +2,10 @@ import { ApiProperty } from '@nestjs/swagger';
|
|||||||
import { Type } from 'class-transformer';
|
import { Type } from 'class-transformer';
|
||||||
import {
|
import {
|
||||||
IsBoolean,
|
IsBoolean,
|
||||||
|
IsNumber,
|
||||||
IsOptional,
|
IsOptional,
|
||||||
IsString,
|
IsString,
|
||||||
|
Min,
|
||||||
ValidateNested,
|
ValidateNested,
|
||||||
} from 'class-validator';
|
} from 'class-validator';
|
||||||
|
|
||||||
@@ -23,6 +25,26 @@ export class CallsAppChannelConfig {
|
|||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsString()
|
@IsString()
|
||||||
message?: string;
|
message?: string;
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
description:
|
||||||
|
'Seconds to wait before declining the call. If not set or undefined, the call is declined immediately (0 seconds).',
|
||||||
|
required: false,
|
||||||
|
})
|
||||||
|
@IsOptional()
|
||||||
|
@IsNumber()
|
||||||
|
@Min(0)
|
||||||
|
waitBeforeDecline?: number;
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
description:
|
||||||
|
'Seconds to wait before sending the auto-reply message. If not set or undefined, the message is sent immediately (0 seconds).',
|
||||||
|
required: false,
|
||||||
|
})
|
||||||
|
@IsOptional()
|
||||||
|
@IsNumber()
|
||||||
|
@Min(0)
|
||||||
|
waitBeforeResponse?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export class CallsAppConfig {
|
export class CallsAppConfig {
|
||||||
|
|||||||
@@ -92,10 +92,14 @@ export class CallsListener {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (shouldReject) {
|
if (shouldReject) {
|
||||||
|
const waitBeforeDeclineMs = (config.waitBeforeDecline ?? 0) * 1000;
|
||||||
|
await sleep(waitBeforeDeclineMs);
|
||||||
await this.rejectCall(call);
|
await this.rejectCall(call);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (shouldMessage) {
|
if (shouldMessage) {
|
||||||
|
const waitBeforeResponseMs = (config.waitBeforeResponse ?? 0) * 1000;
|
||||||
|
await sleep(waitBeforeResponseMs);
|
||||||
await this.replyWithTyping(call.from, message);
|
await this.replyWithTyping(call.from, message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import {
|
|||||||
NoRetriesJobOptions,
|
NoRetriesJobOptions,
|
||||||
} from '@waha/apps/app_sdk/constants';
|
} from '@waha/apps/app_sdk/constants';
|
||||||
import { MessageCleanupConsumer } from '@waha/apps/chatwoot/consumers/scheduled/message.cleanup';
|
import { MessageCleanupConsumer } from '@waha/apps/chatwoot/consumers/scheduled/message.cleanup';
|
||||||
|
import { CheckTierConsumer } from '@waha/apps/chatwoot/consumers/scheduled/check.tier';
|
||||||
import { ChatWootAppService } from '@waha/apps/chatwoot/services/ChatWootAppService';
|
import { ChatWootAppService } from '@waha/apps/chatwoot/services/ChatWootAppService';
|
||||||
import * as lodash from 'lodash';
|
import * as lodash from 'lodash';
|
||||||
|
|
||||||
@@ -51,6 +52,10 @@ const IMPORTS = lodash.flatten([
|
|||||||
name: QueueName.SCHEDULED_CHECK_VERSION,
|
name: QueueName.SCHEDULED_CHECK_VERSION,
|
||||||
defaultJobOptions: merge(NoRetriesJobOptions, JobRemoveOptions),
|
defaultJobOptions: merge(NoRetriesJobOptions, JobRemoveOptions),
|
||||||
}),
|
}),
|
||||||
|
RegisterAppQueue({
|
||||||
|
name: QueueName.SCHEDULED_CHECK_TIER,
|
||||||
|
defaultJobOptions: merge(NoRetriesJobOptions, JobRemoveOptions),
|
||||||
|
}),
|
||||||
RegisterAppQueue({
|
RegisterAppQueue({
|
||||||
name: QueueName.TASK_CONTACTS_PULL,
|
name: QueueName.TASK_CONTACTS_PULL,
|
||||||
defaultJobOptions: merge(ExponentialRetriesJobOptions, JobRemoveOptions),
|
defaultJobOptions: merge(ExponentialRetriesJobOptions, JobRemoveOptions),
|
||||||
@@ -145,6 +150,7 @@ const PROVIDERS = [
|
|||||||
// Scheduled
|
// Scheduled
|
||||||
MessageCleanupConsumer,
|
MessageCleanupConsumer,
|
||||||
CheckVersionConsumer,
|
CheckVersionConsumer,
|
||||||
|
CheckTierConsumer,
|
||||||
// Services
|
// Services
|
||||||
ChatWootWAHAQueueService,
|
ChatWootWAHAQueueService,
|
||||||
ChatWootQueueService,
|
ChatWootQueueService,
|
||||||
|
|||||||
@@ -20,8 +20,18 @@ export async function QueueStatus(ctx: QueueCommandContext, name: string) {
|
|||||||
for (const status of result) {
|
for (const status of result) {
|
||||||
status.name = QueueNameRepr(status.name);
|
status.name = QueueNameRepr(status.name);
|
||||||
}
|
}
|
||||||
// locked: true - last
|
const categoryOrder = ['inbox', 'whatsapp', 'task', 'scheduled'];
|
||||||
result = lodash.sortBy(result, [(x) => !!x.locked, 'name']);
|
const categoryIndex = (name: string) => {
|
||||||
|
const category = name.split(' | ')[0];
|
||||||
|
const index = categoryOrder.indexOf(category);
|
||||||
|
return index === -1 ? categoryOrder.length : index;
|
||||||
|
};
|
||||||
|
// locked: true - last, then by category (inbox/whatsapp/task/scheduled), then by name
|
||||||
|
result = lodash.sortBy(result, [
|
||||||
|
(x) => !!x.locked,
|
||||||
|
(x) => categoryIndex(x.name),
|
||||||
|
'name',
|
||||||
|
]);
|
||||||
const msg = ctx.l.r('cli.cmd.queue.status.result', {
|
const msg = ctx.l.r('cli.cmd.queue.status.result', {
|
||||||
queues: result,
|
queues: result,
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -17,6 +17,9 @@ export async function runText(
|
|||||||
.map((line) => line.trimStart()) // remove indentation
|
.map((line) => line.trimStart()) // remove indentation
|
||||||
.join(' ') // join with space
|
.join(' ') // join with space
|
||||||
.trim(); // final cleanup
|
.trim(); // final cleanup
|
||||||
|
// Strip WhatsApp/markdown formatting characters so shell-quote doesn't
|
||||||
|
// treat them as glob operators and return non-string tokens
|
||||||
|
text = text.replace(/[*_~`]/g, '');
|
||||||
const output = new BufferedOutput();
|
const output = new BufferedOutput();
|
||||||
const program = BuildProgram(commands, ctx, output);
|
const program = BuildProgram(commands, ctx, output);
|
||||||
const argv = parse(text);
|
const argv = parse(text);
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import { Locale } from '@waha/apps/chatwoot/i18n/locale';
|
|||||||
* Parse human string into milliseconds
|
* Parse human string into milliseconds
|
||||||
*/
|
*/
|
||||||
export function ParseMS(value: string) {
|
export function ParseMS(value: string) {
|
||||||
const duration = ms(value);
|
const duration = ms(value as ms.StringValue);
|
||||||
if (duration == null) throw new Error(`Invalid duration: "${value}"`);
|
if (duration == null) throw new Error(`Invalid duration: "${value}"`);
|
||||||
if (duration < 0) throw new Error(`Duration cannot be negative: "${value}"`);
|
if (duration < 0) throw new Error(`Duration cannot be negative: "${value}"`);
|
||||||
return duration;
|
return duration;
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ import { Locale } from '@waha/apps/chatwoot/i18n/locale';
|
|||||||
|
|
||||||
import { CacheForConfig } from '../cache/ConversationCache';
|
import { CacheForConfig } from '../cache/ConversationCache';
|
||||||
import { IConversationCache } from '../cache/IConversationCache';
|
import { IConversationCache } from '../cache/IConversationCache';
|
||||||
|
import { AttributeKey } from '@waha/apps/chatwoot/const';
|
||||||
|
|
||||||
export interface ContactInfo {
|
export interface ContactInfo {
|
||||||
ChatId(): string;
|
ChatId(): string;
|
||||||
@@ -63,6 +64,8 @@ export class ContactConversationService {
|
|||||||
`Updating if required contact custom attributes for chat.id: ${chatId}, contact.id: ${cwContact.data.id}`,
|
`Updating if required contact custom attributes for chat.id: ${chatId}, contact.id: ${cwContact.data.id}`,
|
||||||
);
|
);
|
||||||
const attributes = await contactInfo.Attributes();
|
const attributes = await contactInfo.Attributes();
|
||||||
|
// Keep the current chat id in sync to reply using the latest address.
|
||||||
|
attributes[AttributeKey.WA_CHAT_ID] = chatId;
|
||||||
await this.contactService.upsertCustomAttributes(
|
await this.contactService.upsertCustomAttributes(
|
||||||
cwContact.data,
|
cwContact.data,
|
||||||
attributes,
|
attributes,
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { AttributeKey, INBOX_CONTACT_CHAT_ID } from '@waha/apps/chatwoot/const';
|
|||||||
import * as lodash from 'lodash';
|
import * as lodash from 'lodash';
|
||||||
import { WhatsAppMessage } from '@waha/apps/chatwoot/storage';
|
import { WhatsAppMessage } from '@waha/apps/chatwoot/storage';
|
||||||
import { buildMessageId } from '@waha/core/engines/noweb/session.noweb.core';
|
import { buildMessageId } from '@waha/core/engines/noweb/session.noweb.core';
|
||||||
import { isLidUser } from '@waha/core/utils/jids';
|
import { isLidUser, normalizeJid } from '@waha/core/utils/jids';
|
||||||
|
|
||||||
export function GetJID(contact: any): string | null {
|
export function GetJID(contact: any): string | null {
|
||||||
return contact?.custom_attributes?.[AttributeKey.WA_JID];
|
return contact?.custom_attributes?.[AttributeKey.WA_JID];
|
||||||
@@ -23,20 +23,13 @@ export function GetAllChatIDs(contact: any): Array<string> {
|
|||||||
attrs[AttributeKey.WA_JID],
|
attrs[AttributeKey.WA_JID],
|
||||||
attrs[AttributeKey.WA_LID],
|
attrs[AttributeKey.WA_LID],
|
||||||
];
|
];
|
||||||
return lodash.uniq(ids.filter(Boolean));
|
return lodash.uniq(ids.filter(Boolean).map(normalizeJid));
|
||||||
}
|
}
|
||||||
|
|
||||||
export function FindChatID(contact: any): string | null {
|
export function FindChatID(contact: any): string | null {
|
||||||
if (GetJID(contact)) {
|
const chatId =
|
||||||
return GetJID(contact);
|
GetChatID(contact) ?? GetJID(contact) ?? GetLID(contact) ?? null;
|
||||||
}
|
return chatId ? normalizeJid(chatId) : null;
|
||||||
if (GetLID(contact)) {
|
|
||||||
return GetLID(contact);
|
|
||||||
}
|
|
||||||
if (GetChatID(contact)) {
|
|
||||||
return GetChatID(contact);
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function SerializeWhatsAppKey(message: WhatsAppMessage): string {
|
export function SerializeWhatsAppKey(message: WhatsAppMessage): string {
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ export enum QueueName {
|
|||||||
//
|
//
|
||||||
SCHEDULED_MESSAGE_CLEANUP = 'chatwoot.scheduled | message.cleanup',
|
SCHEDULED_MESSAGE_CLEANUP = 'chatwoot.scheduled | message.cleanup',
|
||||||
SCHEDULED_CHECK_VERSION = 'chatwoot.scheduled | check.version',
|
SCHEDULED_CHECK_VERSION = 'chatwoot.scheduled | check.version',
|
||||||
|
SCHEDULED_CHECK_TIER = 'chatwoot.scheduled | check.tier',
|
||||||
|
|
||||||
//
|
//
|
||||||
// Task
|
// Task
|
||||||
|
|||||||
@@ -0,0 +1,42 @@
|
|||||||
|
import { Processor } from '@nestjs/bullmq';
|
||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { JOB_CONCURRENCY } from '@waha/apps/app_sdk/constants';
|
||||||
|
import { QueueName } from '@waha/apps/chatwoot/consumers/QueueName';
|
||||||
|
import { DIContainer } from '@waha/apps/chatwoot/di/DIContainer';
|
||||||
|
import { SessionManager } from '@waha/core/abc/manager.abc';
|
||||||
|
import { SUPPORT_US_URL } from '@waha/core/constants';
|
||||||
|
import { RMutexService } from '@waha/modules/rmutex/rmutex.service';
|
||||||
|
import { VERSION, WAHAVersion } from '@waha/version';
|
||||||
|
import { Job } from 'bullmq';
|
||||||
|
import { PinoLogger } from 'nestjs-pino';
|
||||||
|
|
||||||
|
import { TKey } from '@waha/apps/chatwoot/i18n/templates';
|
||||||
|
import { ChatWootScheduledConsumer } from './base';
|
||||||
|
|
||||||
|
@Processor(QueueName.SCHEDULED_CHECK_TIER, { concurrency: JOB_CONCURRENCY })
|
||||||
|
export class CheckTierConsumer extends ChatWootScheduledConsumer {
|
||||||
|
constructor(manager: SessionManager, log: PinoLogger, rmutex: RMutexService) {
|
||||||
|
super(manager, log, rmutex, CheckTierConsumer.name);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected ErrorHeaderKey(): TKey {
|
||||||
|
return TKey.JOB_SCHEDULED_ERROR_HEADER;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected async Process(container: DIContainer, job: Job): Promise<any> {
|
||||||
|
const logger = container.Logger();
|
||||||
|
const locale = container.Locale();
|
||||||
|
const conversation = await container
|
||||||
|
.ContactConversationService()
|
||||||
|
.InboxNotifications();
|
||||||
|
if (VERSION.tier !== WAHAVersion.CORE) {
|
||||||
|
logger.info('WAHA is not using the CORE version');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
logger.info('WAHA is using the CORE version');
|
||||||
|
const supportMessage = locale.key(TKey.WAHA_CORE_VERSION_USED).render({
|
||||||
|
supportUrl: SUPPORT_US_URL,
|
||||||
|
});
|
||||||
|
await conversation.incoming(supportMessage);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,24 +1,19 @@
|
|||||||
import { Processor } from '@nestjs/bullmq';
|
import { Processor } from '@nestjs/bullmq';
|
||||||
import { Injectable } from '@nestjs/common';
|
|
||||||
import { JOB_CONCURRENCY } from '@waha/apps/app_sdk/constants';
|
import { JOB_CONCURRENCY } from '@waha/apps/app_sdk/constants';
|
||||||
import { ILogger } from '@waha/apps/app_sdk/ILogger';
|
import { ILogger } from '@waha/apps/app_sdk/ILogger';
|
||||||
import { QueueName } from '@waha/apps/chatwoot/consumers/QueueName';
|
import { QueueName } from '@waha/apps/chatwoot/consumers/QueueName';
|
||||||
import { DIContainer } from '@waha/apps/chatwoot/di/DIContainer';
|
import { DIContainer } from '@waha/apps/chatwoot/di/DIContainer';
|
||||||
import { SessionManager } from '@waha/core/abc/manager.abc';
|
import { SessionManager } from '@waha/core/abc/manager.abc';
|
||||||
import { CHANGELOG_URL, SUPPORT_US_URL } from '@waha/core/constants';
|
import { CHANGELOG_URL } from '@waha/core/constants';
|
||||||
import { RMutexService } from '@waha/modules/rmutex/rmutex.service';
|
import { RMutexService } from '@waha/modules/rmutex/rmutex.service';
|
||||||
import { VERSION, WAHAVersion } from '@waha/version';
|
import { VERSION } from '@waha/version';
|
||||||
import axios from 'axios';
|
import axios from 'axios';
|
||||||
import { Job } from 'bullmq';
|
import { Job } from 'bullmq';
|
||||||
import { PinoLogger } from 'nestjs-pino';
|
import { PinoLogger } from 'nestjs-pino';
|
||||||
|
|
||||||
import { ChatWootScheduledConsumer } from './base';
|
|
||||||
import { TKey } from '@waha/apps/chatwoot/i18n/templates';
|
import { TKey } from '@waha/apps/chatwoot/i18n/templates';
|
||||||
|
import { ChatWootScheduledConsumer } from './base';
|
||||||
|
|
||||||
/**
|
|
||||||
* Scheduled consumer for version checking
|
|
||||||
* Periodically checks for new versions and notifies if updates are available
|
|
||||||
*/
|
|
||||||
@Processor(QueueName.SCHEDULED_CHECK_VERSION, { concurrency: JOB_CONCURRENCY })
|
@Processor(QueueName.SCHEDULED_CHECK_VERSION, { concurrency: JOB_CONCURRENCY })
|
||||||
export class CheckVersionConsumer extends ChatWootScheduledConsumer {
|
export class CheckVersionConsumer extends ChatWootScheduledConsumer {
|
||||||
constructor(manager: SessionManager, log: PinoLogger, rmutex: RMutexService) {
|
constructor(manager: SessionManager, log: PinoLogger, rmutex: RMutexService) {
|
||||||
@@ -29,34 +24,7 @@ export class CheckVersionConsumer extends ChatWootScheduledConsumer {
|
|||||||
return TKey.JOB_SCHEDULED_ERROR_HEADER;
|
return TKey.JOB_SCHEDULED_ERROR_HEADER;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Process the version check job
|
|
||||||
* Checks for new versions and notifies if updates are available
|
|
||||||
*/
|
|
||||||
protected async Process(container: DIContainer, job: Job): Promise<any> {
|
protected async Process(container: DIContainer, job: Job): Promise<any> {
|
||||||
await this.CheckWAHACoreVersion(container);
|
|
||||||
await this.CheckNewVersionAvailable(container);
|
|
||||||
}
|
|
||||||
|
|
||||||
private async CheckWAHACoreVersion(container: DIContainer) {
|
|
||||||
const logger = container.Logger();
|
|
||||||
const locale = container.Locale();
|
|
||||||
const conversation = await container
|
|
||||||
.ContactConversationService()
|
|
||||||
.InboxNotifications();
|
|
||||||
// If using the CORE version, send a message encouraging support
|
|
||||||
if (VERSION.tier !== WAHAVersion.CORE) {
|
|
||||||
logger.info('WAHA is not using the CORE version');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
logger.info('WAHA is using the CORE version');
|
|
||||||
const supportMessage = locale.key(TKey.WAHA_CORE_VERSION_USED).render({
|
|
||||||
supportUrl: SUPPORT_US_URL,
|
|
||||||
});
|
|
||||||
await conversation.incoming(supportMessage);
|
|
||||||
}
|
|
||||||
|
|
||||||
private async CheckNewVersionAvailable(container: DIContainer) {
|
|
||||||
const logger = container.Logger();
|
const logger = container.Logger();
|
||||||
logger.info('Processing version check job');
|
logger.info('Processing version check job');
|
||||||
const currentVersion = VERSION.version;
|
const currentVersion = VERSION.version;
|
||||||
@@ -72,7 +40,6 @@ export class CheckVersionConsumer extends ChatWootScheduledConsumer {
|
|||||||
`New version available: ${latestVersion} (current: ${currentVersion})`,
|
`New version available: ${latestVersion} (current: ${currentVersion})`,
|
||||||
);
|
);
|
||||||
|
|
||||||
// Send a message to Chatwoot conversation about a new version
|
|
||||||
const locale = container.Locale();
|
const locale = container.Locale();
|
||||||
const message = locale.key(TKey.WAHA_NEW_VERSION_AVAILABLE).render({
|
const message = locale.key(TKey.WAHA_NEW_VERSION_AVAILABLE).render({
|
||||||
currentVersion: currentVersion,
|
currentVersion: currentVersion,
|
||||||
|
|||||||
@@ -212,7 +212,11 @@ class MessagesPullHandler {
|
|||||||
|
|
||||||
// Perform some actions before any job started
|
// Perform some actions before any job started
|
||||||
if (options.pause) {
|
if (options.pause) {
|
||||||
await this.queueManager.pause();
|
const queues = [
|
||||||
|
...this.queueManager.resolve('inbox'),
|
||||||
|
...this.queueManager.resolve('waha'),
|
||||||
|
];
|
||||||
|
await this.queueManager.pause(queues);
|
||||||
await this.activity.queue(true);
|
await this.activity.queue(true);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -228,7 +232,11 @@ class MessagesPullHandler {
|
|||||||
|
|
||||||
// Resume queues if paused
|
// Resume queues if paused
|
||||||
if (options.pause) {
|
if (options.pause) {
|
||||||
await this.queueManager.resume();
|
const queues = [
|
||||||
|
...this.queueManager.resolve('inbox'),
|
||||||
|
...this.queueManager.resolve('waha'),
|
||||||
|
];
|
||||||
|
await this.queueManager.resume(queues);
|
||||||
await this.activity.queue(false);
|
await this.activity.queue(false);
|
||||||
}
|
}
|
||||||
// Progress summary
|
// Progress summary
|
||||||
|
|||||||
@@ -347,7 +347,7 @@ export abstract class MessageBaseHandler<
|
|||||||
chat_id: toCusFormat(key.remoteJid),
|
chat_id: toCusFormat(key.remoteJid),
|
||||||
message_id: key.id,
|
message_id: key.id,
|
||||||
from_me: key.fromMe,
|
from_me: key.fromMe,
|
||||||
participant: null,
|
participant: isJidGroup(key.remoteJid) ? key.participant : null,
|
||||||
};
|
};
|
||||||
await this.mappingService.map(chatwoot, whatsapp, 1);
|
await this.mappingService.map(chatwoot, whatsapp, 1);
|
||||||
return;
|
return;
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ import {
|
|||||||
PollMessage,
|
PollMessage,
|
||||||
ListMessage,
|
ListMessage,
|
||||||
ShareContactMessage,
|
ShareContactMessage,
|
||||||
|
StatusReplyMessage,
|
||||||
TextMessage,
|
TextMessage,
|
||||||
UnsupportedMessage,
|
UnsupportedMessage,
|
||||||
AlbumMessage,
|
AlbumMessage,
|
||||||
@@ -86,6 +87,18 @@ export class MessageAnyHandler extends MessageBaseHandler<WAMessage> {
|
|||||||
return msg;
|
return msg;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
converter = new StatusReplyMessage(
|
||||||
|
this.l,
|
||||||
|
this.logger,
|
||||||
|
this.waha,
|
||||||
|
this.job,
|
||||||
|
this.session,
|
||||||
|
);
|
||||||
|
msg = await converter.convert(payload, protoMessage);
|
||||||
|
if (msg) {
|
||||||
|
return msg;
|
||||||
|
}
|
||||||
|
|
||||||
converter = new TextMessage(this.l, this.logger, this.waha, this.job);
|
converter = new TextMessage(this.l, this.logger, this.waha, this.job);
|
||||||
msg = await converter.convert(payload, null);
|
msg = await converter.convert(payload, null);
|
||||||
if (msg) {
|
if (msg) {
|
||||||
|
|||||||
@@ -32,7 +32,10 @@ export class WAHAMessageReactionConsumer extends ChatWootWAHABaseConsumer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
GetChatId(event: WAHAWebhookMessageReaction): string {
|
GetChatId(event: WAHAWebhookMessageReaction): string {
|
||||||
if (event.environment?.engine == WAHAEngine.WEBJS) {
|
if (
|
||||||
|
event.environment?.engine == WAHAEngine.WEBJS ||
|
||||||
|
event.environment?.engine == WAHAEngine.WPP
|
||||||
|
) {
|
||||||
// chat in "to" field for WEBJS for message.reaction
|
// chat in "to" field for WEBJS for message.reaction
|
||||||
// probably we need to set it to "from"
|
// probably we need to set it to "from"
|
||||||
// but for backward compatability we do this
|
// but for backward compatability we do this
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import {
|
|||||||
isJidStatusBroadcast,
|
isJidStatusBroadcast,
|
||||||
isLidUser,
|
isLidUser,
|
||||||
isPnUser,
|
isPnUser,
|
||||||
|
normalizeJid,
|
||||||
} from '@waha/core/utils/jids';
|
} from '@waha/core/utils/jids';
|
||||||
import { UnknownJIDFormat } from '@waha/apps/chatwoot/errors';
|
import { UnknownJIDFormat } from '@waha/apps/chatwoot/errors';
|
||||||
import { E164Parser } from '@waha/core/utils/PhoneJidNormalizer';
|
import { E164Parser } from '@waha/core/utils/PhoneJidNormalizer';
|
||||||
@@ -270,7 +271,7 @@ export function WhatsAppContactInfo(
|
|||||||
} else if (isJidBroadcast(chatId)) {
|
} else if (isJidBroadcast(chatId)) {
|
||||||
return new BroadcastContactInfo(session, chatId, locale);
|
return new BroadcastContactInfo(session, chatId, locale);
|
||||||
} else if (isLidUser(chatId)) {
|
} else if (isLidUser(chatId)) {
|
||||||
return new LidContactInfo(session, chatId, locale);
|
return new LidContactInfo(session, normalizeJid(chatId), locale);
|
||||||
} else if (isPnUser(chatId)) {
|
} else if (isPnUser(chatId)) {
|
||||||
return new JidContactInfo(session, chatId, locale);
|
return new JidContactInfo(session, chatId, locale);
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -325,6 +325,8 @@ waha.new.version.available: |-
|
|||||||
|
|
||||||
👉 تحقق مما هو جديد في [**🆕 سجل التغييرات**]({{{changelogUrl}}})
|
👉 تحقق مما هو جديد في [**🆕 سجل التغييرات**]({{{changelogUrl}}})
|
||||||
|
|
||||||
|
_لإيقاف هذه الإشعارات، أرسل_ `queue stop check.version`
|
||||||
|
|
||||||
waha.core.version.used: |-
|
waha.core.version.used: |-
|
||||||
❤️ **ادعم WAHA!**
|
❤️ **ادعم WAHA!**
|
||||||
|
|
||||||
@@ -487,6 +489,15 @@ whatsapp.to.chatwoot.message.pix: |-
|
|||||||
💳 **تم إرسال PIX نسخ ولصق**
|
💳 **تم إرسال PIX نسخ ولصق**
|
||||||
{{/pixData}}
|
{{/pixData}}
|
||||||
|
|
||||||
|
whatsapp.to.chatwoot.message.status.reply: |-
|
||||||
|
📣 **رد على حالة واتساب**
|
||||||
|
🏷️ **النوع:** {{type}}
|
||||||
|
{{#quotedText}}
|
||||||
|
📝 **نص الحالة:** {{quotedText}}
|
||||||
|
{{/quotedText}}
|
||||||
|
|
||||||
|
{{content}}
|
||||||
|
|
||||||
whatsapp.to.chatwoot.message.unsupported: |-
|
whatsapp.to.chatwoot.message.unsupported: |-
|
||||||
⚠️ **هذا النوع من الرسائل غير مدعوم في هذا الصندوق الوارد.**
|
⚠️ **هذا النوع من الرسائل غير مدعوم في هذا الصندوق الوارد.**
|
||||||
📱 يرجى فتح **WhatsApp** لعرضه.
|
📱 يرجى فتح **WhatsApp** لعرضه.
|
||||||
|
|||||||
@@ -325,6 +325,8 @@ waha.new.version.available: |-
|
|||||||
|
|
||||||
👉 [**🆕 পরিবর্তন লগ**]({{{changelogUrl}}}) এ নতুন কি আছে তা দেখুন
|
👉 [**🆕 পরিবর্তন লগ**]({{{changelogUrl}}}) এ নতুন কি আছে তা দেখুন
|
||||||
|
|
||||||
|
_এই বিজ্ঞপ্তিগুলি অক্ষম করতে, পাঠান_ `queue stop check.version`
|
||||||
|
|
||||||
waha.core.version.used: |-
|
waha.core.version.used: |-
|
||||||
❤️ **WAHA সমর্থন করুন!**
|
❤️ **WAHA সমর্থন করুন!**
|
||||||
|
|
||||||
@@ -487,6 +489,15 @@ whatsapp.to.chatwoot.message.pix: |-
|
|||||||
💳 **PIX কপি এবং পেস্ট পাঠানো হয়েছে**
|
💳 **PIX কপি এবং পেস্ট পাঠানো হয়েছে**
|
||||||
{{/pixData}}
|
{{/pixData}}
|
||||||
|
|
||||||
|
whatsapp.to.chatwoot.message.status.reply: |-
|
||||||
|
📣 **WhatsApp স্ট্যাটাসের জবাব**
|
||||||
|
🏷️ **ধরন:** {{type}}
|
||||||
|
{{#quotedText}}
|
||||||
|
📝 **স্ট্যাটাসের টেক্সট:** {{quotedText}}
|
||||||
|
{{/quotedText}}
|
||||||
|
|
||||||
|
{{content}}
|
||||||
|
|
||||||
whatsapp.to.chatwoot.message.unsupported: |-
|
whatsapp.to.chatwoot.message.unsupported: |-
|
||||||
⚠️ **এই ধরনের বার্তা এই ইনবক্সে সমর্থিত নয়।**
|
⚠️ **এই ধরনের বার্তা এই ইনবক্সে সমর্থিত নয়।**
|
||||||
📱 এটি দেখতে অনুগ্রহ করে **WhatsApp** খুলুন।
|
📱 এটি দেখতে অনুগ্রহ করে **WhatsApp** খুলুন।
|
||||||
|
|||||||
@@ -328,6 +328,8 @@ waha.new.version.available: |-
|
|||||||
|
|
||||||
👉 Sehen Sie, was neu ist im [**🆕 Änderungsprotokoll**]({{{changelogUrl}}})
|
👉 Sehen Sie, was neu ist im [**🆕 Änderungsprotokoll**]({{{changelogUrl}}})
|
||||||
|
|
||||||
|
_Um diese Benachrichtigungen zu deaktivieren, senden Sie_ `queue stop check.version`
|
||||||
|
|
||||||
waha.core.version.used: |-
|
waha.core.version.used: |-
|
||||||
❤️ **Unterstützen Sie WAHA!**
|
❤️ **Unterstützen Sie WAHA!**
|
||||||
|
|
||||||
@@ -490,6 +492,15 @@ whatsapp.to.chatwoot.message.pix: |-
|
|||||||
💳 **PIX Kopieren und Einfügen gesendet**
|
💳 **PIX Kopieren und Einfügen gesendet**
|
||||||
{{/pixData}}
|
{{/pixData}}
|
||||||
|
|
||||||
|
whatsapp.to.chatwoot.message.status.reply: |-
|
||||||
|
📣 **Antwort auf WhatsApp-Status**
|
||||||
|
🏷️ **Typ:** {{type}}
|
||||||
|
{{#quotedText}}
|
||||||
|
📝 **Status-Text:** {{quotedText}}
|
||||||
|
{{/quotedText}}
|
||||||
|
|
||||||
|
{{content}}
|
||||||
|
|
||||||
whatsapp.to.chatwoot.message.unsupported: |-
|
whatsapp.to.chatwoot.message.unsupported: |-
|
||||||
⚠️ **Dieser Nachrichtentyp wird in dieser Inbox nicht unterstützt.**
|
⚠️ **Dieser Nachrichtentyp wird in dieser Inbox nicht unterstützt.**
|
||||||
📱 Bitte öffne **WhatsApp**, um ihn anzusehen.
|
📱 Bitte öffne **WhatsApp**, um ihn anzusehen.
|
||||||
|
|||||||
@@ -268,6 +268,15 @@ whatsapp.to.chatwoot.message.pix: |-
|
|||||||
💳 **PIX Copy and Paste sent**
|
💳 **PIX Copy and Paste sent**
|
||||||
{{/pixData}}
|
{{/pixData}}
|
||||||
|
|
||||||
|
whatsapp.to.chatwoot.message.status.reply: |-
|
||||||
|
📣 **Reply to WhatsApp Status**
|
||||||
|
🏷️ **Type:** {{type}}
|
||||||
|
{{#quotedText}}
|
||||||
|
📝 **Status Text:** {{quotedText}}
|
||||||
|
{{/quotedText}}
|
||||||
|
|
||||||
|
{{content}}
|
||||||
|
|
||||||
whatsapp.to.chatwoot.message.has.media.no.media: |-
|
whatsapp.to.chatwoot.message.has.media.no.media: |-
|
||||||
{{#content}}
|
{{#content}}
|
||||||
{{{content}}}
|
{{{content}}}
|
||||||
@@ -705,6 +714,8 @@ waha.new.version.available: |-
|
|||||||
|
|
||||||
👉 Check out what's new in the [**🆕 Changelog**]({{{changelogUrl}}})
|
👉 Check out what's new in the [**🆕 Changelog**]({{{changelogUrl}}})
|
||||||
|
|
||||||
|
_To disable these notifications, send_ `queue stop check.version`
|
||||||
|
|
||||||
waha.core.version.used: |-
|
waha.core.version.used: |-
|
||||||
❤️ **Support WAHA!**
|
❤️ **Support WAHA!**
|
||||||
|
|
||||||
|
|||||||
@@ -325,6 +325,8 @@ waha.new.version.available: |-
|
|||||||
|
|
||||||
👉 Mira qué hay de nuevo en el [**🆕 Registro de Cambios**]({{{changelogUrl}}})
|
👉 Mira qué hay de nuevo en el [**🆕 Registro de Cambios**]({{{changelogUrl}}})
|
||||||
|
|
||||||
|
_Para desactivar estas notificaciones, envía_ `queue stop check.version`
|
||||||
|
|
||||||
waha.core.version.used: |-
|
waha.core.version.used: |-
|
||||||
❤️ **¡Apoya a WAHA!**
|
❤️ **¡Apoya a WAHA!**
|
||||||
|
|
||||||
@@ -487,6 +489,15 @@ whatsapp.to.chatwoot.message.pix: |-
|
|||||||
💳 **PIX Copiar y Pegar enviado**
|
💳 **PIX Copiar y Pegar enviado**
|
||||||
{{/pixData}}
|
{{/pixData}}
|
||||||
|
|
||||||
|
whatsapp.to.chatwoot.message.status.reply: |-
|
||||||
|
📣 **Respuesta al estado de WhatsApp**
|
||||||
|
🏷️ **Tipo:** {{type}}
|
||||||
|
{{#quotedText}}
|
||||||
|
📝 **Texto del Estado:** {{quotedText}}
|
||||||
|
{{/quotedText}}
|
||||||
|
|
||||||
|
{{content}}
|
||||||
|
|
||||||
whatsapp.to.chatwoot.message.unsupported: |-
|
whatsapp.to.chatwoot.message.unsupported: |-
|
||||||
⚠️ **Este tipo de mensaje no es compatible con esta bandeja de entrada.**
|
⚠️ **Este tipo de mensaje no es compatible con esta bandeja de entrada.**
|
||||||
📱 Por favor, abre **WhatsApp** para verlo.
|
📱 Por favor, abre **WhatsApp** para verlo.
|
||||||
|
|||||||
@@ -325,6 +325,8 @@ waha.new.version.available: |-
|
|||||||
|
|
||||||
👉 موارد جدید را در [**🆕 تغییرات**]({{{changelogUrl}}}) مشاهده کنید
|
👉 موارد جدید را در [**🆕 تغییرات**]({{{changelogUrl}}}) مشاهده کنید
|
||||||
|
|
||||||
|
_برای غیرفعال کردن این اعلانها، ارسال کنید_ `queue stop check.version`
|
||||||
|
|
||||||
waha.core.version.used: |-
|
waha.core.version.used: |-
|
||||||
❤️ **از WAHA پشتیبانی کنید!**
|
❤️ **از WAHA پشتیبانی کنید!**
|
||||||
|
|
||||||
@@ -487,6 +489,15 @@ whatsapp.to.chatwoot.message.pix: |-
|
|||||||
💳 **PIX کپی و چسباندن ارسال شد**
|
💳 **PIX کپی و چسباندن ارسال شد**
|
||||||
{{/pixData}}
|
{{/pixData}}
|
||||||
|
|
||||||
|
whatsapp.to.chatwoot.message.status.reply: |-
|
||||||
|
📣 **پاسخ به وضعیت واتساپ**
|
||||||
|
🏷️ **نوع:** {{type}}
|
||||||
|
{{#quotedText}}
|
||||||
|
📝 **متن وضعیت:** {{quotedText}}
|
||||||
|
{{/quotedText}}
|
||||||
|
|
||||||
|
{{content}}
|
||||||
|
|
||||||
whatsapp.to.chatwoot.message.unsupported: |-
|
whatsapp.to.chatwoot.message.unsupported: |-
|
||||||
⚠️ **این نوع پیام در این صندوق ورودی پشتیبانی نمیشود.**
|
⚠️ **این نوع پیام در این صندوق ورودی پشتیبانی نمیشود.**
|
||||||
📱 لطفاً برای مشاهده آن **WhatsApp** را باز کنید.
|
📱 لطفاً برای مشاهده آن **WhatsApp** را باز کنید.
|
||||||
|
|||||||
@@ -325,6 +325,8 @@ waha.new.version.available: |-
|
|||||||
|
|
||||||
👉 Découvrez les nouveautés dans le [**🆕 Journal des modifications**]({{{changelogUrl}}})
|
👉 Découvrez les nouveautés dans le [**🆕 Journal des modifications**]({{{changelogUrl}}})
|
||||||
|
|
||||||
|
_Pour désactiver ces notifications, envoyez_ `queue stop check.version`
|
||||||
|
|
||||||
waha.core.version.used: |-
|
waha.core.version.used: |-
|
||||||
❤️ **Soutenez WAHA !**
|
❤️ **Soutenez WAHA !**
|
||||||
|
|
||||||
@@ -487,6 +489,15 @@ whatsapp.to.chatwoot.message.pix: |-
|
|||||||
💳 **PIX Copier et Coller envoyé**
|
💳 **PIX Copier et Coller envoyé**
|
||||||
{{/pixData}}
|
{{/pixData}}
|
||||||
|
|
||||||
|
whatsapp.to.chatwoot.message.status.reply: |-
|
||||||
|
📣 **Réponse au statut WhatsApp**
|
||||||
|
🏷️ **Type :** {{type}}
|
||||||
|
{{#quotedText}}
|
||||||
|
📝 **Texte du Statut :** {{quotedText}}
|
||||||
|
{{/quotedText}}
|
||||||
|
|
||||||
|
{{content}}
|
||||||
|
|
||||||
whatsapp.to.chatwoot.message.unsupported: |-
|
whatsapp.to.chatwoot.message.unsupported: |-
|
||||||
⚠️ **Ce type de message n’est pas pris en charge dans cette boîte de réception.**
|
⚠️ **Ce type de message n’est pas pris en charge dans cette boîte de réception.**
|
||||||
📱 Veuillez ouvrir **WhatsApp** pour l’afficher.
|
📱 Veuillez ouvrir **WhatsApp** pour l’afficher.
|
||||||
|
|||||||
@@ -325,6 +325,8 @@ waha.new.version.available: |-
|
|||||||
|
|
||||||
👉 בדוק מה חדש ב[**🆕 יומן שינויים**]({{{changelogUrl}}})
|
👉 בדוק מה חדש ב[**🆕 יומן שינויים**]({{{changelogUrl}}})
|
||||||
|
|
||||||
|
_כדי לבטל התראות אלו, שלח_ `queue stop check.version`
|
||||||
|
|
||||||
waha.core.version.used: |-
|
waha.core.version.used: |-
|
||||||
❤️ **תמוך ב-WAHA!**
|
❤️ **תמוך ב-WAHA!**
|
||||||
|
|
||||||
@@ -487,6 +489,15 @@ whatsapp.to.chatwoot.message.pix: |-
|
|||||||
💳 **PIX העתק והדבק נשלח**
|
💳 **PIX העתק והדבק נשלח**
|
||||||
{{/pixData}}
|
{{/pixData}}
|
||||||
|
|
||||||
|
whatsapp.to.chatwoot.message.status.reply: |-
|
||||||
|
📣 **תגובה לסטטוס ב-WhatsApp**
|
||||||
|
🏷️ **סוג:** {{type}}
|
||||||
|
{{#quotedText}}
|
||||||
|
📝 **טקסט הסטטוס:** {{quotedText}}
|
||||||
|
{{/quotedText}}
|
||||||
|
|
||||||
|
{{content}}
|
||||||
|
|
||||||
whatsapp.to.chatwoot.message.unsupported: |-
|
whatsapp.to.chatwoot.message.unsupported: |-
|
||||||
⚠️ **סוג הודעה זה אינו נתמך בתיבה זו.**
|
⚠️ **סוג הודעה זה אינו נתמך בתיבה זו.**
|
||||||
📱 אנא פתח/י את **WhatsApp** כדי לצפות בזה.
|
📱 אנא פתח/י את **WhatsApp** כדי לצפות בזה.
|
||||||
|
|||||||
@@ -325,6 +325,8 @@ waha.new.version.available: |-
|
|||||||
|
|
||||||
👉 [**🆕 चेंजलॉग**]({{{changelogUrl}}}) में क्या नया है देखें
|
👉 [**🆕 चेंजलॉग**]({{{changelogUrl}}}) में क्या नया है देखें
|
||||||
|
|
||||||
|
_इन सूचनाओं को अक्षम करने के लिए, भेजें_ `queue stop check.version`
|
||||||
|
|
||||||
waha.core.version.used: |-
|
waha.core.version.used: |-
|
||||||
❤️ **WAHA का समर्थन करें!**
|
❤️ **WAHA का समर्थन करें!**
|
||||||
|
|
||||||
@@ -487,6 +489,15 @@ whatsapp.to.chatwoot.message.pix: |-
|
|||||||
💳 **PIX कॉपी और पेस्ट भेजा गया**
|
💳 **PIX कॉपी और पेस्ट भेजा गया**
|
||||||
{{/pixData}}
|
{{/pixData}}
|
||||||
|
|
||||||
|
whatsapp.to.chatwoot.message.status.reply: |-
|
||||||
|
📣 **WhatsApp स्टेटस का जवाब**
|
||||||
|
🏷️ **प्रकार:** {{type}}
|
||||||
|
{{#quotedText}}
|
||||||
|
📝 **स्टेटस टेक्स्ट:** {{quotedText}}
|
||||||
|
{{/quotedText}}
|
||||||
|
|
||||||
|
{{content}}
|
||||||
|
|
||||||
whatsapp.to.chatwoot.message.unsupported: |-
|
whatsapp.to.chatwoot.message.unsupported: |-
|
||||||
⚠️ **इस प्रकार का संदेश इस इनबॉक्स में समर्थित नहीं है।**
|
⚠️ **इस प्रकार का संदेश इस इनबॉक्स में समर्थित नहीं है।**
|
||||||
📱 इसे देखने के लिए कृपया **WhatsApp** खोलें।
|
📱 इसे देखने के लिए कृपया **WhatsApp** खोलें।
|
||||||
|
|||||||
@@ -325,6 +325,8 @@ waha.new.version.available: |-
|
|||||||
|
|
||||||
👉 Lihat apa yang baru di [**🆕 Changelog**]({{{changelogUrl}}})
|
👉 Lihat apa yang baru di [**🆕 Changelog**]({{{changelogUrl}}})
|
||||||
|
|
||||||
|
_Untuk menonaktifkan notifikasi ini, kirim_ `queue stop check.version`
|
||||||
|
|
||||||
waha.core.version.used: |-
|
waha.core.version.used: |-
|
||||||
❤️ **Dukung WAHA!**
|
❤️ **Dukung WAHA!**
|
||||||
|
|
||||||
@@ -487,6 +489,15 @@ whatsapp.to.chatwoot.message.pix: |-
|
|||||||
💳 **PIX Salin dan Tempel terkirim**
|
💳 **PIX Salin dan Tempel terkirim**
|
||||||
{{/pixData}}
|
{{/pixData}}
|
||||||
|
|
||||||
|
whatsapp.to.chatwoot.message.status.reply: |-
|
||||||
|
📣 **Balasan ke Status WhatsApp**
|
||||||
|
🏷️ **Tipe:** {{type}}
|
||||||
|
{{#quotedText}}
|
||||||
|
📝 **Teks Status:** {{quotedText}}
|
||||||
|
{{/quotedText}}
|
||||||
|
|
||||||
|
{{content}}
|
||||||
|
|
||||||
whatsapp.to.chatwoot.message.unsupported: |-
|
whatsapp.to.chatwoot.message.unsupported: |-
|
||||||
⚠️ **Jenis pesan ini tidak didukung di kotak masuk ini.**
|
⚠️ **Jenis pesan ini tidak didukung di kotak masuk ini.**
|
||||||
📱 Silakan buka **WhatsApp** untuk melihatnya.
|
📱 Silakan buka **WhatsApp** untuk melihatnya.
|
||||||
|
|||||||
@@ -268,6 +268,15 @@ whatsapp.to.chatwoot.message.pix: |-
|
|||||||
💳 **PIX Copia e Incolla inviato**
|
💳 **PIX Copia e Incolla inviato**
|
||||||
{{/pixData}}
|
{{/pixData}}
|
||||||
|
|
||||||
|
whatsapp.to.chatwoot.message.status.reply: |-
|
||||||
|
📣 **Risposta allo stato di WhatsApp**
|
||||||
|
🏷️ **Tipo:** {{type}}
|
||||||
|
{{#quotedText}}
|
||||||
|
📝 **Testo dello Stato:** {{quotedText}}
|
||||||
|
{{/quotedText}}
|
||||||
|
|
||||||
|
{{content}}
|
||||||
|
|
||||||
whatsapp.to.chatwoot.message.has.media.no.media: |-
|
whatsapp.to.chatwoot.message.has.media.no.media: |-
|
||||||
{{#content}}
|
{{#content}}
|
||||||
{{{content}}}
|
{{{content}}}
|
||||||
@@ -705,6 +714,8 @@ waha.new.version.available: |-
|
|||||||
|
|
||||||
👉 Scopri le novità nel [**🆕 Changelog**]({{{changelogUrl}}})
|
👉 Scopri le novità nel [**🆕 Changelog**]({{{changelogUrl}}})
|
||||||
|
|
||||||
|
_Per disattivare queste notifiche, invia_ `queue stop check.version`
|
||||||
|
|
||||||
waha.core.version.used: |-
|
waha.core.version.used: |-
|
||||||
❤️ **Supporta WAHA!**
|
❤️ **Supporta WAHA!**
|
||||||
|
|
||||||
|
|||||||
@@ -325,6 +325,8 @@ waha.new.version.available: |-
|
|||||||
|
|
||||||
👉 [**🆕 ਬਦਲਾਅ ਲੌਗ**]({{{changelogUrl}}}) ਵਿੱਚ ਨਵਾਂ ਕੀ ਹੈ ਦੇਖੋ
|
👉 [**🆕 ਬਦਲਾਅ ਲੌਗ**]({{{changelogUrl}}}) ਵਿੱਚ ਨਵਾਂ ਕੀ ਹੈ ਦੇਖੋ
|
||||||
|
|
||||||
|
_ਇਹ ਸੂਚਨਾਵਾਂ ਬੰਦ ਕਰਨ ਲਈ, ਭੇਜੋ_ `queue stop check.version`
|
||||||
|
|
||||||
waha.core.version.used: |-
|
waha.core.version.used: |-
|
||||||
❤️ **WAHA ਦਾ ਸਮਰਥਨ ਕਰੋ!**
|
❤️ **WAHA ਦਾ ਸਮਰਥਨ ਕਰੋ!**
|
||||||
|
|
||||||
@@ -487,6 +489,15 @@ whatsapp.to.chatwoot.message.pix: |-
|
|||||||
💳 **PIX ਕਾਪੀ ਅਤੇ ਪੇਸਟ ਭੇਜਿਆ ਗਿਆ**
|
💳 **PIX ਕਾਪੀ ਅਤੇ ਪੇਸਟ ਭੇਜਿਆ ਗਿਆ**
|
||||||
{{/pixData}}
|
{{/pixData}}
|
||||||
|
|
||||||
|
whatsapp.to.chatwoot.message.status.reply: |-
|
||||||
|
📣 **WhatsApp ਸਟੇਟਸ ਦਾ ਜਵਾਬ**
|
||||||
|
🏷️ **ਕਿਸਮ:** {{type}}
|
||||||
|
{{#quotedText}}
|
||||||
|
📝 **ਸਟੇਟਸ ਲਿਖਤ:** {{quotedText}}
|
||||||
|
{{/quotedText}}
|
||||||
|
|
||||||
|
{{content}}
|
||||||
|
|
||||||
whatsapp.to.chatwoot.message.unsupported: |-
|
whatsapp.to.chatwoot.message.unsupported: |-
|
||||||
⚠️ **ਇਹ ਸੁਨੇਹੇ ਦੀ ਕਿਸਮ ਇਸ ਇਨਬਾਕਸ ਵਿੱਚ ਸਮਰਥਿਤ ਨਹੀਂ ਹੈ।**
|
⚠️ **ਇਹ ਸੁਨੇਹੇ ਦੀ ਕਿਸਮ ਇਸ ਇਨਬਾਕਸ ਵਿੱਚ ਸਮਰਥਿਤ ਨਹੀਂ ਹੈ।**
|
||||||
📱 ਇਸਨੂੰ ਦੇਖਣ ਲਈ ਕਿਰਪਾ ਕਰਕੇ **WhatsApp** ਖੋਲ੍ਹੋ।
|
📱 ਇਸਨੂੰ ਦੇਖਣ ਲਈ ਕਿਰਪਾ ਕਰਕੇ **WhatsApp** ਖੋਲ੍ਹੋ।
|
||||||
|
|||||||
@@ -326,6 +326,8 @@ waha.new.version.available: |-
|
|||||||
|
|
||||||
👉 Confira o que há de novo no [**🆕 Registro de Alterações**]({{{changelogUrl}}})
|
👉 Confira o que há de novo no [**🆕 Registro de Alterações**]({{{changelogUrl}}})
|
||||||
|
|
||||||
|
_Para desativar essas notificações, envie_ `queue stop check.version`
|
||||||
|
|
||||||
waha.core.version.used: |-
|
waha.core.version.used: |-
|
||||||
❤️ **Apoie o WAHA!**
|
❤️ **Apoie o WAHA!**
|
||||||
|
|
||||||
@@ -492,6 +494,15 @@ whatsapp.to.chatwoot.message.pix: |-
|
|||||||
💳 **PIX Copia e Cola enviado**
|
💳 **PIX Copia e Cola enviado**
|
||||||
{{/pixData}}
|
{{/pixData}}
|
||||||
|
|
||||||
|
whatsapp.to.chatwoot.message.status.reply: |-
|
||||||
|
📣 **Resposta a Status do WhatsApp**
|
||||||
|
🏷️ **Tipo:** {{type}}
|
||||||
|
{{#quotedText}}
|
||||||
|
📝 **Texto do Status:** {{quotedText}}
|
||||||
|
{{/quotedText}}
|
||||||
|
|
||||||
|
{{content}}
|
||||||
|
|
||||||
whatsapp.to.chatwoot.message.unsupported: |-
|
whatsapp.to.chatwoot.message.unsupported: |-
|
||||||
⚠️ **Esse tipo de mensagem não é suportado nesta caixa de entrada.**
|
⚠️ **Esse tipo de mensagem não é suportado nesta caixa de entrada.**
|
||||||
📱 Por favor, abra o **WhatsApp** para visualizá-la.
|
📱 Por favor, abra o **WhatsApp** para visualizá-la.
|
||||||
|
|||||||
@@ -325,6 +325,8 @@ waha.new.version.available: |-
|
|||||||
|
|
||||||
👉 Узнайте, что нового в [**🆕 Списке изменений**]({{{changelogUrl}}})
|
👉 Узнайте, что нового в [**🆕 Списке изменений**]({{{changelogUrl}}})
|
||||||
|
|
||||||
|
_Чтобы отключить эти уведомления, отправьте_ `queue stop check.version`
|
||||||
|
|
||||||
waha.core.version.used: |-
|
waha.core.version.used: |-
|
||||||
❤️ **Поддержите WAHA!**
|
❤️ **Поддержите WAHA!**
|
||||||
|
|
||||||
@@ -487,6 +489,15 @@ whatsapp.to.chatwoot.message.pix: |-
|
|||||||
💳 **PIX Копировать и вставить отправлен**
|
💳 **PIX Копировать и вставить отправлен**
|
||||||
{{/pixData}}
|
{{/pixData}}
|
||||||
|
|
||||||
|
whatsapp.to.chatwoot.message.status.reply: |-
|
||||||
|
📣 **Ответ на статус WhatsApp**
|
||||||
|
🏷️ **Тип:** {{type}}
|
||||||
|
{{#quotedText}}
|
||||||
|
📝 **Текст Статуса:** {{quotedText}}
|
||||||
|
{{/quotedText}}
|
||||||
|
|
||||||
|
{{content}}
|
||||||
|
|
||||||
whatsapp.to.chatwoot.message.unsupported: |-
|
whatsapp.to.chatwoot.message.unsupported: |-
|
||||||
⚠️ **Этот тип сообщения не поддерживается в этом Inbox.**
|
⚠️ **Этот тип сообщения не поддерживается в этом Inbox.**
|
||||||
📱 Пожалуйста, откройте **WhatsApp**, чтобы просмотреть.
|
📱 Пожалуйста, откройте **WhatsApp**, чтобы просмотреть.
|
||||||
|
|||||||
@@ -325,6 +325,8 @@ waha.new.version.available: |-
|
|||||||
|
|
||||||
👉 [**🆕 Değişiklik Günlüğü**]({{{changelogUrl}}}) içinde yenilikleri kontrol edin
|
👉 [**🆕 Değişiklik Günlüğü**]({{{changelogUrl}}}) içinde yenilikleri kontrol edin
|
||||||
|
|
||||||
|
_Bu bildirimleri devre dışı bırakmak için gönderin_ `queue stop check.version`
|
||||||
|
|
||||||
waha.core.version.used: |-
|
waha.core.version.used: |-
|
||||||
❤️ **WAHA'yı Destekleyin!**
|
❤️ **WAHA'yı Destekleyin!**
|
||||||
|
|
||||||
@@ -487,6 +489,15 @@ whatsapp.to.chatwoot.message.pix: |-
|
|||||||
💳 **PIX Kopyala ve Yapıştır gönderildi**
|
💳 **PIX Kopyala ve Yapıştır gönderildi**
|
||||||
{{/pixData}}
|
{{/pixData}}
|
||||||
|
|
||||||
|
whatsapp.to.chatwoot.message.status.reply: |-
|
||||||
|
📣 **WhatsApp Durumuna Yanıt**
|
||||||
|
🏷️ **Tür:** {{type}}
|
||||||
|
{{#quotedText}}
|
||||||
|
📝 **Durum Metni:** {{quotedText}}
|
||||||
|
{{/quotedText}}
|
||||||
|
|
||||||
|
{{content}}
|
||||||
|
|
||||||
whatsapp.to.chatwoot.message.unsupported: |-
|
whatsapp.to.chatwoot.message.unsupported: |-
|
||||||
⚠️ **Bu mesaj türü bu gelen kutusunda desteklenmiyor.**
|
⚠️ **Bu mesaj türü bu gelen kutusunda desteklenmiyor.**
|
||||||
📱 Görüntülemek için lütfen **WhatsApp’ı** açın.
|
📱 Görüntülemek için lütfen **WhatsApp’ı** açın.
|
||||||
|
|||||||
@@ -325,6 +325,8 @@ waha.new.version.available: |-
|
|||||||
|
|
||||||
👉 Перевірте, що нового у [**🆕 Журналі змін**]({{{changelogUrl}}})
|
👉 Перевірте, що нового у [**🆕 Журналі змін**]({{{changelogUrl}}})
|
||||||
|
|
||||||
|
_Щоб вимкнути ці сповіщення, надішліть_ `queue stop check.version`
|
||||||
|
|
||||||
waha.core.version.used: |-
|
waha.core.version.used: |-
|
||||||
❤️ **Підтримайте WAHA!**
|
❤️ **Підтримайте WAHA!**
|
||||||
|
|
||||||
@@ -487,6 +489,15 @@ whatsapp.to.chatwoot.message.pix: |-
|
|||||||
💳 **PIX Копіювати та Вставити надіслано**
|
💳 **PIX Копіювати та Вставити надіслано**
|
||||||
{{/pixData}}
|
{{/pixData}}
|
||||||
|
|
||||||
|
whatsapp.to.chatwoot.message.status.reply: |-
|
||||||
|
📣 **Відповідь на статус WhatsApp**
|
||||||
|
🏷️ **Тип:** {{type}}
|
||||||
|
{{#quotedText}}
|
||||||
|
📝 **Текст Статусу:** {{quotedText}}
|
||||||
|
{{/quotedText}}
|
||||||
|
|
||||||
|
{{content}}
|
||||||
|
|
||||||
whatsapp.to.chatwoot.message.unsupported: |-
|
whatsapp.to.chatwoot.message.unsupported: |-
|
||||||
⚠️ **Цей тип повідомлення не підтримується в цих вхідних.**
|
⚠️ **Цей тип повідомлення не підтримується в цих вхідних.**
|
||||||
📱 Будь ласка, відкрийте **WhatsApp**, щоб переглянути.
|
📱 Будь ласка, відкрийте **WhatsApp**, щоб переглянути.
|
||||||
|
|||||||
@@ -325,6 +325,8 @@ waha.new.version.available: |-
|
|||||||
|
|
||||||
👉 [**🆕 تبدیلیوں کی فہرست**]({{{changelogUrl}}}) میں نیا کیا ہے دیکھیں
|
👉 [**🆕 تبدیلیوں کی فہرست**]({{{changelogUrl}}}) میں نیا کیا ہے دیکھیں
|
||||||
|
|
||||||
|
_ان اطلاعات کو بند کرنے کے لیے بھیجیں_ `queue stop check.version`
|
||||||
|
|
||||||
waha.core.version.used: |-
|
waha.core.version.used: |-
|
||||||
❤️ **WAHA کی حمایت کریں!**
|
❤️ **WAHA کی حمایت کریں!**
|
||||||
|
|
||||||
@@ -487,6 +489,15 @@ whatsapp.to.chatwoot.message.pix: |-
|
|||||||
💳 **PIX کاپی اور پیسٹ بھیج دیا گیا**
|
💳 **PIX کاپی اور پیسٹ بھیج دیا گیا**
|
||||||
{{/pixData}}
|
{{/pixData}}
|
||||||
|
|
||||||
|
whatsapp.to.chatwoot.message.status.reply: |-
|
||||||
|
📣 **WhatsApp اسٹیٹس کا جواب**
|
||||||
|
🏷️ **قسم:** {{type}}
|
||||||
|
{{#quotedText}}
|
||||||
|
📝 **اسٹیٹس کا متن:** {{quotedText}}
|
||||||
|
{{/quotedText}}
|
||||||
|
|
||||||
|
{{content}}
|
||||||
|
|
||||||
whatsapp.to.chatwoot.message.unsupported: |-
|
whatsapp.to.chatwoot.message.unsupported: |-
|
||||||
⚠️ **اس قسم کا پیغام اس انبکس میں معاونت یافتہ نہیں ہے۔**
|
⚠️ **اس قسم کا پیغام اس انبکس میں معاونت یافتہ نہیں ہے۔**
|
||||||
📱 اسے دیکھنے کے لیے براہ کرم **WhatsApp** کھولیں۔
|
📱 اسے دیکھنے کے لیے براہ کرم **WhatsApp** کھولیں۔
|
||||||
|
|||||||
@@ -325,6 +325,8 @@ waha.new.version.available: |-
|
|||||||
|
|
||||||
👉 查看[**🆕 更新日志**]({{{changelogUrl}}})
|
👉 查看[**🆕 更新日志**]({{{changelogUrl}}})
|
||||||
|
|
||||||
|
_要禁用这些通知,请发送_ `queue stop check.version`
|
||||||
|
|
||||||
waha.core.version.used: |-
|
waha.core.version.used: |-
|
||||||
❤️ **支持 WAHA!**
|
❤️ **支持 WAHA!**
|
||||||
|
|
||||||
@@ -487,6 +489,15 @@ whatsapp.to.chatwoot.message.pix: |-
|
|||||||
💳 **PIX 复制粘贴已发送**
|
💳 **PIX 复制粘贴已发送**
|
||||||
{{/pixData}}
|
{{/pixData}}
|
||||||
|
|
||||||
|
whatsapp.to.chatwoot.message.status.reply: |-
|
||||||
|
📣 **回复 WhatsApp 状态**
|
||||||
|
🏷️ **类型:**{{type}}
|
||||||
|
{{#quotedText}}
|
||||||
|
📝 **状态文本:**{{quotedText}}
|
||||||
|
{{/quotedText}}
|
||||||
|
|
||||||
|
{{content}}
|
||||||
|
|
||||||
whatsapp.to.chatwoot.message.unsupported: |-
|
whatsapp.to.chatwoot.message.unsupported: |-
|
||||||
⚠️ **此收件箱不支持此消息类型。**
|
⚠️ **此收件箱不支持此消息类型。**
|
||||||
📱 请打开 **WhatsApp** 查看。
|
📱 请打开 **WhatsApp** 查看。
|
||||||
|
|||||||
@@ -54,6 +54,7 @@ export enum TKey {
|
|||||||
WA_TO_CW_MESSAGE_POLL = 'whatsapp.to.chatwoot.message.poll',
|
WA_TO_CW_MESSAGE_POLL = 'whatsapp.to.chatwoot.message.poll',
|
||||||
WA_TO_CW_MESSAGE_EVENT = 'whatsapp.to.chatwoot.message.event',
|
WA_TO_CW_MESSAGE_EVENT = 'whatsapp.to.chatwoot.message.event',
|
||||||
WA_TO_CW_MESSAGE_PIX = 'whatsapp.to.chatwoot.message.pix',
|
WA_TO_CW_MESSAGE_PIX = 'whatsapp.to.chatwoot.message.pix',
|
||||||
|
WA_TO_CW_MESSAGE_STATUS_REPLY = 'whatsapp.to.chatwoot.message.status.reply',
|
||||||
WA_TO_CW_MESSAGE_UNSUPPORTED = 'whatsapp.to.chatwoot.message.unsupported',
|
WA_TO_CW_MESSAGE_UNSUPPORTED = 'whatsapp.to.chatwoot.message.unsupported',
|
||||||
WA_TO_CW_MESSAGE_FACEBOOK_AD = 'whatsapp.to.chatwoot.message.facebook.ad',
|
WA_TO_CW_MESSAGE_FACEBOOK_AD = 'whatsapp.to.chatwoot.message.facebook.ad',
|
||||||
WA_TO_CW_MESSAGE_LIST = 'whatsapp.to.chatwoot.message.list',
|
WA_TO_CW_MESSAGE_LIST = 'whatsapp.to.chatwoot.message.list',
|
||||||
@@ -189,6 +190,11 @@ export type TemplatePayloads = {
|
|||||||
message: proto.Message | null;
|
message: proto.Message | null;
|
||||||
pixData: PixTemplatePayload;
|
pixData: PixTemplatePayload;
|
||||||
};
|
};
|
||||||
|
[TKey.WA_TO_CW_MESSAGE_STATUS_REPLY]: {
|
||||||
|
type: string;
|
||||||
|
quotedText?: string;
|
||||||
|
content: string;
|
||||||
|
};
|
||||||
[TKey.WA_TO_CW_MESSAGE_UNSUPPORTED]: { details: Link };
|
[TKey.WA_TO_CW_MESSAGE_UNSUPPORTED]: { details: Link };
|
||||||
[TKey.WA_TO_CW_MESSAGE_FACEBOOK_AD]: {
|
[TKey.WA_TO_CW_MESSAGE_FACEBOOK_AD]: {
|
||||||
payload: WAMessage;
|
payload: WAMessage;
|
||||||
|
|||||||
@@ -0,0 +1,231 @@
|
|||||||
|
import type { proto } from '@adiwajshing/baileys';
|
||||||
|
import { ILogger } from '@waha/apps/app_sdk/ILogger';
|
||||||
|
import { WAHASelf, WAHASessionAPI } from '@waha/apps/app_sdk/waha/WAHASelf';
|
||||||
|
import { ChatWootMessagePartial } from '@waha/apps/chatwoot/consumers/waha/base';
|
||||||
|
import { Locale } from '@waha/apps/chatwoot/i18n/locale';
|
||||||
|
import { TKey } from '@waha/apps/chatwoot/i18n/templates';
|
||||||
|
import { WhatsappToMarkdown } from '@waha/apps/chatwoot/messages/to/chatwoot/utils/markdown';
|
||||||
|
import { EngineHelper, QuotedMedia } from '@waha/apps/chatwoot/waha';
|
||||||
|
import { Jid } from '@waha/core/engines/const';
|
||||||
|
import { WAMessage } from '@waha/structures/responses.dto';
|
||||||
|
import { Job } from 'bullmq';
|
||||||
|
import { TextMessage } from './TextMessage';
|
||||||
|
import { isEmptyString } from './utils/text';
|
||||||
|
import { SendAttachment } from '@waha/apps/chatwoot/client/types';
|
||||||
|
import esm from '@waha/vendor/esm';
|
||||||
|
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||||
|
const mime = require('mime-types');
|
||||||
|
|
||||||
|
type StatusReplyType = 'text' | 'image' | 'audio' | 'video' | 'unknown';
|
||||||
|
|
||||||
|
interface StatusQuotedMessageInfo {
|
||||||
|
data?: any;
|
||||||
|
id: string;
|
||||||
|
type: StatusReplyType;
|
||||||
|
text?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class StatusReplyMessage extends TextMessage {
|
||||||
|
constructor(
|
||||||
|
locale: Locale,
|
||||||
|
logger: ILogger,
|
||||||
|
waha: WAHASelf,
|
||||||
|
job: Job,
|
||||||
|
private readonly session: WAHASessionAPI,
|
||||||
|
) {
|
||||||
|
super(locale, logger, waha, job);
|
||||||
|
}
|
||||||
|
|
||||||
|
async convert(
|
||||||
|
payload: WAMessage,
|
||||||
|
protoMessage: proto.Message | null,
|
||||||
|
): Promise<ChatWootMessagePartial | null> {
|
||||||
|
if (!payload.replyTo?.id) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (!EngineHelper.IsReplyToStatus(payload, protoMessage)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
let attachments: SendAttachment[] = [];
|
||||||
|
const quoted = this.getStatusQuotedMessageInfo(payload);
|
||||||
|
let wamessage = null; // aka "quoted from store"
|
||||||
|
|
||||||
|
// Media - Use provided replyTo.media if present
|
||||||
|
if (attachments.length === 0 && payload.replyTo.media) {
|
||||||
|
const extension = mime.extension(payload.replyTo.media.mimetype);
|
||||||
|
payload.replyTo.media.filename = `status-message.${extension}`;
|
||||||
|
const quotedAttachments = await super.getAttachments(payload.replyTo);
|
||||||
|
attachments = [...attachments, ...quotedAttachments];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Media - fetch message by id from store and use it's "media"
|
||||||
|
if (attachments.length == 0) {
|
||||||
|
wamessage = await this.fetchStatusMessage(quoted.id);
|
||||||
|
if (wamessage?.media?.url) {
|
||||||
|
const extension = mime.extension(wamessage.media.mimetype);
|
||||||
|
wamessage.media.filename = `status-message.${extension}`;
|
||||||
|
const quotedAttachments = await super.getAttachments(wamessage);
|
||||||
|
attachments = [...attachments, ...quotedAttachments];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Media - get media url, key and try to decrypt it
|
||||||
|
if (attachments.length == 0) {
|
||||||
|
const replyData = payload.replyTo._data;
|
||||||
|
const quotedMedia = EngineHelper.ExtractQuotedMedia(replyData);
|
||||||
|
if (quotedMedia) {
|
||||||
|
const attachment =
|
||||||
|
await this.downloadQuotedMediaAttachment(quotedMedia);
|
||||||
|
if (attachment) {
|
||||||
|
attachments.push(attachment);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Act as regular text message, but we'll adjust some properties
|
||||||
|
const msg = await super.convert(payload, protoMessage);
|
||||||
|
// First goes Quoted attachments, then what sender sent
|
||||||
|
msg.attachments = [...attachments, ...msg.attachments];
|
||||||
|
|
||||||
|
// Wrap content with additional info
|
||||||
|
const quotedText = quoted.text ?? wamessage?.body ?? payload.replyTo?.body;
|
||||||
|
if (
|
||||||
|
isEmptyString(quotedText) &&
|
||||||
|
isEmptyString(msg.content) &&
|
||||||
|
attachments.length === 0
|
||||||
|
) {
|
||||||
|
// Nothing to send.
|
||||||
|
// Must check msg.content before wrapping it in status reply
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
msg.content = this.locale.r(TKey.WA_TO_CW_MESSAGE_STATUS_REPLY, {
|
||||||
|
type: quoted.type,
|
||||||
|
quotedText: WhatsappToMarkdown(quotedText),
|
||||||
|
content: msg.content,
|
||||||
|
});
|
||||||
|
return msg;
|
||||||
|
}
|
||||||
|
|
||||||
|
private getStatusQuotedMessageInfo(
|
||||||
|
payload: WAMessage,
|
||||||
|
): StatusQuotedMessageInfo {
|
||||||
|
const replyData = payload.replyTo._data;
|
||||||
|
const imageMessage =
|
||||||
|
replyData?.imageMessage || this.getWebjsMediaData(replyData, 'image');
|
||||||
|
if (imageMessage) {
|
||||||
|
return {
|
||||||
|
data: replyData,
|
||||||
|
id: payload.replyTo.id,
|
||||||
|
type: 'image',
|
||||||
|
text: imageMessage.caption ?? payload.replyTo.body ?? replyData?.body,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const videoMessage =
|
||||||
|
replyData?.videoMessage || this.getWebjsMediaData(replyData, 'video');
|
||||||
|
if (videoMessage) {
|
||||||
|
return {
|
||||||
|
data: replyData,
|
||||||
|
id: payload.replyTo.id,
|
||||||
|
type: 'video',
|
||||||
|
text: videoMessage.caption ?? payload.replyTo.body ?? replyData?.body,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const audioMessage =
|
||||||
|
replyData?.audioMessage || this.getWebjsMediaData(replyData, 'audio');
|
||||||
|
if (audioMessage) {
|
||||||
|
return {
|
||||||
|
data: replyData,
|
||||||
|
id: payload.replyTo.id,
|
||||||
|
type: 'audio',
|
||||||
|
text: audioMessage.caption ?? payload.replyTo.body ?? replyData?.body,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const quotedText =
|
||||||
|
replyData?.extendedTextMessage?.text ??
|
||||||
|
replyData?.conversation ??
|
||||||
|
payload.replyTo.body ??
|
||||||
|
replyData?.body;
|
||||||
|
return {
|
||||||
|
data: replyData,
|
||||||
|
id: payload.replyTo.id,
|
||||||
|
type: quotedText ? 'text' : 'unknown',
|
||||||
|
text: quotedText,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private getWebjsMediaData(
|
||||||
|
replyData: any,
|
||||||
|
expectedKind: 'image' | 'video' | 'audio',
|
||||||
|
): any | null {
|
||||||
|
if (!replyData) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const kind = replyData.kind ?? replyData.type;
|
||||||
|
if (kind !== expectedKind) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return replyData;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async downloadQuotedMediaAttachment(
|
||||||
|
quotedMedia: QuotedMedia,
|
||||||
|
): Promise<SendAttachment | null> {
|
||||||
|
try {
|
||||||
|
const decrypt = !!quotedMedia.mediaKey;
|
||||||
|
const mediaKeyBuffer = decrypt
|
||||||
|
? Buffer.from(quotedMedia.mediaKey, 'base64')
|
||||||
|
: undefined;
|
||||||
|
const stream = await esm.b.downloadContentFromMessage(
|
||||||
|
{
|
||||||
|
mediaKey: mediaKeyBuffer,
|
||||||
|
directPath: quotedMedia.directPath,
|
||||||
|
url: quotedMedia.url,
|
||||||
|
},
|
||||||
|
quotedMedia.mediaType as any,
|
||||||
|
{},
|
||||||
|
decrypt,
|
||||||
|
);
|
||||||
|
const chunks: Buffer[] = [];
|
||||||
|
for await (const chunk of stream) {
|
||||||
|
chunks.push(chunk);
|
||||||
|
}
|
||||||
|
const buffer = Buffer.concat(chunks);
|
||||||
|
const extension = mime.extension(quotedMedia.mimetype);
|
||||||
|
const filename = `status-message.${extension}`;
|
||||||
|
return {
|
||||||
|
content: buffer.toString('base64'),
|
||||||
|
filename: filename,
|
||||||
|
encoding: 'base64',
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
this.logger.warn('Failed to download quoted status media directly');
|
||||||
|
this.logger.debug(error);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async fetchStatusMessage(
|
||||||
|
replyMessageId: string,
|
||||||
|
): Promise<WAMessage | null> {
|
||||||
|
try {
|
||||||
|
const quotedMessage = await this.session.getMessageById(
|
||||||
|
Jid.BROADCAST,
|
||||||
|
replyMessageId,
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
return quotedMessage || null;
|
||||||
|
} catch (error) {
|
||||||
|
this.logger.warn(
|
||||||
|
`Failed to fetch original status message '${replyMessageId}'`,
|
||||||
|
);
|
||||||
|
this.logger.debug(error);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,16 +11,17 @@ import { MessageToChatWootConverter } from '@waha/apps/chatwoot/messages/to/chat
|
|||||||
import { WhatsappToMarkdown } from '@waha/apps/chatwoot/messages/to/chatwoot/utils/markdown';
|
import { WhatsappToMarkdown } from '@waha/apps/chatwoot/messages/to/chatwoot/utils/markdown';
|
||||||
import { JobLink } from '@waha/apps/app_sdk/JobUtils';
|
import { JobLink } from '@waha/apps/app_sdk/JobUtils';
|
||||||
import { Job } from 'bullmq';
|
import { Job } from 'bullmq';
|
||||||
|
import { WAMedia } from '@waha/structures/media.dto';
|
||||||
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||||
const mime = require('mime-types');
|
const mime = require('mime-types');
|
||||||
|
|
||||||
export class TextMessage implements MessageToChatWootConverter {
|
export class TextMessage implements MessageToChatWootConverter {
|
||||||
constructor(
|
constructor(
|
||||||
private readonly locale: Locale,
|
protected readonly locale: Locale,
|
||||||
private readonly logger: ILogger,
|
protected readonly logger: ILogger,
|
||||||
private readonly waha: WAHASelf,
|
protected readonly waha: WAHASelf,
|
||||||
private readonly job: Job,
|
protected readonly job: Job,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
async convert(
|
async convert(
|
||||||
@@ -52,12 +53,14 @@ export class TextMessage implements MessageToChatWootConverter {
|
|||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
content: WhatsappToMarkdown(content),
|
content: WhatsappToMarkdown(content),
|
||||||
attachments,
|
attachments: attachments,
|
||||||
private: undefined,
|
private: undefined,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
private async getAttachments(payload: WAMessage): Promise<SendAttachment[]> {
|
protected async getAttachments(payload: {
|
||||||
|
media?: WAMedia;
|
||||||
|
}): Promise<SendAttachment[]> {
|
||||||
const hasMedia = payload.media?.url;
|
const hasMedia = payload.media?.url;
|
||||||
if (!hasMedia) {
|
if (!hasMedia) {
|
||||||
return [];
|
return [];
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ export { EventMessage } from './EventMessage';
|
|||||||
export { PixMessage } from './PixMessage';
|
export { PixMessage } from './PixMessage';
|
||||||
export { ListMessage } from './ListMessage';
|
export { ListMessage } from './ListMessage';
|
||||||
export { AlbumMessage } from './AlbumMessage';
|
export { AlbumMessage } from './AlbumMessage';
|
||||||
|
export { StatusReplyMessage } from './StatusReplyMessage';
|
||||||
|
|
||||||
export type Awaitable<T> = T | Promise<T>;
|
export type Awaitable<T> = T | Promise<T>;
|
||||||
|
|
||||||
|
|||||||
@@ -15,6 +15,14 @@ describe('MarkdownToWhatsApp', () => {
|
|||||||
expect(MarkdownToWhatsApp(input)).toBe(expected);
|
expect(MarkdownToWhatsApp(input)).toBe(expected);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ChatWoot v4.10.1+ escapes newlines with trailing backslash
|
||||||
|
it('strips trailing backslash before newlines', () => {
|
||||||
|
const input = 'Hi \\\ntext message \\\nwith line \\\nbreak';
|
||||||
|
expect(MarkdownToWhatsApp(input)).toBe(
|
||||||
|
'Hi \ntext message \nwith line \nbreak',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
// Tests for URL protection
|
// Tests for URL protection
|
||||||
it('preserves URLs with multiple underscores', () => {
|
it('preserves URLs with multiple underscores', () => {
|
||||||
const input = 'https://example.com/page__name__test';
|
const input = 'https://example.com/page__name__test';
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ export function MarkdownToWhatsApp(text: string): string {
|
|||||||
}
|
}
|
||||||
return (
|
return (
|
||||||
text
|
text
|
||||||
|
// Remove trailing backslash before newlines (ChatWoot v4.10.1+ escaping)
|
||||||
|
.replace(/\\\n/g, '\n')
|
||||||
// Triple-backtick blocks → WhatsApp monospace blocks (same syntax)
|
// Triple-backtick blocks → WhatsApp monospace blocks (same syntax)
|
||||||
.replace(/```([\s\S]*?)```/g, '```$1```')
|
.replace(/```([\s\S]*?)```/g, '```$1```')
|
||||||
// Italic **first**, but only single‐star or single‐underscore
|
// Italic **first**, but only single‐star or single‐underscore
|
||||||
|
|||||||
@@ -9,6 +9,13 @@ describe('parseMentionsFromText', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('handles empty content safely', () => {
|
||||||
|
expect(parseMentionsFromText(null)).toEqual({
|
||||||
|
text: null,
|
||||||
|
mentions: null,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
it('parses @all and removes it from the text', () => {
|
it('parses @all and removes it from the text', () => {
|
||||||
const input = 'Hello @all';
|
const input = 'Hello @all';
|
||||||
expect(parseMentionsFromText(input)).toEqual({
|
expect(parseMentionsFromText(input)).toEqual({
|
||||||
@@ -108,8 +115,16 @@ describe('parseMentionsFromText', () => {
|
|||||||
it('parses @lid mentions without c.us suffix', () => {
|
it('parses @lid mentions without c.us suffix', () => {
|
||||||
const input = 'Notify @123123@lid now';
|
const input = 'Notify @123123@lid now';
|
||||||
expect(parseMentionsFromText(input)).toEqual({
|
expect(parseMentionsFromText(input)).toEqual({
|
||||||
text: 'Notify @123123@lid now',
|
text: 'Notify @123123 now',
|
||||||
mentions: ['123123@lid'],
|
mentions: ['123123@lid'],
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('replaces @lid suffix with plain ids', () => {
|
||||||
|
const input = '@123456@lid please ping @654321@lid.';
|
||||||
|
expect(parseMentionsFromText(input)).toEqual({
|
||||||
|
text: '@123456 please ping @654321.',
|
||||||
|
mentions: ['123456@lid', '654321@lid'],
|
||||||
|
});
|
||||||
|
});
|
||||||
});
|
});
|
||||||
@@ -15,7 +15,15 @@ export interface ParsedMentions {
|
|||||||
* @param text - The message text
|
* @param text - The message text
|
||||||
* @returns Parsed mentions with cleaned text
|
* @returns Parsed mentions with cleaned text
|
||||||
*/
|
*/
|
||||||
export function parseMentionsFromText(text: string): ParsedMentions {
|
export function parseMentionsFromText(
|
||||||
|
text: string | null | undefined,
|
||||||
|
): ParsedMentions {
|
||||||
|
if (!text) {
|
||||||
|
return {
|
||||||
|
text: text,
|
||||||
|
mentions: null,
|
||||||
|
};
|
||||||
|
}
|
||||||
const mentions: string[] = [];
|
const mentions: string[] = [];
|
||||||
let content = text;
|
let content = text;
|
||||||
|
|
||||||
@@ -40,6 +48,10 @@ export function parseMentionsFromText(text: string): ParsedMentions {
|
|||||||
mentions.push(formattedLid);
|
mentions.push(formattedLid);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if (mentions.length > 0) {
|
||||||
|
const lidRegexReplace = /(^|\s)@(\d{6,15})@lid\b/g;
|
||||||
|
content = content.replace(lidRegexReplace, '$1@$2').trim();
|
||||||
|
}
|
||||||
|
|
||||||
// Regex to match @ followed by phone number
|
// Regex to match @ followed by phone number
|
||||||
// Matches: @558591203123, @5585991203123, etc.
|
// Matches: @558591203123, @5585991203123, etc.
|
||||||
|
|||||||
@@ -54,6 +54,21 @@ export class ChatWootScheduleService {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
// Check the tier
|
||||||
|
const checkTierQueue = this.queueRegistry.queue(
|
||||||
|
QueueName.SCHEDULED_CHECK_TIER,
|
||||||
|
);
|
||||||
|
await checkTierQueue.upsertJobScheduler(
|
||||||
|
this.JobId(QueueName.SCHEDULED_CHECK_TIER, appId),
|
||||||
|
// Every Monday (1) at 14:00
|
||||||
|
{ pattern: '0 0 14 * * 1' },
|
||||||
|
{
|
||||||
|
data: {
|
||||||
|
app: appId,
|
||||||
|
session: sessionName,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
async unschedule(appId: string, sessionName: string): Promise<void> {
|
async unschedule(appId: string, sessionName: string): Promise<void> {
|
||||||
@@ -71,6 +86,13 @@ export class ChatWootScheduleService {
|
|||||||
await checkVersionQueue.removeJobScheduler(
|
await checkVersionQueue.removeJobScheduler(
|
||||||
this.JobId(QueueName.SCHEDULED_CHECK_VERSION, appId),
|
this.JobId(QueueName.SCHEDULED_CHECK_VERSION, appId),
|
||||||
);
|
);
|
||||||
|
// Check the tier
|
||||||
|
const checkTierQueue = this.queueRegistry.queue(
|
||||||
|
QueueName.SCHEDULED_CHECK_TIER,
|
||||||
|
);
|
||||||
|
await checkTierQueue.removeJobScheduler(
|
||||||
|
this.JobId(QueueName.SCHEDULED_CHECK_TIER, appId),
|
||||||
|
);
|
||||||
|
|
||||||
// contacts
|
// contacts
|
||||||
const contactsPullQueue = this.queueRegistry.queue(
|
const contactsPullQueue = this.queueRegistry.queue(
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { QueueName } from '../consumers/QueueName';
|
import { QueueName } from '../consumers/QueueName';
|
||||||
import { QueueRegistry } from '@waha/apps/chatwoot/services/QueueRegistry';
|
import { QueueRegistry } from '@waha/apps/chatwoot/services/QueueRegistry';
|
||||||
import { Injectable } from '@nestjs/common';
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { QueueNameRepr } from '@waha/apps/app_sdk/JobUtils';
|
||||||
|
|
||||||
const Managable = true;
|
const Managable = true;
|
||||||
const Locked = false;
|
const Locked = false;
|
||||||
@@ -18,7 +19,8 @@ export class QueueManager {
|
|||||||
constructor(private readonly registry: QueueRegistry) {
|
constructor(private readonly registry: QueueRegistry) {
|
||||||
this.queues = {
|
this.queues = {
|
||||||
[QueueName.SCHEDULED_MESSAGE_CLEANUP]: Locked,
|
[QueueName.SCHEDULED_MESSAGE_CLEANUP]: Locked,
|
||||||
[QueueName.SCHEDULED_CHECK_VERSION]: Locked,
|
[QueueName.SCHEDULED_CHECK_VERSION]: Managable,
|
||||||
|
[QueueName.SCHEDULED_CHECK_TIER]: Locked,
|
||||||
[QueueName.TASK_CONTACTS_PULL]: Locked,
|
[QueueName.TASK_CONTACTS_PULL]: Locked,
|
||||||
[QueueName.TASK_MESSAGES_PULL]: Locked,
|
[QueueName.TASK_MESSAGES_PULL]: Locked,
|
||||||
[QueueName.WAHA_SESSION_STATUS]: Locked,
|
[QueueName.WAHA_SESSION_STATUS]: Locked,
|
||||||
@@ -75,8 +77,19 @@ export class QueueManager {
|
|||||||
case undefined:
|
case undefined:
|
||||||
return queues;
|
return queues;
|
||||||
|
|
||||||
default:
|
default: {
|
||||||
|
const matches = queues.filter((q) => q.split(' | ')[1] === shortcut);
|
||||||
|
if (matches.length === 1) {
|
||||||
|
return [matches[0]];
|
||||||
|
}
|
||||||
|
if (matches.length > 1) {
|
||||||
|
const names = matches.map(QueueNameRepr).join(', ');
|
||||||
|
throw new Error(
|
||||||
|
`Ambiguous queue name "${shortcut}", matches: ${names}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
return [shortcut as QueueName];
|
return [shortcut as QueueName];
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -16,6 +16,8 @@ export class QueueRegistry {
|
|||||||
private readonly scheduledMessageCleanupQueue: Queue,
|
private readonly scheduledMessageCleanupQueue: Queue,
|
||||||
@InjectQueue(QueueName.SCHEDULED_CHECK_VERSION)
|
@InjectQueue(QueueName.SCHEDULED_CHECK_VERSION)
|
||||||
private readonly scheduledCheckVersionQueue: Queue,
|
private readonly scheduledCheckVersionQueue: Queue,
|
||||||
|
@InjectQueue(QueueName.SCHEDULED_CHECK_TIER)
|
||||||
|
private readonly scheduledCheckTierQueue: Queue,
|
||||||
@InjectQueue(QueueName.TASK_CONTACTS_PULL)
|
@InjectQueue(QueueName.TASK_CONTACTS_PULL)
|
||||||
private readonly taskContactsPullQueue: Queue,
|
private readonly taskContactsPullQueue: Queue,
|
||||||
@InjectQueue(QueueName.TASK_MESSAGES_PULL)
|
@InjectQueue(QueueName.TASK_MESSAGES_PULL)
|
||||||
@@ -55,6 +57,7 @@ export class QueueRegistry {
|
|||||||
this.queues = {
|
this.queues = {
|
||||||
[QueueName.SCHEDULED_MESSAGE_CLEANUP]: this.scheduledMessageCleanupQueue,
|
[QueueName.SCHEDULED_MESSAGE_CLEANUP]: this.scheduledMessageCleanupQueue,
|
||||||
[QueueName.SCHEDULED_CHECK_VERSION]: this.scheduledCheckVersionQueue,
|
[QueueName.SCHEDULED_CHECK_VERSION]: this.scheduledCheckVersionQueue,
|
||||||
|
[QueueName.SCHEDULED_CHECK_TIER]: this.scheduledCheckTierQueue,
|
||||||
[QueueName.TASK_CONTACTS_PULL]: this.taskContactsPullQueue,
|
[QueueName.TASK_CONTACTS_PULL]: this.taskContactsPullQueue,
|
||||||
[QueueName.TASK_MESSAGES_PULL]: this.taskMessagesPullQueue,
|
[QueueName.TASK_MESSAGES_PULL]: this.taskMessagesPullQueue,
|
||||||
[QueueName.WAHA_SESSION_STATUS]: this.wahaSessionStatusQueue,
|
[QueueName.WAHA_SESSION_STATUS]: this.wahaSessionStatusQueue,
|
||||||
|
|||||||
@@ -1,17 +1,34 @@
|
|||||||
import * as lodash from 'lodash';
|
import * as lodash from 'lodash';
|
||||||
|
import type { proto } from '@adiwajshing/baileys';
|
||||||
import { WhatsAppMessage } from '@waha/apps/chatwoot/storage';
|
import { WhatsAppMessage } from '@waha/apps/chatwoot/storage';
|
||||||
import { WAHAEngine } from '@waha/structures/enums.dto';
|
import { WAHAEngine } from '@waha/structures/enums.dto';
|
||||||
import { getEngineName } from '@waha/version';
|
import { getEngineName } from '@waha/version';
|
||||||
import { Message as MessageInstance } from 'whatsapp-web.js/src/structures';
|
import { Message as MessageInstance } from 'whatsapp-web.js/src/structures';
|
||||||
|
import { Jid } from '@waha/core/engines/const';
|
||||||
import { isLidUser, isPnUser, toCusFormat } from '@waha/core/utils/jids';
|
import { isLidUser, isPnUser, toCusFormat } from '@waha/core/utils/jids';
|
||||||
|
import { parseMessageIdSerialized } from '@waha/core/utils/ids';
|
||||||
import { WAMessage } from '@waha/structures/responses.dto';
|
import { WAMessage } from '@waha/structures/responses.dto';
|
||||||
import { CallData } from '@waha/structures/calls.dto';
|
import { CallData } from '@waha/structures/calls.dto';
|
||||||
|
import { getContextInfo } from '@waha/core/utils/pwa';
|
||||||
|
|
||||||
|
export interface QuotedMedia {
|
||||||
|
url?: string;
|
||||||
|
directPath: string;
|
||||||
|
mediaKey?: string;
|
||||||
|
mimetype: string;
|
||||||
|
mediaType: string;
|
||||||
|
}
|
||||||
|
|
||||||
interface IEngineHelper {
|
interface IEngineHelper {
|
||||||
ChatID(message: WAMessage | any): string;
|
ChatID(message: WAMessage | any): string;
|
||||||
|
|
||||||
CallChatID(call: CallData | any): string;
|
CallChatID(call: CallData | any): string;
|
||||||
|
|
||||||
|
IsReplyToStatus(
|
||||||
|
message: WAMessage,
|
||||||
|
protoMessage: proto.Message | null,
|
||||||
|
): boolean;
|
||||||
|
|
||||||
WhatsAppMessageKeys(message: any): WhatsAppMessage;
|
WhatsAppMessageKeys(message: any): WhatsAppMessage;
|
||||||
|
|
||||||
IterateMessages<T extends { timestamp: number }>(
|
IterateMessages<T extends { timestamp: number }>(
|
||||||
@@ -23,6 +40,8 @@ interface IEngineHelper {
|
|||||||
FilterChatIdsForMessages(chats: string[]): string[];
|
FilterChatIdsForMessages(chats: string[]): string[];
|
||||||
|
|
||||||
SupportsAllChatForMessage(): boolean;
|
SupportsAllChatForMessage(): boolean;
|
||||||
|
|
||||||
|
ExtractQuotedMedia(replyData: any): QuotedMedia | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
class NOWEBHelper implements IEngineHelper {
|
class NOWEBHelper implements IEngineHelper {
|
||||||
@@ -34,6 +53,14 @@ class NOWEBHelper implements IEngineHelper {
|
|||||||
return call.from;
|
return call.from;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
IsReplyToStatus(
|
||||||
|
message: WAMessage,
|
||||||
|
protoMessage: proto.Message | null,
|
||||||
|
): boolean {
|
||||||
|
void message;
|
||||||
|
return getContextInfo(protoMessage)?.remoteJid === Jid.BROADCAST;
|
||||||
|
}
|
||||||
|
|
||||||
WhatsAppMessageKeys(message: any): WhatsAppMessage {
|
WhatsAppMessageKeys(message: any): WhatsAppMessage {
|
||||||
const timestamp = parseInt(message.messageTimestamp) * 1000;
|
const timestamp = parseInt(message.messageTimestamp) * 1000;
|
||||||
return {
|
return {
|
||||||
@@ -52,7 +79,7 @@ class NOWEBHelper implements IEngineHelper {
|
|||||||
}
|
}
|
||||||
|
|
||||||
FilterChatIdsForMessages(chats: string[]): string[] {
|
FilterChatIdsForMessages(chats: string[]): string[] {
|
||||||
return chats;
|
return preferPnChats(chats);
|
||||||
}
|
}
|
||||||
|
|
||||||
ContactIsMy(contact) {
|
ContactIsMy(contact) {
|
||||||
@@ -62,6 +89,10 @@ class NOWEBHelper implements IEngineHelper {
|
|||||||
SupportsAllChatForMessage(): boolean {
|
SupportsAllChatForMessage(): boolean {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
ExtractQuotedMedia(replyData: any): QuotedMedia | null {
|
||||||
|
return extractProtoQuotedMedia(replyData);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class GOWSHelper implements IEngineHelper {
|
class GOWSHelper implements IEngineHelper {
|
||||||
@@ -73,6 +104,14 @@ class GOWSHelper implements IEngineHelper {
|
|||||||
return call._data?.CallCreator || call.from;
|
return call._data?.CallCreator || call.from;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
IsReplyToStatus(
|
||||||
|
message: WAMessage,
|
||||||
|
protoMessage: proto.Message | null,
|
||||||
|
): boolean {
|
||||||
|
void message;
|
||||||
|
return getContextInfo(protoMessage)?.remoteJid === Jid.BROADCAST;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Parse API response and get the data
|
* Parse API response and get the data
|
||||||
* API Response depends on engine right now
|
* API Response depends on engine right now
|
||||||
@@ -96,7 +135,7 @@ class GOWSHelper implements IEngineHelper {
|
|||||||
}
|
}
|
||||||
|
|
||||||
FilterChatIdsForMessages(chats: string[]): string[] {
|
FilterChatIdsForMessages(chats: string[]): string[] {
|
||||||
return chats;
|
return preferPnChats(chats);
|
||||||
}
|
}
|
||||||
|
|
||||||
SupportsAllChatForMessage(): boolean {
|
SupportsAllChatForMessage(): boolean {
|
||||||
@@ -106,6 +145,10 @@ class GOWSHelper implements IEngineHelper {
|
|||||||
ContactIsMy(contact) {
|
ContactIsMy(contact) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
ExtractQuotedMedia(replyData: any): QuotedMedia | null {
|
||||||
|
return extractProtoQuotedMedia(replyData, true);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class WEBJSHelper implements IEngineHelper {
|
class WEBJSHelper implements IEngineHelper {
|
||||||
@@ -117,6 +160,14 @@ class WEBJSHelper implements IEngineHelper {
|
|||||||
return call.from;
|
return call.from;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
IsReplyToStatus(
|
||||||
|
message: WAMessage,
|
||||||
|
protoMessage: proto.Message | null,
|
||||||
|
): boolean {
|
||||||
|
void protoMessage;
|
||||||
|
return message._data?.quotedRemoteJid === Jid.BROADCAST;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Parse API response and get the data for WEBJS engine
|
* Parse API response and get the data for WEBJS engine
|
||||||
*/
|
*/
|
||||||
@@ -124,7 +175,7 @@ class WEBJSHelper implements IEngineHelper {
|
|||||||
return {
|
return {
|
||||||
timestamp: new Date(message.timestamp * 1000),
|
timestamp: new Date(message.timestamp * 1000),
|
||||||
from_me: message.fromMe,
|
from_me: message.fromMe,
|
||||||
chat_id: message.from,
|
chat_id: message.id.remote,
|
||||||
message_id: message.id.id,
|
message_id: message.id.id,
|
||||||
participant: message.author || null,
|
participant: message.author || null,
|
||||||
};
|
};
|
||||||
@@ -150,17 +201,7 @@ class WEBJSHelper implements IEngineHelper {
|
|||||||
}
|
}
|
||||||
|
|
||||||
FilterChatIdsForMessages(chats: string[]): string[] {
|
FilterChatIdsForMessages(chats: string[]): string[] {
|
||||||
if (chats.length == 2) {
|
return preferPnChats(chats);
|
||||||
const lidChat = chats.find(isLidUser);
|
|
||||||
const cusChat = chats.find(isPnUser);
|
|
||||||
if (lidChat && cusChat) {
|
|
||||||
return [lidChat];
|
|
||||||
}
|
|
||||||
// WEBJS engine merges messages for @lid and @c.us
|
|
||||||
// into single chat, so it's fine to pull only from one
|
|
||||||
}
|
|
||||||
// Otherwise - return the original
|
|
||||||
return chats;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
SupportsAllChatForMessage(): boolean {
|
SupportsAllChatForMessage(): boolean {
|
||||||
@@ -170,6 +211,78 @@ class WEBJSHelper implements IEngineHelper {
|
|||||||
ContactIsMy(contact) {
|
ContactIsMy(contact) {
|
||||||
return contact.isMyContact;
|
return contact.isMyContact;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
ExtractQuotedMedia(replyData: any): QuotedMedia | null {
|
||||||
|
return extractBrowserQuotedMedia(replyData);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class WPPHelper implements IEngineHelper {
|
||||||
|
ChatID(message: WAMessage): string {
|
||||||
|
return toCusFormat(parseMessageIdSerialized(message.id as any).remoteJid);
|
||||||
|
}
|
||||||
|
|
||||||
|
CallChatID(call: CallData): string {
|
||||||
|
return call.from;
|
||||||
|
}
|
||||||
|
|
||||||
|
IsReplyToStatus(
|
||||||
|
message: WAMessage,
|
||||||
|
protoMessage: proto.Message | null,
|
||||||
|
): boolean {
|
||||||
|
void protoMessage;
|
||||||
|
return message._data?.quotedRemoteJid === Jid.BROADCAST;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parse API response and get the data for WPP engine.
|
||||||
|
* WPP returns message.id as a composite string "fromMe_chatId_msgId".
|
||||||
|
*/
|
||||||
|
WhatsAppMessageKeys(message: any): WhatsAppMessage {
|
||||||
|
const parsed = parseMessageIdSerialized(message.id);
|
||||||
|
return {
|
||||||
|
timestamp: new Date(message.timestamp * 1000),
|
||||||
|
from_me: parsed.fromMe,
|
||||||
|
chat_id: toCusFormat(parsed.remoteJid),
|
||||||
|
message_id: parsed.id,
|
||||||
|
participant: message.author || null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* WPP API lacks server-side sorting hooks, so we buffer and sort by the unix timestamp in memory.
|
||||||
|
*/
|
||||||
|
async *IterateMessages<T extends { timestamp: number }>(
|
||||||
|
messages: AsyncGenerator<T>,
|
||||||
|
): AsyncGenerator<T> {
|
||||||
|
const buffer: T[] = [];
|
||||||
|
|
||||||
|
for await (const message of messages) {
|
||||||
|
buffer.push(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
const sorted = lodash.sortBy(buffer, (item) => item.timestamp);
|
||||||
|
|
||||||
|
for (const message of sorted) {
|
||||||
|
yield message;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
FilterChatIdsForMessages(chats: string[]): string[] {
|
||||||
|
return preferPnChats(chats);
|
||||||
|
}
|
||||||
|
|
||||||
|
SupportsAllChatForMessage(): boolean {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
ContactIsMy(contact) {
|
||||||
|
return contact.isMyContact;
|
||||||
|
}
|
||||||
|
|
||||||
|
ExtractQuotedMedia(replyData: any): QuotedMedia | null {
|
||||||
|
return extractBrowserQuotedMedia(replyData);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Choose the right EngineHelper based on getEngineName() function
|
// Choose the right EngineHelper based on getEngineName() function
|
||||||
@@ -185,8 +298,82 @@ switch (getEngineName()) {
|
|||||||
case WAHAEngine.WEBJS:
|
case WAHAEngine.WEBJS:
|
||||||
engineHelper = new WEBJSHelper();
|
engineHelper = new WEBJSHelper();
|
||||||
break;
|
break;
|
||||||
|
case WAHAEngine.WPP:
|
||||||
|
engineHelper = new WPPHelper();
|
||||||
|
break;
|
||||||
default:
|
default:
|
||||||
engineHelper = new WEBJSHelper(); // Default to WEBJS as it's the default engine
|
engineHelper = new WEBJSHelper(); // Default to WEBJS as it's the default engine
|
||||||
}
|
}
|
||||||
|
|
||||||
export const EngineHelper = engineHelper;
|
export const EngineHelper = engineHelper;
|
||||||
|
|
||||||
|
//
|
||||||
|
// Quoted media extraction helpers
|
||||||
|
//
|
||||||
|
|
||||||
|
function extractProtoQuotedMedia(
|
||||||
|
replyData: any,
|
||||||
|
capitalUrl = false,
|
||||||
|
): QuotedMedia | null {
|
||||||
|
if (!replyData) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const mediaTypes: Array<[string, string]> = [
|
||||||
|
['imageMessage', 'image'],
|
||||||
|
['videoMessage', 'video'],
|
||||||
|
['audioMessage', 'audio'],
|
||||||
|
];
|
||||||
|
for (const [key, mediaType] of mediaTypes) {
|
||||||
|
const msg = replyData[key];
|
||||||
|
if (!msg) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const url: string | undefined = capitalUrl ? msg.URL ?? msg.url : msg.url;
|
||||||
|
const directPath: string = msg.directPath;
|
||||||
|
const mimetype: string = msg.mimetype;
|
||||||
|
if (!directPath || !mimetype) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
url: url,
|
||||||
|
directPath: directPath,
|
||||||
|
mediaKey: msg.mediaKey,
|
||||||
|
mimetype: mimetype,
|
||||||
|
mediaType: mediaType,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function extractBrowserQuotedMedia(replyData: any): QuotedMedia | null {
|
||||||
|
if (!replyData) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const kind: string = replyData.kind ?? replyData.type;
|
||||||
|
if (kind !== 'image' && kind !== 'video' && kind !== 'audio') {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const directPath: string = replyData.directPath;
|
||||||
|
const mimetype: string = replyData.mimetype;
|
||||||
|
if (!directPath || !mimetype) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
url: replyData.deprecatedMms3Url,
|
||||||
|
directPath: directPath,
|
||||||
|
mediaKey: replyData.mediaKey,
|
||||||
|
mimetype: mimetype,
|
||||||
|
mediaType: kind,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function preferPnChats(chats: string[]): string[] {
|
||||||
|
const unique = lodash.uniq(chats ?? []);
|
||||||
|
const hasPn = unique.some(isPnUser);
|
||||||
|
const hasLid = unique.some(isLidUser);
|
||||||
|
if (hasPn && hasLid) {
|
||||||
|
// Prefer @c.us / phone chats when both formats exist to avoid duplicate fetches.
|
||||||
|
return unique.filter(isPnUser);
|
||||||
|
}
|
||||||
|
return unique;
|
||||||
|
}
|
||||||
@@ -1,3 +1,5 @@
|
|||||||
import { EngineHelper } from './engines';
|
import { EngineHelper } from './engines';
|
||||||
|
import type { QuotedMedia } from './engines';
|
||||||
|
|
||||||
export { EngineHelper };
|
export { EngineHelper };
|
||||||
|
export type { QuotedMedia };
|
||||||
@@ -5,3 +5,15 @@ export function getEngineName(): string {
|
|||||||
// If not set - use WEBJS
|
// If not set - use WEBJS
|
||||||
return process.env.WHATSAPP_DEFAULT_ENGINE || WAHAEngine.WEBJS;
|
return process.env.WHATSAPP_DEFAULT_ENGINE || WAHAEngine.WEBJS;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function getNamespace(): string {
|
||||||
|
// Controls the prefix used for the main database and folder (non-session data)
|
||||||
|
// If not set - falls back to engine name for backward compatibility
|
||||||
|
return (process.env.WAHA_NAMESPACE || getEngineName()).toLowerCase();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getSessionNamespace(): string {
|
||||||
|
// Controls the prefix used for session databases and folders
|
||||||
|
// If not set - falls back to engine name for backward compatibility
|
||||||
|
return (process.env.WAHA_SESSION_NAMESPACE || getEngineName()).toLowerCase();
|
||||||
|
}
|
||||||
@@ -1,38 +0,0 @@
|
|||||||
import { Body, Controller, Delete, Param, Put, UsePipes } from '@nestjs/common';
|
|
||||||
import { ApiOperation, ApiSecurity, ApiTags } from '@nestjs/swagger';
|
|
||||||
import { WhatsappSession } from '@waha/core/abc/session.abc';
|
|
||||||
import { ChatIdApiParam } from '@waha/nestjs/params/ChatIdApiParam';
|
|
||||||
import {
|
|
||||||
SessionApiParam,
|
|
||||||
WorkingSessionParam,
|
|
||||||
} from '@waha/nestjs/params/SessionApiParam';
|
|
||||||
import { WAHAValidationPipe } from '@waha/nestjs/pipes/WAHAValidationPipe';
|
|
||||||
|
|
||||||
import { SessionManager } from './core/abc/manager.abc';
|
|
||||||
import { Result } from './structures/base.dto';
|
|
||||||
import { ContactUpdateBody } from './structures/contacts.dto';
|
|
||||||
|
|
||||||
@ApiSecurity('api_key')
|
|
||||||
@Controller('api/:session/contacts')
|
|
||||||
@ApiTags('👤 Contacts')
|
|
||||||
export class ContactsSessionController {
|
|
||||||
constructor(private manager: SessionManager) {}
|
|
||||||
|
|
||||||
@Put('/:chatId')
|
|
||||||
@SessionApiParam
|
|
||||||
@ChatIdApiParam
|
|
||||||
@ApiOperation({
|
|
||||||
summary: 'Create or update contact',
|
|
||||||
description:
|
|
||||||
'Create or update contact on the phone address book. May not work if you have installed many WhatsApp apps on the same phone',
|
|
||||||
})
|
|
||||||
@UsePipes(new WAHAValidationPipe())
|
|
||||||
async put(
|
|
||||||
@WorkingSessionParam session: WhatsappSession,
|
|
||||||
@Param('chatId') chatId: string,
|
|
||||||
@Body() body: ContactUpdateBody,
|
|
||||||
): Promise<Result> {
|
|
||||||
await session.upsertContact(chatId, body);
|
|
||||||
return { success: true };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -74,15 +74,14 @@ export class SwaggerConfiguratorCore {
|
|||||||
.setExternalDoc(this.title, this.externalDocUrl)
|
.setExternalDoc(this.title, this.externalDocUrl)
|
||||||
.setVersion(VERSION.version)
|
.setVersion(VERSION.version)
|
||||||
.addTag('🖥️ Sessions', 'Control WhatsApp sessions (accounts)')
|
.addTag('🖥️ Sessions', 'Control WhatsApp sessions (accounts)')
|
||||||
.addTag('🧩 Apps', 'Applications (built-in integrations)')
|
.addTag('📱 Pairing', 'Pair a session with WhatsApp on your phone.')
|
||||||
.addTag('🔑 Auth', 'Authentication')
|
|
||||||
.addTag('🆔 Profile', 'Your profile information')
|
.addTag('🆔 Profile', 'Your profile information')
|
||||||
.addTag('🖼️ Screenshot', 'Get screenshot of WhatsApp and show QR code')
|
|
||||||
.addTag('📤 Chatting', 'Chatting methods')
|
.addTag('📤 Chatting', 'Chatting methods')
|
||||||
.addTag('📞 Calls', 'Call handling methods')
|
.addTag('✅ Presence', `Presence information`)
|
||||||
.addTag('📢 Channels', 'Channels (newsletters) methods')
|
.addTag('📢 Channels', 'Channels (newsletters) methods')
|
||||||
.addTag('🟢 Status', 'Status (aka stories) methods')
|
.addTag('🟢 Status', 'Status (aka stories) methods')
|
||||||
.addTag('💬 Chats', `Chats methods`)
|
.addTag('💬 Chats', `Chats methods`)
|
||||||
|
.addTag('🔑 Api Keys', 'API Keys management')
|
||||||
.addTag(
|
.addTag(
|
||||||
'👤 Contacts',
|
'👤 Contacts',
|
||||||
`Contacts methods.<br>
|
`Contacts methods.<br>
|
||||||
@@ -90,13 +89,14 @@ export class SwaggerConfiguratorCore {
|
|||||||
'E.g: \`12312312310\` OR \`12312312310@c.us\`<br>`,
|
'E.g: \`12312312310\` OR \`12312312310@c.us\`<br>`,
|
||||||
)
|
)
|
||||||
.addTag('👥 Groups', `Groups methods.<br>`)
|
.addTag('👥 Groups', `Groups methods.<br>`)
|
||||||
.addTag('✅ Presence', `Presence information`)
|
.addTag('📞 Calls', 'Call handling methods')
|
||||||
.addTag('📅 Events', `Event Message`)
|
.addTag('📅 Events', `Event Message`)
|
||||||
.addTag(
|
.addTag(
|
||||||
'🏷️ Labels',
|
'🏷️ Labels',
|
||||||
'Labels - available only for WhatsApp Business accounts',
|
'Labels - available only for WhatsApp Business accounts',
|
||||||
)
|
)
|
||||||
.addTag('🖼️ Media', 'Media methods')
|
.addTag('🖼️ Media', 'Media methods')
|
||||||
|
.addTag('🧩 Apps', 'Applications (built-in integrations)')
|
||||||
.addTag('🔍 Observability', 'Other methods')
|
.addTag('🔍 Observability', 'Other methods')
|
||||||
.addTag('🗄️ Storage', 'Storage methods')
|
.addTag('🗄️ Storage', 'Storage methods')
|
||||||
.addApiKey({
|
.addApiKey({
|
||||||
@@ -195,6 +195,8 @@ export class SwaggerConfiguratorCore {
|
|||||||
'/ping',
|
'/ping',
|
||||||
'/ws',
|
'/ws',
|
||||||
'/webhooks/',
|
'/webhooks/',
|
||||||
|
'/jobs',
|
||||||
|
'/jobs/',
|
||||||
...config.getExcludedFullPaths(),
|
...config.getExcludedFullPaths(),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
|||||||
@@ -36,6 +36,7 @@ import {
|
|||||||
import { ISessionAuthRepository } from '../storage/ISessionAuthRepository';
|
import { ISessionAuthRepository } from '../storage/ISessionAuthRepository';
|
||||||
import { ISessionConfigRepository } from '../storage/ISessionConfigRepository';
|
import { ISessionConfigRepository } from '../storage/ISessionConfigRepository';
|
||||||
import { WhatsappSession } from './session.abc';
|
import { WhatsappSession } from './session.abc';
|
||||||
|
import { IApiKeyRepository } from '@waha/core/storage/IApiKeyRepository';
|
||||||
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||||
const AsyncLock = require('async-lock');
|
const AsyncLock = require('async-lock');
|
||||||
@@ -48,6 +49,7 @@ export abstract class SessionManager
|
|||||||
public sessionConfigRepository: ISessionConfigRepository;
|
public sessionConfigRepository: ISessionConfigRepository;
|
||||||
protected sessionMeRepository: ISessionMeRepository;
|
protected sessionMeRepository: ISessionMeRepository;
|
||||||
protected sessionWorkerRepository: ISessionWorkerRepository;
|
protected sessionWorkerRepository: ISessionWorkerRepository;
|
||||||
|
public apiKeyRepository: IApiKeyRepository;
|
||||||
private lock: any;
|
private lock: any;
|
||||||
|
|
||||||
WAIT_SESSION_RUNNING_INTERVAL = 500;
|
WAIT_SESSION_RUNNING_INTERVAL = 500;
|
||||||
|
|||||||
@@ -1,3 +1,6 @@
|
|||||||
|
import {
|
||||||
|
getBrowserExecutablePath as getBrowserExecutablePathAutodetect,
|
||||||
|
} from '@waha/core/abc/session.browser';
|
||||||
import {
|
import {
|
||||||
CoreMediaConverter,
|
CoreMediaConverter,
|
||||||
IMediaConverter,
|
IMediaConverter,
|
||||||
@@ -142,15 +145,6 @@ const qrcode = require('qrcode-terminal');
|
|||||||
|
|
||||||
axiosRetry(axios, { retries: 3 });
|
axiosRetry(axios, { retries: 3 });
|
||||||
|
|
||||||
const CHROME_PATH = '/usr/bin/google-chrome-stable';
|
|
||||||
const CHROMIUM_PATH = '/usr/bin/chromium';
|
|
||||||
|
|
||||||
export function getBrowserExecutablePath() {
|
|
||||||
if (fs.existsSync(CHROME_PATH)) {
|
|
||||||
return CHROME_PATH;
|
|
||||||
}
|
|
||||||
return CHROMIUM_PATH;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function ensureSuffix(phone) {
|
export function ensureSuffix(phone) {
|
||||||
const suffix = '@c.us';
|
const suffix = '@c.us';
|
||||||
@@ -360,7 +354,7 @@ export abstract class WhatsappSession {
|
|||||||
}
|
}
|
||||||
|
|
||||||
getBrowserExecutablePath() {
|
getBrowserExecutablePath() {
|
||||||
return getBrowserExecutablePath();
|
return getBrowserExecutablePathAutodetect();
|
||||||
}
|
}
|
||||||
|
|
||||||
getBrowserArgsForPuppeteer() {
|
getBrowserArgsForPuppeteer() {
|
||||||
@@ -381,6 +375,7 @@ export abstract class WhatsappSession {
|
|||||||
'--disable-default-apps',
|
'--disable-default-apps',
|
||||||
'--disable-dev-shm-usage',
|
'--disable-dev-shm-usage',
|
||||||
'--disable-extensions',
|
'--disable-extensions',
|
||||||
|
'--disable-metrics',
|
||||||
// '--disable-features=site-per-process', // COMMENTED to test WEBJS stability
|
// '--disable-features=site-per-process', // COMMENTED to test WEBJS stability
|
||||||
'--disable-gpu', // COMMENTED to test WEBJS stability
|
'--disable-gpu', // COMMENTED to test WEBJS stability
|
||||||
'--disable-offer-store-unmasked-wallet-cards',
|
'--disable-offer-store-unmasked-wallet-cards',
|
||||||
|
|||||||
@@ -0,0 +1,42 @@
|
|||||||
|
import * as fs from 'fs';
|
||||||
|
|
||||||
|
//
|
||||||
|
// Browser executable path detection
|
||||||
|
//
|
||||||
|
|
||||||
|
// Ordered: Chrome paths first, then Chromium.
|
||||||
|
// Windows: only global Program Files paths (no per-user %LOCALAPPDATA%).
|
||||||
|
const BROWSER_PATHS: Record<string, string[]> = {
|
||||||
|
darwin: [
|
||||||
|
'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
|
||||||
|
'/Applications/Chromium.app/Contents/MacOS/Chromium',
|
||||||
|
],
|
||||||
|
win32: [
|
||||||
|
'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe',
|
||||||
|
'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe',
|
||||||
|
'C:\\Program Files\\Chromium\\Application\\chrome.exe',
|
||||||
|
],
|
||||||
|
linux: [
|
||||||
|
'/usr/bin/google-chrome',
|
||||||
|
'/usr/bin/google-chrome-stable',
|
||||||
|
'/usr/bin/chromium',
|
||||||
|
'/usr/bin/chromium-browser',
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
export function getBrowserExecutablePath(): string {
|
||||||
|
const paths = BROWSER_PATHS[process.platform] ?? BROWSER_PATHS['linux'];
|
||||||
|
for (const p of paths) {
|
||||||
|
if (fs.existsSync(p)) {
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return paths[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
// A path belongs to Google Chrome when it contains "google" in any casing.
|
||||||
|
// All Chrome paths include "Google" (macOS/Windows) or "google-chrome" (Linux),
|
||||||
|
// while Chromium paths never do.
|
||||||
|
export function isChromeExecutablePath(executablePath: string): boolean {
|
||||||
|
return executablePath.toLowerCase().includes('google');
|
||||||
|
}
|
||||||
@@ -9,18 +9,20 @@ import { ServeStaticModule } from '@nestjs/serve-static';
|
|||||||
import { TerminusModule } from '@nestjs/terminus';
|
import { TerminusModule } from '@nestjs/terminus';
|
||||||
import { ChannelsController } from '@waha/api/channels.controller';
|
import { ChannelsController } from '@waha/api/channels.controller';
|
||||||
import { LidsController } from '@waha/api/lids.controller';
|
import { LidsController } from '@waha/api/lids.controller';
|
||||||
|
import { ApiKeysController } from '@waha/api/apikeys.controller';
|
||||||
import { ProfileController } from '@waha/api/profile.controller';
|
import { ProfileController } from '@waha/api/profile.controller';
|
||||||
import { ServerController } from '@waha/api/server.controller';
|
import { ServerController } from '@waha/api/server.controller';
|
||||||
import { ServerDebugController } from '@waha/api/server.debug.controller';
|
import { ServerDebugController } from '@waha/api/server.debug.controller';
|
||||||
import { WebsocketGatewayCore } from '@waha/api/websocket.gateway.core';
|
import { WebsocketGatewayCore } from '@waha/api/websocket.gateway.core';
|
||||||
import { AppsModuleExports } from '@waha/apps/apps.module';
|
import { AppsModuleExports } from '@waha/apps/apps.module';
|
||||||
import { ContactsSessionController } from '@waha/contacts.session.controller';
|
import { ContactsSessionController } from '@waha/api/contacts.session.controller';
|
||||||
import { ApiKeyStrategy } from '@waha/core/auth/apiKey.strategy';
|
import { ApiKeyStrategy } from '@waha/core/auth/apiKey.strategy';
|
||||||
import { IApiKeyAuth } from '@waha/core/auth/auth';
|
import { IApiKeyAuth } from '@waha/core/auth/auth';
|
||||||
import { AuthMiddleware } from '@waha/core/auth/auth.middleware';
|
import { ApiKeyAuthMiddleware } from '@waha/core/auth/api-key-auth.middleware';
|
||||||
import { BasicAuthFunction } from '@waha/core/auth/basicAuth';
|
import { BasicAuthFunction } from '@waha/core/auth/basicAuth';
|
||||||
import { WebSocketAuth } from '@waha/core/auth/WebSocketAuth';
|
import { WebSocketAuth } from '@waha/core/auth/WebSocketAuth';
|
||||||
import { GowsEngineConfigService } from '@waha/core/config/GowsEngineConfigService';
|
import { GowsEngineConfigService } from '@waha/core/config/GowsEngineConfigService';
|
||||||
|
import { WPPEngineConfigService } from '@waha/core/config/WPPEngineConfigService';
|
||||||
import { WebJSEngineConfigService } from '@waha/core/config/WebJSEngineConfigService';
|
import { WebJSEngineConfigService } from '@waha/core/config/WebJSEngineConfigService';
|
||||||
import { MediaLocalStorageModule } from '@waha/core/media/local/media.local.storage.module';
|
import { MediaLocalStorageModule } from '@waha/core/media/local/media.local.storage.module';
|
||||||
import { MediaLocalStorageConfig } from '@waha/core/media/local/MediaLocalStorageConfig';
|
import { MediaLocalStorageConfig } from '@waha/core/media/local/MediaLocalStorageConfig';
|
||||||
@@ -64,6 +66,9 @@ import { EngineConfigService } from './config/EngineConfigService';
|
|||||||
import { SwaggerConfigServiceCore } from './config/SwaggerConfigServiceCore';
|
import { SwaggerConfigServiceCore } from './config/SwaggerConfigServiceCore';
|
||||||
import { WAHAHealthCheckServiceCore } from './health/WAHAHealthCheckServiceCore';
|
import { WAHAHealthCheckServiceCore } from './health/WAHAHealthCheckServiceCore';
|
||||||
import { SessionManagerCore } from './manager.core';
|
import { SessionManagerCore } from './manager.core';
|
||||||
|
import { CaslAbilityFactory } from '@waha/core/auth/casl.ability';
|
||||||
|
import { PoliciesGuard } from '@waha/core/auth/policies.guard';
|
||||||
|
import { ApiKeyService } from '@waha/core/auth/ApiKeyService';
|
||||||
|
|
||||||
export const IMPORTS_CORE = [
|
export const IMPORTS_CORE = [
|
||||||
...AppsModuleExports.imports,
|
...AppsModuleExports.imports,
|
||||||
@@ -140,6 +145,7 @@ const IMPORTS = [...IMPORTS_CORE, ...IMPORTS_MEDIA];
|
|||||||
|
|
||||||
export const CONTROLLERS = [
|
export const CONTROLLERS = [
|
||||||
AuthController,
|
AuthController,
|
||||||
|
ApiKeysController,
|
||||||
SessionsController,
|
SessionsController,
|
||||||
ProfileController,
|
ProfileController,
|
||||||
ChattingController,
|
ChattingController,
|
||||||
@@ -171,6 +177,7 @@ export const PROVIDERS_BASE: Provider[] = [
|
|||||||
DashboardConfigServiceCore,
|
DashboardConfigServiceCore,
|
||||||
SwaggerConfigServiceCore,
|
SwaggerConfigServiceCore,
|
||||||
WebJSEngineConfigService,
|
WebJSEngineConfigService,
|
||||||
|
WPPEngineConfigService,
|
||||||
GowsEngineConfigService,
|
GowsEngineConfigService,
|
||||||
WhatsappConfigService,
|
WhatsappConfigService,
|
||||||
EngineConfigService,
|
EngineConfigService,
|
||||||
@@ -178,6 +185,9 @@ export const PROVIDERS_BASE: Provider[] = [
|
|||||||
MediaLocalStorageConfig,
|
MediaLocalStorageConfig,
|
||||||
WebSocketAuth,
|
WebSocketAuth,
|
||||||
ApiKeyStrategy,
|
ApiKeyStrategy,
|
||||||
|
ApiKeyService,
|
||||||
|
CaslAbilityFactory,
|
||||||
|
PoliciesGuard,
|
||||||
{
|
{
|
||||||
provide: IApiKeyAuth,
|
provide: IApiKeyAuth,
|
||||||
useFactory: ApiKeyAuthFactory,
|
useFactory: ApiKeyAuthFactory,
|
||||||
@@ -234,11 +244,15 @@ export class AppModuleCore {
|
|||||||
}
|
}
|
||||||
|
|
||||||
configure(consumer: MiddlewareConsumer) {
|
configure(consumer: MiddlewareConsumer) {
|
||||||
|
// Because we use ServeStaticModule, we need to inject a middleware
|
||||||
|
// ServeStaticModule does not support @UseGuards
|
||||||
const exclude = this.config.getExcludedPaths();
|
const exclude = this.config.getExcludedPaths();
|
||||||
consumer
|
consumer
|
||||||
.apply(AuthMiddleware)
|
.apply(ApiKeyAuthMiddleware)
|
||||||
.exclude(...exclude)
|
.exclude(...exclude)
|
||||||
.forRoutes('api', 'health', 'ws');
|
.forRoutes('api', 'health');
|
||||||
|
|
||||||
|
// Dashboard
|
||||||
const dashboardCredentials = this.dashboardConfig.credentials;
|
const dashboardCredentials = this.dashboardConfig.credentials;
|
||||||
if (dashboardCredentials) {
|
if (dashboardCredentials) {
|
||||||
const username = dashboardCredentials[0];
|
const username = dashboardCredentials[0];
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { User } from '@waha/core/auth/apiKey.strategy';
|
||||||
|
import { SessionManager } from '@waha/core/abc/manager.abc';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class ApiKeyService {
|
||||||
|
constructor(private manager: SessionManager) {}
|
||||||
|
|
||||||
|
async get(apikey: string): Promise<User | null> {
|
||||||
|
if (!apikey) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const key = await this.manager.apiKeyRepository.getActiveByKey(apikey);
|
||||||
|
if (!key) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
isAdmin: key.isAdmin,
|
||||||
|
session: key.session,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
Loaded 100 of 189 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user