mirror of
https://github.com/EvolutionAPI/evolution-api.git
synced 2025-12-10 18:39:38 -06:00
Compare commits
186 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cd800f2976 | ||
|
|
4f642e17a7 | ||
|
|
afa6d633c6 | ||
|
|
2e3e752719 | ||
|
|
de11e6f9ca | ||
|
|
26e7eefe51 | ||
|
|
b55c9fcab7 | ||
|
|
86b194af5f | ||
|
|
3c1573c400 | ||
|
|
178386594c | ||
|
|
cea1fa0979 | ||
|
|
38be0b49d9 | ||
|
|
04ac880fcc | ||
|
|
3864366e75 | ||
|
|
2756d7e61c | ||
|
|
bb36bfe424 | ||
|
|
6277c5d084 | ||
|
|
b1d77019f5 | ||
|
|
8d5c7d875e | ||
|
|
abd0351f8f | ||
|
|
c7a2aa51ee | ||
|
|
bbf60e30b0 | ||
|
|
2408384b0f | ||
|
|
250ddd2e89 | ||
|
|
bee309cd28 | ||
|
|
92c2ace7bc | ||
|
|
faed3f4574 | ||
|
|
baff4e8f5e | ||
|
|
1c3a7ab027 | ||
|
|
338cc93cfc | ||
|
|
930d32df3a | ||
|
|
fa6b5c28a6 | ||
|
|
8e7f348c12 | ||
|
|
5c58cb7eae | ||
|
|
879bee962b | ||
|
|
af47b859e4 | ||
|
|
1c61116a3e | ||
|
|
13f96a366b | ||
|
|
08a4795016 | ||
|
|
53a94af3f7 | ||
|
|
302e219f7f | ||
|
|
1e036ba3ae | ||
|
|
377993e4b0 | ||
|
|
689f347457 | ||
|
|
7743063439 | ||
|
|
f5e43a3b3f | ||
|
|
ea88edd512 | ||
|
|
e6a9ed92ce | ||
|
|
8707520a3e | ||
|
|
d3e3c458a0 | ||
|
|
067f0999b5 | ||
|
|
179af3f41c | ||
|
|
31a6f2d92e | ||
|
|
dc72f01625 | ||
|
|
3b139078c3 | ||
|
|
f2c2a6a64a | ||
|
|
e5a249109c | ||
|
|
73fb376602 | ||
|
|
27633aad53 | ||
|
|
06543e89e5 | ||
|
|
90640b7cee | ||
|
|
da8774caa2 | ||
|
|
4ae3139163 | ||
|
|
f4043a9141 | ||
|
|
139ad9b3cb | ||
|
|
fca39a2b34 | ||
|
|
1e3a23588e | ||
|
|
27be03ea95 | ||
|
|
9b73252f35 | ||
|
|
71322cd8f6 | ||
|
|
263854db47 | ||
|
|
400b6291a2 | ||
|
|
feff038446 | ||
|
|
4d2a189905 | ||
|
|
48625a739c | ||
|
|
b6620d2bd6 | ||
|
|
45e461e757 | ||
|
|
be5760905e | ||
|
|
92626fa559 | ||
|
|
1aaad541ad | ||
|
|
3b0432dd9f | ||
|
|
a95c843e77 | ||
|
|
8d1151d0a0 | ||
|
|
a1393b679c | ||
|
|
5cbc163716 | ||
|
|
a84faaa575 | ||
|
|
503cbfb21c | ||
|
|
40281871c8 | ||
|
|
85868b3439 | ||
|
|
066e060b86 | ||
|
|
c555048783 | ||
|
|
2d14c8849b | ||
|
|
df20c5fc93 | ||
|
|
3818313161 | ||
|
|
4a38e505f4 | ||
|
|
d5f5b8325e | ||
|
|
1ad51a434b | ||
|
|
3454bec79f | ||
|
|
8c27f11f5b | ||
|
|
ae9f3efeff | ||
|
|
ba3a2fae59 | ||
|
|
aa0d793d26 | ||
|
|
48bda1b5af | ||
|
|
dd21a29ea6 | ||
|
|
e83a7e2e88 | ||
|
|
d58d0b8bff | ||
|
|
4efc9b65bc | ||
|
|
cd71ff503d | ||
|
|
582166e5ae | ||
|
|
e1ae03c1e4 | ||
|
|
0737c45df2 | ||
|
|
adbe1079d5 | ||
|
|
423f629b04 | ||
|
|
946dcaeb2e | ||
|
|
d48fbc3a4e | ||
|
|
cdf06666a1 | ||
|
|
5254928887 | ||
|
|
8468690d37 | ||
|
|
bdd9257c47 | ||
|
|
d6834c8741 | ||
|
|
164beddb39 | ||
|
|
4991f1dc37 | ||
|
|
1b1e3b3e9d | ||
|
|
563ca2dd22 | ||
|
|
4e44bfb222 | ||
|
|
9edd600513 | ||
|
|
501b06d133 | ||
|
|
dc530285d5 | ||
|
|
8775cdf036 | ||
|
|
6ad33df879 | ||
|
|
633d0b4c45 | ||
|
|
82c0eadf7c | ||
|
|
1756abf1e6 | ||
|
|
a2f48030dc | ||
|
|
3214a9fb5b | ||
|
|
4b89e3f987 | ||
|
|
72622dca31 | ||
|
|
d73b72b67e | ||
|
|
20eef33df3 | ||
|
|
37571c03b4 | ||
|
|
017949458b | ||
|
|
2feaf1c74e | ||
|
|
4b043cb4b8 | ||
|
|
b0d261b305 | ||
|
|
c041986e26 | ||
|
|
0976109d27 | ||
|
|
b808dda33b | ||
|
|
98b7f15a43 | ||
|
|
94ddc0dfbe | ||
|
|
d4b0cfd2ba | ||
|
|
a5a46dc72a | ||
|
|
e13434804c | ||
|
|
53cd7d5d13 | ||
|
|
bedfb019aa | ||
|
|
6e1d027750 | ||
|
|
fb1fa4d91a | ||
|
|
57ea6707bc | ||
|
|
ad8df44236 | ||
|
|
c132379b3a | ||
|
|
f7862637b1 | ||
|
|
0d8e8bc0fb | ||
|
|
b62917e80f | ||
|
|
eeb324227b | ||
|
|
c31b62fb3d | ||
|
|
22465c0a56 | ||
|
|
da6f1bd540 | ||
|
|
069786b9fe | ||
|
|
bd0c43feac | ||
|
|
5dc1d02d0a | ||
|
|
8697329f71 | ||
|
|
58b5561f72 | ||
|
|
093515555d | ||
|
|
d8268b0eb1 | ||
|
|
4585850741 | ||
|
|
6c150eed6d | ||
|
|
f0c6300599 | ||
|
|
24c339343f | ||
|
|
ddbaf2335a | ||
|
|
20c8a2ff0e | ||
|
|
e623269a18 | ||
|
|
0363fa979d | ||
|
|
b640329cf8 | ||
|
|
f72b1f7717 | ||
|
|
ed4c8868a0 | ||
|
|
06081f6502 | ||
|
|
8e51ae63ae |
2
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
2
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
@ -59,7 +59,7 @@ body:
|
||||
value: |
|
||||
- OS: [e.g. Ubuntu 20.04, Windows 10, macOS 12.0]
|
||||
- Node.js version: [e.g. 18.17.0]
|
||||
- Evolution API version: [e.g. 2.3.4]
|
||||
- Evolution API version: [e.g. 2.3.7]
|
||||
- Database: [e.g. PostgreSQL 14, MySQL 8.0]
|
||||
- Connection type: [e.g. Baileys, WhatsApp Business API]
|
||||
validations:
|
||||
|
||||
2
.github/workflows/check_code_quality.yml
vendored
2
.github/workflows/check_code_quality.yml
vendored
@ -13,6 +13,8 @@ jobs:
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
with:
|
||||
submodules: recursive
|
||||
|
||||
- name: Install Node
|
||||
uses: actions/setup-node@v5
|
||||
|
||||
2
.github/workflows/publish_docker_image.yml
vendored
2
.github/workflows/publish_docker_image.yml
vendored
@ -15,6 +15,8 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
submodules: recursive
|
||||
|
||||
- name: Docker meta
|
||||
id: meta
|
||||
|
||||
@ -15,6 +15,8 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
submodules: recursive
|
||||
|
||||
- name: Docker meta
|
||||
id: meta
|
||||
|
||||
@ -15,6 +15,8 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
submodules: recursive
|
||||
|
||||
- name: Docker meta
|
||||
id: meta
|
||||
|
||||
4
.github/workflows/security.yml
vendored
4
.github/workflows/security.yml
vendored
@ -26,6 +26,8 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
submodules: recursive
|
||||
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@v3
|
||||
@ -47,5 +49,7 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout Repository
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
submodules: recursive
|
||||
- name: Dependency Review
|
||||
uses: actions/dependency-review-action@v4
|
||||
|
||||
220
CHANGELOG.md
220
CHANGELOG.md
@ -1,3 +1,223 @@
|
||||
# 2.3.7 (2025-12-05)
|
||||
|
||||
### Features
|
||||
|
||||
* **WhatsApp Business Meta Templates**: Add update and delete endpoints for Meta templates
|
||||
- New endpoints to edit and delete WhatsApp Business templates
|
||||
- Added DTOs and validation schemas for template management
|
||||
- Enhanced template lifecycle management capabilities
|
||||
|
||||
* **Events API**: Add isLatest and progress to messages.set event
|
||||
- Allows consumers to know when history sync is complete (isLatest=true)
|
||||
- Track sync progress percentage through webhooks
|
||||
- Added extra field to EmitData type for additional payload properties
|
||||
- Updated all event controllers (webhook, rabbitmq, sqs, websocket, pusher, kafka, nats)
|
||||
|
||||
* **N8N Integration**: Add quotedMessage to payload in sendMessageToBot
|
||||
- Support for quoted messages in N8N chatbot integration
|
||||
- Enhanced message context information
|
||||
|
||||
* **WebSocket**: Add wildcard "*" to allow all hosts to connect via websocket
|
||||
- More flexible host configuration for WebSocket connections
|
||||
- Improved host validation logic in WebsocketController
|
||||
|
||||
* **Pix Support**: Handle interactive button message for pix
|
||||
- Support for interactive Pix button messages
|
||||
- Enhanced payment flow integration
|
||||
|
||||
### Fixed
|
||||
|
||||
* **Baileys Message Processor**: Fix incoming message events not working after reconnection
|
||||
- Added cleanup logic in mount() to prevent memory leaks from multiple subscriptions
|
||||
- Recreate messageSubject if it was completed during logout
|
||||
- Remount messageProcessor in connectToWhatsapp() to ensure subscription is active
|
||||
- Fixed issue where onDestroy() calls complete() on RxJS Subject, making it permanently closed
|
||||
- Ensures old subscriptions are properly cleaned up before creating new ones
|
||||
|
||||
* **Baileys Authentication**: Resolve "waiting for message" state after reconnection
|
||||
- Fixed Redis keys not being properly removed during instance logout
|
||||
- Prevented loading of old/invalid cryptographic keys on reconnection
|
||||
- Fixed blocking state where instances authenticate but cannot send messages
|
||||
- Ensures new credentials (creds) are properly used after reconnection
|
||||
|
||||
* **OnWhatsapp Cache**: Prevent unique constraint errors and optimize database writes
|
||||
- Fixed `Unique constraint failed on the fields: (remoteJid)` error when sending to groups
|
||||
- Refactored query to use OR condition finding by jidOptions or remoteJid
|
||||
- Added deep comparison to skip unnecessary database updates
|
||||
- Replaced sequential processing with Promise.allSettled for parallel execution
|
||||
- Sorted JIDs alphabetically in jidOptions for accurate change detection
|
||||
- Added normalizeJid helper function for cleaner code
|
||||
|
||||
* **Proxy Integration**: Fix "Media upload failed on all hosts" error when using proxy
|
||||
- Created makeProxyAgentUndici() for Undici-compatible proxy agents
|
||||
- Fixed compatibility with Node.js 18+ native fetch() implementation
|
||||
- Replaced traditional HttpsProxyAgent/SocksProxyAgent with Undici ProxyAgent
|
||||
- Maintained legacy makeProxyAgent() for Axios compatibility
|
||||
- Fixed protocol handling in makeProxyAgent to prevent undefined errors
|
||||
|
||||
* **WhatsApp Business API**: Fix base64, filename and caption handling
|
||||
- Corrected base64 media conversion in Business API
|
||||
- Fixed filename handling for document messages
|
||||
- Improved caption processing for media messages
|
||||
- Enhanced remoteJid validation and processing
|
||||
|
||||
* **Chat Service**: Fix fetchChats and message panel errors
|
||||
- Fixed cleanMessageData errors in Manager message panel
|
||||
- Improved chat fetching reliability
|
||||
- Enhanced message data sanitization
|
||||
|
||||
* **Contact Filtering**: Apply where filters correctly in findContacts endpoint
|
||||
- Fixed endpoint to process all where clause fields (id, remoteJid, pushName)
|
||||
- Previously only processed remoteJid field, ignoring other filters
|
||||
- Added remoteJid field to contactValidateSchema for proper validation
|
||||
- Maintained multi-tenant isolation with instanceId filtering
|
||||
- Allows filtering contacts by any supported field instead of returning all contacts
|
||||
|
||||
* **Chatwoot and Baileys Integration**: Multiple integration improvements
|
||||
- Enhanced code formatting and consistency
|
||||
- Fixed integration issues between Chatwoot and Baileys services
|
||||
- Improved message handling and delivery
|
||||
|
||||
* **Baileys Message Loss**: Prevent message loss from WhatsApp stub placeholders
|
||||
- Fixed messages being lost and not saved to database, especially for channels/newsletters (@lid)
|
||||
- Detects WhatsApp stubs through messageStubParameters containing 'Message absent from node'
|
||||
- Prevents adding stubs to duplicate message cache
|
||||
- Allows real message to be processed when it arrives after decryption
|
||||
- Maintains stub discard to avoid saving empty placeholders
|
||||
|
||||
* **Database Contacts**: Respect DATABASE_SAVE_DATA_CONTACTS in contact updates
|
||||
- Added missing conditional checks for DATABASE_SAVE_DATA_CONTACTS configuration
|
||||
- Fixed profile picture updates attempting to save when database save is disabled
|
||||
- Fixed unawaited promise in contacts.upsert handler
|
||||
|
||||
* **Prisma/PostgreSQL**: Add unique constraint to Chat model
|
||||
- Generated migration to add unique index on instanceId and remoteJid
|
||||
- Added deduplication step before creating index to prevent constraint violations
|
||||
- Prevents chat duplication in database
|
||||
|
||||
* **MinIO Upload**: Handle messageContextInfo in media upload to prevent MinIO errors
|
||||
- Prevents errors when uploading media with messageContextInfo metadata
|
||||
- Improved error handling for media storage operations
|
||||
|
||||
* **Typebot**: Fix message routing for @lid JIDs
|
||||
- Typebot now responds to messages from JIDs ending with @lid
|
||||
- Maintains complete JID for @lid instead of extracting only number
|
||||
- Fixed condition: `remoteJid.includes('@lid') ? remoteJid : remoteJid.split('@')[0]`
|
||||
- Handles both @s.whatsapp.net and @lid message formats
|
||||
|
||||
* **Message Filtering**: Unify remoteJid filtering using OR with remoteJidAlt
|
||||
- Improved message filtering with alternative JID support
|
||||
- Better handling of messages with different JID formats
|
||||
|
||||
* **@lid Integration**: Multiple fixes for @lid problems, message events and chatwoot errors
|
||||
- Reorganized imports and improved message handling in BaileysStartupService
|
||||
- Enhanced remoteJid processing to handle @lid cases
|
||||
- Improved jid normalization and type safety in Chatwoot integration
|
||||
- Streamlined message handling logic and cache management
|
||||
- Refactored message handling and polling updates with decryption logic for poll votes
|
||||
- Improved event processing flow for various message types
|
||||
|
||||
* **Chatwoot Contacts**: Fix contact duplication error on import
|
||||
- Resolved 'ON CONFLICT DO UPDATE command cannot affect row a second time' error
|
||||
- Removed attempt to update identifier field in conflict (part of constraint)
|
||||
- Changed to update only updated_at field: `updated_at = NOW()`
|
||||
- Allows duplicate contacts to be updated correctly without errors
|
||||
|
||||
* **Chatwoot Service**: Fix async handling in update_last_seen method
|
||||
- Added missing await for chatwootRequest in read message processing
|
||||
- Prevents service failure when processing read messages
|
||||
|
||||
* **Metrics Access**: Fix IP validation including x-forwarded-for
|
||||
- Uses all IPs including x-forwarded-for header when checking metrics access
|
||||
- Improved security and access control for metrics endpoint
|
||||
|
||||
### Dependencies
|
||||
|
||||
* **Baileys**: Updated to version 7.0.0-rc.9
|
||||
- Latest release candidate with multiple improvements and bug fixes
|
||||
|
||||
* **AWS SDK**: Updated packages to version 3.936.0
|
||||
- Enhanced functionality and compatibility
|
||||
- Performance improvements
|
||||
|
||||
### Code Quality & Refactoring
|
||||
|
||||
* **Template Management**: Remove unused template edit/delete DTOs after refactoring
|
||||
* **Proxy Utilities**: Improve makeProxyAgent for Undici compatibility
|
||||
* **Code Formatting**: Enhance code formatting and consistency across services
|
||||
* **BaileysStartupService**: Fix indentation and remove unnecessary blank lines
|
||||
* **Event Controllers**: Guard extra spread and prevent core field override in all event controllers
|
||||
* **Import Organization**: Reorganize imports for better code structure and maintainability
|
||||
|
||||
# 2.3.6 (2025-10-21)
|
||||
|
||||
### Features
|
||||
|
||||
* **Baileys, Chatwoot, OnWhatsapp Cache**: Multiple implementations and fixes
|
||||
- Fixed cache for PN, LID and g.us numbers to send correct number
|
||||
- Fixed audio and document sending via Chatwoot in Baileys channel
|
||||
- Multiple fixes in Chatwoot integration
|
||||
- Fixed ignored messages when receiving leads
|
||||
|
||||
### Fixed
|
||||
|
||||
* **Baileys**: Fix buffer storage in database
|
||||
- Correctly save Uint8Array values to database
|
||||
* **Baileys**: Simplify logging of messageSent object
|
||||
- Fixed "this.isZero not is function" error
|
||||
|
||||
### Chore
|
||||
|
||||
* **Version**: Bump version to 2.3.6 and update Baileys dependency to 7.0.0-rc.6
|
||||
* **Workflows**: Update checkout step to include submodules
|
||||
- Added 'submodules: recursive' option to checkout step in multiple workflow files to ensure submodules are properly initialized during CI/CD processes
|
||||
* **Manager**: Update asset files and install process
|
||||
- Updated subproject reference in evolution-manager-v2 to the latest commit
|
||||
- Enhanced the manager_install.sh script to include npm install and build steps
|
||||
- Replaced old JavaScript asset file with a new version for improved performance
|
||||
- Added a new CSS file for consistent styling across the application
|
||||
|
||||
# 2.3.5 (2025-10-15)
|
||||
|
||||
### Features
|
||||
|
||||
* **Chatwoot Enhancements**: Comprehensive improvements to message handling, editing, deletion and i18n
|
||||
* **Participants Data**: Add participantsData field maintaining backward compatibility for group participants
|
||||
* **LID to Phone Number**: Convert LID to phoneNumber on group participants
|
||||
* **Docker Configurations**: Add Kafka and frontend services to Docker configurations
|
||||
|
||||
### Fixed
|
||||
|
||||
* **Kafka Migration**: Fixed PostgreSQL migration error for Kafka integration
|
||||
- Corrected table reference from `"public"."Instance"` to `"Instance"` in foreign key constraint
|
||||
- Fixed `ERROR: relation "public.Instance" does not exist` issue in migration `20250918182355_add_kafka_integration`
|
||||
- Aligned table naming convention with other Evolution API migrations for consistency
|
||||
- Resolved database migration failure that prevented Kafka integration setup
|
||||
* **Update Baileys Version**: v7.0.0-rc.5 with compatibility fixes
|
||||
- Fixed assertSessions signature compatibility using type assertion
|
||||
- Fixed incompatibility in voice call (wavoip) with new Baileys version
|
||||
- Handle undefined status in update by defaulting to 'DELETED'
|
||||
* **Chatwoot Improvements**: Multiple fixes for enhanced reliability
|
||||
- Correct chatId extraction for non-group JIDs
|
||||
- Resolve webhook timeout on deletion with 5+ images
|
||||
- Improve error handling in Chatwoot messages
|
||||
- Adjust conversation verification logic and cache
|
||||
- Optimize conversation reopening logic and connection notification
|
||||
- Fix conversation reopening and connection loop
|
||||
* **Baileys Message Handling**: Enhanced message processing
|
||||
- Add warning log for messages not found
|
||||
- Fix message verification in Baileys service
|
||||
- Simplify linkPreview handling in BaileysStartupService
|
||||
* **Media Validation**: Fix media content validation
|
||||
* **PostgreSQL Connection**: Refactor connection with PostgreSQL and improve message handling
|
||||
|
||||
### Code Quality & Refactoring
|
||||
|
||||
* **Exponential Backoff**: Implement exponential backoff patterns and extract magic numbers to constants
|
||||
* **TypeScript Build**: Update TypeScript build process and dependencies
|
||||
|
||||
###
|
||||
|
||||
# 2.3.4 (2025-09-23)
|
||||
|
||||
### Features
|
||||
|
||||
51
Docker/kafka/docker-compose.yaml
Normal file
51
Docker/kafka/docker-compose.yaml
Normal file
@ -0,0 +1,51 @@
|
||||
version: '3.3'
|
||||
|
||||
services:
|
||||
zookeeper:
|
||||
container_name: zookeeper
|
||||
image: confluentinc/cp-zookeeper:7.5.0
|
||||
environment:
|
||||
- ZOOKEEPER_CLIENT_PORT=2181
|
||||
- ZOOKEEPER_TICK_TIME=2000
|
||||
- ZOOKEEPER_SYNC_LIMIT=2
|
||||
volumes:
|
||||
- zookeeper_data:/var/lib/zookeeper/
|
||||
ports:
|
||||
- 2181:2181
|
||||
|
||||
kafka:
|
||||
container_name: kafka
|
||||
image: confluentinc/cp-kafka:7.5.0
|
||||
depends_on:
|
||||
- zookeeper
|
||||
environment:
|
||||
- KAFKA_BROKER_ID=1
|
||||
- KAFKA_ZOOKEEPER_CONNECT=zookeeper:2181
|
||||
- KAFKA_LISTENER_SECURITY_PROTOCOL_MAP=PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT,OUTSIDE:PLAINTEXT
|
||||
- KAFKA_ADVERTISED_LISTENERS=PLAINTEXT://kafka:29092,PLAINTEXT_HOST://localhost:9092,OUTSIDE://host.docker.internal:9094
|
||||
- KAFKA_INTER_BROKER_LISTENER_NAME=PLAINTEXT
|
||||
- KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR=1
|
||||
- KAFKA_TRANSACTION_STATE_LOG_MIN_ISR=1
|
||||
- KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR=1
|
||||
- KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS=0
|
||||
- KAFKA_AUTO_CREATE_TOPICS_ENABLE=true
|
||||
- KAFKA_LOG_RETENTION_HOURS=168
|
||||
- KAFKA_LOG_SEGMENT_BYTES=1073741824
|
||||
- KAFKA_LOG_RETENTION_CHECK_INTERVAL_MS=300000
|
||||
- KAFKA_COMPRESSION_TYPE=gzip
|
||||
ports:
|
||||
- 29092:29092
|
||||
- 9092:9092
|
||||
- 9094:9094
|
||||
volumes:
|
||||
- kafka_data:/var/lib/kafka/data
|
||||
|
||||
volumes:
|
||||
zookeeper_data:
|
||||
kafka_data:
|
||||
|
||||
|
||||
networks:
|
||||
evolution-net:
|
||||
name: evolution-net
|
||||
driver: bridge
|
||||
@ -2,7 +2,7 @@ version: "3.7"
|
||||
|
||||
services:
|
||||
evolution_v2:
|
||||
image: evoapicloud/evolution-api:v2.3.1
|
||||
image: evoapicloud/evolution-api:v2.3.7
|
||||
volumes:
|
||||
- evolution_instances:/evolution/instances
|
||||
networks:
|
||||
|
||||
@ -15,6 +15,16 @@ services:
|
||||
expose:
|
||||
- 8080
|
||||
|
||||
frontend:
|
||||
container_name: evolution_frontend
|
||||
image: evolution/manager:local
|
||||
build: ./evolution-manager-v2
|
||||
restart: always
|
||||
ports:
|
||||
- "3000:80"
|
||||
networks:
|
||||
- evolution-net
|
||||
|
||||
volumes:
|
||||
evolution_instances:
|
||||
|
||||
|
||||
@ -20,6 +20,15 @@ services:
|
||||
expose:
|
||||
- "8080"
|
||||
|
||||
frontend:
|
||||
container_name: evolution_frontend
|
||||
image: evoapicloud/evolution-manager:latest
|
||||
restart: always
|
||||
ports:
|
||||
- "3000:80"
|
||||
networks:
|
||||
- evolution-net
|
||||
|
||||
redis:
|
||||
container_name: evolution_redis
|
||||
image: redis:latest
|
||||
|
||||
@ -1 +1 @@
|
||||
Subproject commit fcb38dd407b89697b7a7154cfd873f76729e6ece
|
||||
Subproject commit f054b9bc28083152d4948f835e3346fd0add39db
|
||||
BIN
manager/dist/assets/images/evolution-logo.png
vendored
BIN
manager/dist/assets/images/evolution-logo.png
vendored
Binary file not shown.
|
Before Width: | Height: | Size: 17 KiB After Width: | Height: | Size: 25 KiB |
485
manager/dist/assets/index-CO3NSIFj.js
vendored
Normal file
485
manager/dist/assets/index-CO3NSIFj.js
vendored
Normal file
File diff suppressed because one or more lines are too long
461
manager/dist/assets/index-DJ2Q5K8k.js
vendored
461
manager/dist/assets/index-DJ2Q5K8k.js
vendored
File diff suppressed because one or more lines are too long
1
manager/dist/assets/index-DsIrum0U.css
vendored
Normal file
1
manager/dist/assets/index-DsIrum0U.css
vendored
Normal file
File diff suppressed because one or more lines are too long
1
manager/dist/assets/index-DxAxQfZR.css
vendored
1
manager/dist/assets/index-DxAxQfZR.css
vendored
File diff suppressed because one or more lines are too long
4
manager/dist/index.html
vendored
4
manager/dist/index.html
vendored
@ -5,8 +5,8 @@
|
||||
<link rel="icon" type="image/png" href="https://evolution-api.com/files/evo/favicon.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Evolution Manager</title>
|
||||
<script type="module" crossorigin src="/assets/index-DJ2Q5K8k.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/assets/index-DxAxQfZR.css">
|
||||
<script type="module" crossorigin src="/assets/index-CO3NSIFj.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/assets/index-DsIrum0U.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
|
||||
8
manager_install.sh
Executable file
8
manager_install.sh
Executable file
@ -0,0 +1,8 @@
|
||||
#! /bin/bash
|
||||
|
||||
cd evolution-manager-v2
|
||||
npm install
|
||||
npm run build
|
||||
cd ..
|
||||
rm -rf manager/dist
|
||||
cp -r evolution-manager-v2/dist manager/dist
|
||||
5305
package-lock.json
generated
5305
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "evolution-api",
|
||||
"version": "2.3.4",
|
||||
"version": "2.3.7",
|
||||
"description": "Rest api for communication with WhatsApp",
|
||||
"main": "./dist/main.js",
|
||||
"type": "commonjs",
|
||||
@ -56,7 +56,7 @@
|
||||
"eslint --fix"
|
||||
],
|
||||
"src/**/*.ts": [
|
||||
"sh -c 'npm run build'"
|
||||
"sh -c 'tsc --noEmit'"
|
||||
]
|
||||
},
|
||||
"config": {
|
||||
@ -77,7 +77,7 @@
|
||||
"amqplib": "^0.10.5",
|
||||
"audio-decode": "^2.2.3",
|
||||
"axios": "^1.7.9",
|
||||
"baileys": "^7.0.0-rc.3",
|
||||
"baileys": "7.0.0-rc.9",
|
||||
"class-validator": "^0.14.1",
|
||||
"compression": "^1.7.5",
|
||||
"cors": "^2.8.5",
|
||||
@ -90,12 +90,14 @@
|
||||
"fluent-ffmpeg": "^2.1.3",
|
||||
"form-data": "^4.0.1",
|
||||
"https-proxy-agent": "^7.0.6",
|
||||
"fetch-socks": "^1.3.2",
|
||||
"i18next": "^23.7.19",
|
||||
"jimp": "^1.6.0",
|
||||
"json-schema": "^0.4.0",
|
||||
"jsonschema": "^1.4.1",
|
||||
"jsonwebtoken": "^9.0.2",
|
||||
"kafkajs": "^2.2.4",
|
||||
"libphonenumber-js": "^1.12.25",
|
||||
"link-preview-js": "^3.0.13",
|
||||
"long": "^5.2.3",
|
||||
"mediainfo.js": "^0.3.4",
|
||||
@ -121,6 +123,7 @@
|
||||
"socks-proxy-agent": "^8.0.5",
|
||||
"swagger-ui-express": "^5.0.1",
|
||||
"tsup": "^8.3.5",
|
||||
"undici": "^7.16.0",
|
||||
"uuid": "^13.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
-- CreateTable
|
||||
CREATE TABLE "public"."Kafka" (
|
||||
CREATE TABLE "Kafka" (
|
||||
"id" TEXT NOT NULL,
|
||||
"enabled" BOOLEAN NOT NULL DEFAULT false,
|
||||
"events" JSONB NOT NULL,
|
||||
@ -11,7 +11,7 @@ CREATE TABLE "public"."Kafka" (
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "Kafka_instanceId_key" ON "public"."Kafka"("instanceId");
|
||||
CREATE UNIQUE INDEX "Kafka_instanceId_key" ON "Kafka"("instanceId");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "public"."Kafka" ADD CONSTRAINT "Kafka_instanceId_fkey" FOREIGN KEY ("instanceId") REFERENCES "public"."Instance"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
ALTER TABLE "Kafka" ADD CONSTRAINT "Kafka_instanceId_fkey" FOREIGN KEY ("instanceId") REFERENCES "Instance"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
@ -0,0 +1,16 @@
|
||||
-- 1. Cleanup: Remove duplicate chats, keeping the most recently updated one
|
||||
DELETE FROM "Chat"
|
||||
WHERE id IN (
|
||||
SELECT id FROM (
|
||||
SELECT id,
|
||||
ROW_NUMBER() OVER (
|
||||
PARTITION BY "instanceId", "remoteJid"
|
||||
ORDER BY "updatedAt" DESC
|
||||
) as row_num
|
||||
FROM "Chat"
|
||||
) t
|
||||
WHERE t.row_num > 1
|
||||
);
|
||||
|
||||
-- 2. Create the unique index (Constraint)
|
||||
CREATE UNIQUE INDEX "Chat_instanceId_remoteJid_key" ON "Chat"("instanceId", "remoteJid");
|
||||
@ -132,6 +132,7 @@ model Chat {
|
||||
instanceId String
|
||||
unreadMessages Int @default(0)
|
||||
|
||||
@@unique([instanceId, remoteJid])
|
||||
@@index([instanceId])
|
||||
@@index([remoteJid])
|
||||
}
|
||||
|
||||
@ -92,6 +92,15 @@ export class InstanceController {
|
||||
instanceId: instanceId,
|
||||
});
|
||||
|
||||
const instanceDto: InstanceDto = {
|
||||
instanceName: instance.instanceName,
|
||||
instanceId: instance.instanceId,
|
||||
connectionStatus:
|
||||
typeof instance.connectionStatus === 'string'
|
||||
? instance.connectionStatus
|
||||
: instance.connectionStatus?.state || 'unknown',
|
||||
};
|
||||
|
||||
if (instanceData.proxyHost && instanceData.proxyPort && instanceData.proxyProtocol) {
|
||||
const testProxy = await this.proxyService.testProxy({
|
||||
host: instanceData.proxyHost,
|
||||
@ -103,8 +112,7 @@ export class InstanceController {
|
||||
if (!testProxy) {
|
||||
throw new BadRequestException('Invalid proxy');
|
||||
}
|
||||
|
||||
await this.proxyService.createProxy(instance, {
|
||||
await this.proxyService.createProxy(instanceDto, {
|
||||
enabled: true,
|
||||
host: instanceData.proxyHost,
|
||||
port: instanceData.proxyPort,
|
||||
@ -125,7 +133,7 @@ export class InstanceController {
|
||||
wavoipToken: instanceData.wavoipToken || '',
|
||||
};
|
||||
|
||||
await this.settingsService.create(instance, settings);
|
||||
await this.settingsService.create(instanceDto, settings);
|
||||
|
||||
let webhookWaBusiness = null,
|
||||
accessTokenWaBusiness = '';
|
||||
@ -155,7 +163,10 @@ export class InstanceController {
|
||||
integration: instanceData.integration,
|
||||
webhookWaBusiness,
|
||||
accessTokenWaBusiness,
|
||||
status: instance.connectionStatus.state,
|
||||
status:
|
||||
typeof instance.connectionStatus === 'string'
|
||||
? instance.connectionStatus
|
||||
: instance.connectionStatus?.state || 'unknown',
|
||||
},
|
||||
hash,
|
||||
webhook: {
|
||||
@ -217,7 +228,7 @@ export class InstanceController {
|
||||
const urlServer = this.configService.get<HttpServer>('SERVER').URL;
|
||||
|
||||
try {
|
||||
this.chatwootService.create(instance, {
|
||||
this.chatwootService.create(instanceDto, {
|
||||
enabled: true,
|
||||
accountId: instanceData.chatwootAccountId,
|
||||
token: instanceData.chatwootToken,
|
||||
@ -246,7 +257,10 @@ export class InstanceController {
|
||||
integration: instanceData.integration,
|
||||
webhookWaBusiness,
|
||||
accessTokenWaBusiness,
|
||||
status: instance.connectionStatus.state,
|
||||
status:
|
||||
typeof instance.connectionStatus === 'string'
|
||||
? instance.connectionStatus
|
||||
: instance.connectionStatus?.state || 'unknown',
|
||||
},
|
||||
hash,
|
||||
webhook: {
|
||||
@ -338,20 +352,38 @@ export class InstanceController {
|
||||
throw new BadRequestException('The "' + instanceName + '" instance does not exist');
|
||||
}
|
||||
|
||||
if (state == 'close') {
|
||||
if (state === 'close') {
|
||||
throw new BadRequestException('The "' + instanceName + '" instance is not connected');
|
||||
} else if (state == 'open') {
|
||||
}
|
||||
this.logger.info(`Restarting instance: ${instanceName}`);
|
||||
|
||||
if (typeof instance.restart === 'function') {
|
||||
await instance.restart();
|
||||
// Wait a bit for the reconnection to be established
|
||||
await new Promise((r) => setTimeout(r, 2000));
|
||||
return {
|
||||
instance: {
|
||||
instanceName: instanceName,
|
||||
status: instance.connectionStatus?.state || 'connecting',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Fallback for Baileys (uses different mechanism)
|
||||
if (state === 'open' || state === 'connecting') {
|
||||
if (this.configService.get<Chatwoot>('CHATWOOT').ENABLED) instance.clearCacheChatwoot();
|
||||
this.logger.info('restarting instance' + instanceName);
|
||||
|
||||
instance.client?.ws?.close();
|
||||
instance.client?.end(new Error('restart'));
|
||||
return await this.connectToWhatsapp({ instanceName });
|
||||
} else if (state == 'connecting') {
|
||||
instance.client?.ws?.close();
|
||||
instance.client?.end(new Error('restart'));
|
||||
return await this.connectToWhatsapp({ instanceName });
|
||||
}
|
||||
|
||||
return {
|
||||
instance: {
|
||||
instanceName: instanceName,
|
||||
status: state,
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
this.logger.error(error);
|
||||
return { error: true, message: error.toString() };
|
||||
@ -409,7 +441,7 @@ export class InstanceController {
|
||||
}
|
||||
|
||||
try {
|
||||
this.waMonitor.waInstances[instanceName]?.logoutInstance();
|
||||
await this.waMonitor.waInstances[instanceName]?.logoutInstance();
|
||||
|
||||
return { status: 'SUCCESS', error: false, response: { message: 'Instance logged out' } };
|
||||
} catch (error) {
|
||||
|
||||
@ -12,4 +12,15 @@ export class TemplateController {
|
||||
public async findTemplate(instance: InstanceDto) {
|
||||
return this.templateService.find(instance);
|
||||
}
|
||||
|
||||
public async editTemplate(
|
||||
instance: InstanceDto,
|
||||
data: { templateId: string; category?: string; components?: any; allowCategoryChange?: boolean; ttl?: number },
|
||||
) {
|
||||
return this.templateService.edit(instance, data);
|
||||
}
|
||||
|
||||
public async deleteTemplate(instance: InstanceDto, data: { name: string; hsmId?: string }) {
|
||||
return this.templateService.delete(instance, data);
|
||||
}
|
||||
}
|
||||
|
||||
@ -12,6 +12,7 @@ export class InstanceDto extends IntegrationDto {
|
||||
token?: string;
|
||||
status?: string;
|
||||
ownerJid?: string;
|
||||
connectionStatus?: string;
|
||||
profileName?: string;
|
||||
profilePicUrl?: string;
|
||||
// settings
|
||||
|
||||
@ -6,3 +6,16 @@ export class TemplateDto {
|
||||
components: any;
|
||||
webhookUrl?: string;
|
||||
}
|
||||
|
||||
export class TemplateEditDto {
|
||||
templateId: string;
|
||||
category?: 'AUTHENTICATION' | 'MARKETING' | 'UTILITY';
|
||||
allowCategoryChange?: boolean;
|
||||
ttl?: number;
|
||||
components?: any;
|
||||
}
|
||||
|
||||
export class TemplateDeleteDto {
|
||||
name: string;
|
||||
hsmId?: string;
|
||||
}
|
||||
|
||||
@ -16,6 +16,7 @@ import { Events, wa } from '@api/types/wa.types';
|
||||
import { AudioConverter, Chatwoot, ConfigService, Openai, S3 } from '@config/env.config';
|
||||
import { BadRequestException, InternalServerErrorException } from '@exceptions';
|
||||
import { createJid } from '@utils/createJid';
|
||||
import { sendTelemetry } from '@utils/sendTelemetry';
|
||||
import axios from 'axios';
|
||||
import { isBase64, isURL } from 'class-validator';
|
||||
import EventEmitter2 from 'eventemitter2';
|
||||
@ -171,6 +172,8 @@ export class EvolutionStartupService extends ChannelStartupService {
|
||||
|
||||
this.logger.log(messageRaw);
|
||||
|
||||
sendTelemetry(`received.message.${messageRaw.messageType ?? 'unknown'}`);
|
||||
|
||||
this.sendDataWebhook(Events.MESSAGES_UPSERT, messageRaw);
|
||||
|
||||
await chatbotController.emit({
|
||||
|
||||
@ -24,6 +24,7 @@ import { AudioConverter, Chatwoot, ConfigService, Database, Openai, S3, WaBusine
|
||||
import { BadRequestException, InternalServerErrorException } from '@exceptions';
|
||||
import { createJid } from '@utils/createJid';
|
||||
import { status } from '@utils/renderStatus';
|
||||
import { sendTelemetry } from '@utils/sendTelemetry';
|
||||
import axios from 'axios';
|
||||
import { arrayUnique, isURL } from 'class-validator';
|
||||
import EventEmitter2 from 'eventemitter2';
|
||||
@ -515,7 +516,9 @@ export class BusinessStartupService extends ChannelStartupService {
|
||||
const mediaUrl = await s3Service.getObjectUrl(fullName);
|
||||
|
||||
messageRaw.message.mediaUrl = mediaUrl;
|
||||
messageRaw.message.base64 = buffer.data.toString('base64');
|
||||
if (this.localWebhook.enabled && this.localWebhook.webhookBase64) {
|
||||
messageRaw.message.base64 = buffer.data.toString('base64');
|
||||
}
|
||||
|
||||
// Processar OpenAI speech-to-text para áudio após o mediaUrl estar disponível
|
||||
if (this.configService.get<Openai>('OPENAI').ENABLED && mediaType === 'audio') {
|
||||
@ -553,11 +556,19 @@ export class BusinessStartupService extends ChannelStartupService {
|
||||
this.logger.error(['Error on upload file to minio', error?.message, error?.stack]);
|
||||
}
|
||||
} else {
|
||||
const buffer = await this.downloadMediaMessage(received?.messages[0]);
|
||||
messageRaw.message.base64 = buffer.toString('base64');
|
||||
if (this.localWebhook.enabled && this.localWebhook.webhookBase64) {
|
||||
const buffer = await this.downloadMediaMessage(received?.messages[0]);
|
||||
messageRaw.message.base64 = buffer.toString('base64');
|
||||
}
|
||||
|
||||
// Processar OpenAI speech-to-text para áudio mesmo sem S3
|
||||
if (this.configService.get<Openai>('OPENAI').ENABLED && message.type === 'audio') {
|
||||
let openAiBase64 = messageRaw.message.base64;
|
||||
if (!openAiBase64) {
|
||||
const buffer = await this.downloadMediaMessage(received?.messages[0]);
|
||||
openAiBase64 = buffer.toString('base64');
|
||||
}
|
||||
|
||||
const openAiDefaultSettings = await this.prismaRepository.openaiSetting.findFirst({
|
||||
where: {
|
||||
instanceId: this.instanceId,
|
||||
@ -573,7 +584,7 @@ export class BusinessStartupService extends ChannelStartupService {
|
||||
openAiDefaultSettings.OpenaiCreds,
|
||||
{
|
||||
message: {
|
||||
base64: messageRaw.message.base64,
|
||||
base64: openAiBase64,
|
||||
...messageRaw,
|
||||
},
|
||||
},
|
||||
@ -655,6 +666,8 @@ export class BusinessStartupService extends ChannelStartupService {
|
||||
|
||||
this.logger.log(messageRaw);
|
||||
|
||||
sendTelemetry(`received.message.${messageRaw.messageType ?? 'unknown'}`);
|
||||
|
||||
this.sendDataWebhook(Events.MESSAGES_UPSERT, messageRaw);
|
||||
|
||||
await chatbotController.emit({
|
||||
@ -1013,6 +1026,7 @@ export class BusinessStartupService extends ChannelStartupService {
|
||||
[message['mediaType']]: {
|
||||
[message['type']]: message['id'],
|
||||
...(message['mediaType'] !== 'audio' &&
|
||||
message['mediaType'] !== 'video' &&
|
||||
message['fileName'] &&
|
||||
!isImage && { filename: message['fileName'] }),
|
||||
...(message['mediaType'] !== 'audio' && message['caption'] && { caption: message['caption'] }),
|
||||
@ -1603,9 +1617,14 @@ export class BusinessStartupService extends ChannelStartupService {
|
||||
const messageType = msg.messageType.includes('Message') ? msg.messageType : msg.messageType + 'Message';
|
||||
const mediaMessage = msg.message[messageType];
|
||||
|
||||
if (!msg.message?.base64) {
|
||||
const buffer = await this.downloadMediaMessage({ type: messageType, ...msg.message });
|
||||
msg.message.base64 = buffer.toString('base64');
|
||||
}
|
||||
|
||||
return {
|
||||
mediaType: msg.messageType,
|
||||
fileName: mediaMessage?.fileName,
|
||||
fileName: mediaMessage?.fileName || mediaMessage?.filename,
|
||||
caption: mediaMessage?.caption,
|
||||
size: {
|
||||
fileLength: mediaMessage?.fileLength,
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
import { Logger } from '@config/logger.config';
|
||||
import { BaileysEventMap, MessageUpsertType, proto } from 'baileys';
|
||||
import { BaileysEventMap, MessageUpsertType, WAMessage } from 'baileys';
|
||||
import { catchError, concatMap, delay, EMPTY, from, retryWhen, Subject, Subscription, take, tap } from 'rxjs';
|
||||
|
||||
type MessageUpsertPayload = BaileysEventMap['messages.upsert'];
|
||||
@ -12,13 +12,29 @@ export class BaileysMessageProcessor {
|
||||
private subscription?: Subscription;
|
||||
|
||||
protected messageSubject = new Subject<{
|
||||
messages: proto.IWebMessageInfo[];
|
||||
messages: WAMessage[];
|
||||
type: MessageUpsertType;
|
||||
requestId?: string;
|
||||
settings: any;
|
||||
}>();
|
||||
|
||||
mount({ onMessageReceive }: MountProps) {
|
||||
// Se já existe subscription, fazer cleanup primeiro
|
||||
if (this.subscription && !this.subscription.closed) {
|
||||
this.subscription.unsubscribe();
|
||||
}
|
||||
|
||||
// Se o Subject foi completado, recriar
|
||||
if (this.messageSubject.closed) {
|
||||
this.processorLogs.warn('MessageSubject was closed, recreating...');
|
||||
this.messageSubject = new Subject<{
|
||||
messages: WAMessage[];
|
||||
type: MessageUpsertType;
|
||||
requestId?: string;
|
||||
settings: any;
|
||||
}>();
|
||||
}
|
||||
|
||||
this.subscription = this.messageSubject
|
||||
.pipe(
|
||||
tap(({ messages }) => {
|
||||
|
||||
@ -71,7 +71,7 @@ export const useVoiceCallsBaileys = async (
|
||||
|
||||
socket.on('assertSessions', async (jids, force, callback) => {
|
||||
try {
|
||||
const response = await baileys_sock.assertSessions(jids, force);
|
||||
const response = await baileys_sock.assertSessions(jids);
|
||||
|
||||
callback(response);
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -211,7 +211,7 @@ export abstract class BaseChatbotService<BotType = any, SettingsType = any> {
|
||||
try {
|
||||
if (mediaType === 'audio') {
|
||||
await instance.audioWhatsapp({
|
||||
number: remoteJid.split('@')[0],
|
||||
number: remoteJid.includes('@lid') ? remoteJid : remoteJid.split('@')[0],
|
||||
delay: (settings as any)?.delayMessage || 1000,
|
||||
audio: url,
|
||||
caption: altText,
|
||||
@ -219,7 +219,7 @@ export abstract class BaseChatbotService<BotType = any, SettingsType = any> {
|
||||
} else {
|
||||
await instance.mediaMessage(
|
||||
{
|
||||
number: remoteJid.split('@')[0],
|
||||
number: remoteJid.includes('@lid') ? remoteJid : remoteJid.split('@')[0],
|
||||
delay: (settings as any)?.delayMessage || 1000,
|
||||
mediatype: mediaType,
|
||||
media: url,
|
||||
@ -290,7 +290,7 @@ export abstract class BaseChatbotService<BotType = any, SettingsType = any> {
|
||||
setTimeout(async () => {
|
||||
await instance.textMessage(
|
||||
{
|
||||
number: remoteJid.split('@')[0],
|
||||
number: remoteJid.includes('@lid') ? remoteJid : remoteJid.split('@')[0],
|
||||
delay: settings?.delayMessage || 1000,
|
||||
text: message,
|
||||
linkPreview,
|
||||
|
||||
@ -1,10 +1,6 @@
|
||||
import { InstanceDto } from '@api/dto/instance.dto';
|
||||
import { ChatwootDto } from '@api/integrations/chatbot/chatwoot/dto/chatwoot.dto';
|
||||
import { ChatwootService } from '@api/integrations/chatbot/chatwoot/services/chatwoot.service';
|
||||
import { PrismaRepository } from '@api/repository/repository.service';
|
||||
import { waMonitor } from '@api/server.module';
|
||||
import { CacheService } from '@api/services/cache.service';
|
||||
import { CacheEngine } from '@cache/cacheengine';
|
||||
import { Chatwoot, ConfigService, HttpServer } from '@config/env.config';
|
||||
import { BadRequestException } from '@exceptions';
|
||||
import { isURL } from 'class-validator';
|
||||
@ -13,7 +9,6 @@ export class ChatwootController {
|
||||
constructor(
|
||||
private readonly chatwootService: ChatwootService,
|
||||
private readonly configService: ConfigService,
|
||||
private readonly prismaRepository: PrismaRepository,
|
||||
) {}
|
||||
|
||||
public async createChatwoot(instance: InstanceDto, data: ChatwootDto) {
|
||||
@ -84,9 +79,6 @@ export class ChatwootController {
|
||||
public async receiveWebhook(instance: InstanceDto, data: any) {
|
||||
if (!this.configService.get<Chatwoot>('CHATWOOT').ENABLED) throw new BadRequestException('Chatwoot is disabled');
|
||||
|
||||
const chatwootCache = new CacheService(new CacheEngine(this.configService, ChatwootService.name).getEngine());
|
||||
const chatwootService = new ChatwootService(waMonitor, this.configService, this.prismaRepository, chatwootCache);
|
||||
|
||||
return chatwootService.receiveWebhook(instance, data);
|
||||
return this.chatwootService.receiveWebhook(instance, data);
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,6 +1,5 @@
|
||||
import { InstanceDto } from '@api/dto/instance.dto';
|
||||
import { Options, Quoted, SendAudioDto, SendMediaDto, SendTextDto } from '@api/dto/sendMessage.dto';
|
||||
import { ExtendedMessageKey } from '@api/integrations/channel/whatsapp/whatsapp.baileys.service';
|
||||
import { ChatwootDto } from '@api/integrations/chatbot/chatwoot/dto/chatwoot.dto';
|
||||
import { postgresClient } from '@api/integrations/chatbot/chatwoot/libs/postgres.client';
|
||||
import { chatwootImport } from '@api/integrations/chatbot/chatwoot/utils/chatwoot-import-helper';
|
||||
@ -24,10 +23,11 @@ import { Chatwoot as ChatwootModel, Contact as ContactModel, Message as MessageM
|
||||
import i18next from '@utils/i18n';
|
||||
import { sendTelemetry } from '@utils/sendTelemetry';
|
||||
import axios from 'axios';
|
||||
import { proto } from 'baileys';
|
||||
import { WAMessageContent, WAMessageKey } from 'baileys';
|
||||
import dayjs from 'dayjs';
|
||||
import FormData from 'form-data';
|
||||
import { Jimp, JimpMime } from 'jimp';
|
||||
import { parsePhoneNumberFromString } from 'libphonenumber-js';
|
||||
import Long from 'long';
|
||||
import mimeTypes from 'mime-types';
|
||||
import path from 'path';
|
||||
@ -44,6 +44,9 @@ interface ChatwootMessage {
|
||||
export class ChatwootService {
|
||||
private readonly logger = new Logger('ChatwootService');
|
||||
|
||||
// Lock polling delay
|
||||
private readonly LOCK_POLLING_DELAY_MS = 300; // Delay between lock status checks
|
||||
|
||||
private provider: any;
|
||||
|
||||
constructor(
|
||||
@ -343,6 +346,16 @@ export class ChatwootService {
|
||||
|
||||
return contact;
|
||||
} catch (error) {
|
||||
if ((error.status === 422 || error.response?.status === 422) && jid) {
|
||||
this.logger.warn(`Contact with identifier ${jid} creation failed (422). Checking if it already exists...`);
|
||||
const existingContact = await this.findContactByIdentifier(instance, jid);
|
||||
if (existingContact) {
|
||||
const contactId = existingContact.id;
|
||||
await this.addLabelToContact(this.provider.nameInbox, contactId);
|
||||
return existingContact;
|
||||
}
|
||||
}
|
||||
|
||||
this.logger.error('Error creating contact');
|
||||
console.log(error);
|
||||
return null;
|
||||
@ -412,6 +425,55 @@ export class ChatwootService {
|
||||
}
|
||||
}
|
||||
|
||||
public async findContactByIdentifier(instance: InstanceDto, identifier: string) {
|
||||
const client = await this.clientCw(instance);
|
||||
|
||||
if (!client) {
|
||||
this.logger.warn('client not found');
|
||||
return null;
|
||||
}
|
||||
|
||||
// Direct search by query (q) - most common way to search by identifier/email/phone
|
||||
const contact = (await (client as any).get('contacts/search', {
|
||||
params: {
|
||||
q: identifier,
|
||||
sort: 'name',
|
||||
},
|
||||
})) as any;
|
||||
|
||||
if (contact && contact.data && contact.data.payload && contact.data.payload.length > 0) {
|
||||
return contact.data.payload[0];
|
||||
}
|
||||
|
||||
// Fallback for older API versions or different response structures
|
||||
if (contact && contact.payload && contact.payload.length > 0) {
|
||||
return contact.payload[0];
|
||||
}
|
||||
|
||||
// Try search by attribute
|
||||
const contactByAttr = (await (client as any).post('contacts/filter', {
|
||||
payload: [
|
||||
{
|
||||
attribute_key: 'identifier',
|
||||
filter_operator: 'equal_to',
|
||||
values: [identifier],
|
||||
query_operator: null,
|
||||
},
|
||||
],
|
||||
})) as any;
|
||||
|
||||
if (contactByAttr && contactByAttr.payload && contactByAttr.payload.length > 0) {
|
||||
return contactByAttr.payload[0];
|
||||
}
|
||||
|
||||
// Check inside data property if using axios interceptors wrapper
|
||||
if (contactByAttr && contactByAttr.data && contactByAttr.data.payload && contactByAttr.data.payload.length > 0) {
|
||||
return contactByAttr.data.payload[0];
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public async findContact(instance: InstanceDto, phoneNumber: string) {
|
||||
const client = await this.clientCw(instance);
|
||||
|
||||
@ -568,27 +630,31 @@ export class ChatwootService {
|
||||
}
|
||||
|
||||
public async createConversation(instance: InstanceDto, body: any) {
|
||||
const isLid = body.key.previousRemoteJid?.includes('@lid') && body.key.senderPn;
|
||||
const remoteJid = body.key.remoteJid;
|
||||
const isLid = body.key.addressingMode === 'lid';
|
||||
const isGroup = body.key.remoteJid.endsWith('@g.us');
|
||||
const phoneNumber = isLid && !isGroup ? body.key.remoteJidAlt : body.key.remoteJid;
|
||||
const { remoteJid } = body.key;
|
||||
const cacheKey = `${instance.instanceName}:createConversation-${remoteJid}`;
|
||||
const lockKey = `${instance.instanceName}:lock:createConversation-${remoteJid}`;
|
||||
const maxWaitTime = 5000; // 5 secounds
|
||||
const maxWaitTime = 5000; // 5 seconds
|
||||
const client = await this.clientCw(instance);
|
||||
if (!client) return null;
|
||||
|
||||
try {
|
||||
// Processa atualização de contatos já criados @lid
|
||||
if (isLid && body.key.senderPn !== body.key.previousRemoteJid) {
|
||||
const contact = await this.findContact(instance, body.key.remoteJid.split('@')[0]);
|
||||
if (contact && contact.identifier !== body.key.senderPn) {
|
||||
if (phoneNumber && remoteJid && !isGroup) {
|
||||
const contact = await this.findContact(instance, phoneNumber.split('@')[0]);
|
||||
if (contact && contact.identifier !== remoteJid) {
|
||||
this.logger.verbose(
|
||||
`Identifier needs update: (contact.identifier: ${contact.identifier}, body.key.remoteJid: ${body.key.remoteJid}, body.key.senderPn: ${body.key.senderPn}`,
|
||||
`Identifier needs update: (contact.identifier: ${contact.identifier}, phoneNumber: ${phoneNumber}, body.key.remoteJidAlt: ${remoteJid}`,
|
||||
);
|
||||
const updateContact = await this.updateContact(instance, contact.id, {
|
||||
identifier: body.key.senderPn,
|
||||
phone_number: `+${body.key.senderPn.split('@')[0]}`,
|
||||
identifier: phoneNumber,
|
||||
phone_number: `+${phoneNumber.split('@')[0]}`,
|
||||
});
|
||||
|
||||
if (updateContact === null) {
|
||||
const baseContact = await this.findContact(instance, body.key.senderPn.split('@')[0]);
|
||||
const baseContact = await this.findContact(instance, phoneNumber.split('@')[0]);
|
||||
if (baseContact) {
|
||||
await this.mergeContacts(baseContact.id, contact.id);
|
||||
this.logger.verbose(
|
||||
@ -604,7 +670,25 @@ export class ChatwootService {
|
||||
// If it already exists in the cache, return conversationId
|
||||
if (await this.cache.has(cacheKey)) {
|
||||
const conversationId = (await this.cache.get(cacheKey)) as number;
|
||||
this.logger.verbose(`Found conversation to: ${remoteJid}, conversation ID: ${conversationId}`);
|
||||
this.logger.verbose(`Found conversation to: ${phoneNumber}, conversation ID: ${conversationId}`);
|
||||
let conversationExists: any;
|
||||
try {
|
||||
conversationExists = await client.conversations.get({
|
||||
accountId: this.provider.accountId,
|
||||
conversationId: conversationId,
|
||||
});
|
||||
this.logger.verbose(
|
||||
`Conversation exists: ID: ${conversationExists.id} - Name: ${conversationExists.meta.sender.name} - Identifier: ${conversationExists.meta.sender.identifier}`,
|
||||
);
|
||||
} catch (error) {
|
||||
this.logger.error(`Error getting conversation: ${error}`);
|
||||
conversationExists = false;
|
||||
}
|
||||
if (!conversationExists) {
|
||||
this.logger.verbose('Conversation does not exist, re-calling createConversation');
|
||||
this.cache.delete(cacheKey);
|
||||
return await this.createConversation(instance, body);
|
||||
}
|
||||
return conversationId;
|
||||
}
|
||||
|
||||
@ -617,7 +701,7 @@ export class ChatwootService {
|
||||
this.logger.warn(`Timeout aguardando lock para ${remoteJid}`);
|
||||
break;
|
||||
}
|
||||
await new Promise((res) => setTimeout(res, 300));
|
||||
await new Promise((res) => setTimeout(res, this.LOCK_POLLING_DELAY_MS));
|
||||
if (await this.cache.has(cacheKey)) {
|
||||
const conversationId = (await this.cache.get(cacheKey)) as number;
|
||||
this.logger.verbose(`Resolves creation of: ${remoteJid}, conversation ID: ${conversationId}`);
|
||||
@ -639,11 +723,7 @@ export class ChatwootService {
|
||||
return (await this.cache.get(cacheKey)) as number;
|
||||
}
|
||||
|
||||
const client = await this.clientCw(instance);
|
||||
if (!client) return null;
|
||||
|
||||
const isGroup = remoteJid.includes('@g.us');
|
||||
const chatId = isGroup ? remoteJid : remoteJid.split('@')[0];
|
||||
const chatId = isGroup ? remoteJid : phoneNumber.split('@')[0].split(':')[0];
|
||||
let nameContact = !body.key.fromMe ? body.pushName : chatId;
|
||||
const filterInbox = await this.getInbox(instance);
|
||||
if (!filterInbox) return null;
|
||||
@ -651,19 +731,22 @@ export class ChatwootService {
|
||||
if (isGroup) {
|
||||
this.logger.verbose(`Processing group conversation`);
|
||||
const group = await this.waMonitor.waInstances[instance.instanceName].client.groupMetadata(chatId);
|
||||
this.logger.verbose(`Group metadata: ${JSON.stringify(group)}`);
|
||||
this.logger.verbose(`Group metadata: JID:${group.JID} - Subject:${group?.subject || group?.Name}`);
|
||||
|
||||
const participantJid = isLid && !body.key.fromMe ? body.key.participantAlt : body.key.participant;
|
||||
nameContact = `${group.subject} (GROUP)`;
|
||||
|
||||
const picture_url = await this.waMonitor.waInstances[instance.instanceName].profilePicture(
|
||||
body.key.participant.split('@')[0],
|
||||
participantJid.split('@')[0],
|
||||
);
|
||||
this.logger.verbose(`Participant profile picture URL: ${JSON.stringify(picture_url)}`);
|
||||
|
||||
const findParticipant = await this.findContact(instance, body.key.participant.split('@')[0]);
|
||||
this.logger.verbose(`Found participant: ${JSON.stringify(findParticipant)}`);
|
||||
const findParticipant = await this.findContact(instance, participantJid.split('@')[0]);
|
||||
|
||||
if (findParticipant) {
|
||||
this.logger.verbose(
|
||||
`Found participant: ID:${findParticipant.id} - Name: ${findParticipant.name} - identifier: ${findParticipant.identifier}`,
|
||||
);
|
||||
if (!findParticipant.name || findParticipant.name === chatId) {
|
||||
await this.updateContact(instance, findParticipant.id, {
|
||||
name: body.pushName,
|
||||
@ -673,12 +756,12 @@ export class ChatwootService {
|
||||
} else {
|
||||
await this.createContact(
|
||||
instance,
|
||||
body.key.participant.split('@')[0],
|
||||
participantJid.split('@')[0].split(':')[0],
|
||||
filterInbox.id,
|
||||
false,
|
||||
body.pushName,
|
||||
picture_url.profilePictureUrl || null,
|
||||
body.key.participant,
|
||||
participantJid,
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -686,23 +769,17 @@ export class ChatwootService {
|
||||
const picture_url = await this.waMonitor.waInstances[instance.instanceName].profilePicture(chatId);
|
||||
this.logger.verbose(`Contact profile picture URL: ${JSON.stringify(picture_url)}`);
|
||||
|
||||
this.logger.verbose(`Searching contact for: ${chatId}`);
|
||||
let contact = await this.findContact(instance, chatId);
|
||||
|
||||
if (contact) {
|
||||
this.logger.verbose(`Found contact: ${JSON.stringify(contact)}`);
|
||||
this.logger.verbose(`Found contact: ID:${contact.id} - Name:${contact.name}`);
|
||||
if (!body.key.fromMe) {
|
||||
const waProfilePictureFile =
|
||||
picture_url?.profilePictureUrl?.split('#')[0].split('?')[0].split('/').pop() || '';
|
||||
const chatwootProfilePictureFile = contact?.thumbnail?.split('#')[0].split('?')[0].split('/').pop() || '';
|
||||
const pictureNeedsUpdate = waProfilePictureFile !== chatwootProfilePictureFile;
|
||||
const nameNeedsUpdate =
|
||||
!contact.name ||
|
||||
contact.name === chatId ||
|
||||
(`+${chatId}`.startsWith('+55')
|
||||
? this.getNumbers(`+${chatId}`).some(
|
||||
(v) => contact.name === v || contact.name === v.substring(3) || contact.name === v.substring(1),
|
||||
)
|
||||
: false);
|
||||
const nameNeedsUpdate = !contact.name || contact.name === chatId;
|
||||
this.logger.verbose(`Picture needs update: ${pictureNeedsUpdate}`);
|
||||
this.logger.verbose(`Name needs update: ${nameNeedsUpdate}`);
|
||||
if (pictureNeedsUpdate || nameNeedsUpdate) {
|
||||
@ -721,7 +798,7 @@ export class ChatwootService {
|
||||
isGroup,
|
||||
nameContact,
|
||||
picture_url.profilePictureUrl || null,
|
||||
remoteJid,
|
||||
phoneNumber,
|
||||
);
|
||||
}
|
||||
|
||||
@ -737,7 +814,6 @@ export class ChatwootService {
|
||||
accountId: this.provider.accountId,
|
||||
id: contactId,
|
||||
})) as any;
|
||||
this.logger.verbose(`Contact conversations: ${JSON.stringify(contactConversations)}`);
|
||||
|
||||
if (!contactConversations || !contactConversations.payload) {
|
||||
this.logger.error(`No conversations found or payload is undefined`);
|
||||
@ -749,7 +825,9 @@ export class ChatwootService {
|
||||
);
|
||||
if (inboxConversation) {
|
||||
if (this.provider.reopenConversation) {
|
||||
this.logger.verbose(`Found conversation in reopenConversation mode: ${JSON.stringify(inboxConversation)}`);
|
||||
this.logger.verbose(
|
||||
`Found conversation in reopenConversation mode: ID: ${inboxConversation.id} - Name: ${inboxConversation.meta.sender.name} - Identifier: ${inboxConversation.meta.sender.identifier}`,
|
||||
);
|
||||
if (inboxConversation && this.provider.conversationPending && inboxConversation.status !== 'open') {
|
||||
await client.conversations.toggleStatus({
|
||||
accountId: this.provider.accountId,
|
||||
@ -769,7 +847,7 @@ export class ChatwootService {
|
||||
|
||||
if (inboxConversation) {
|
||||
this.logger.verbose(`Returning existing conversation ID: ${inboxConversation.id}`);
|
||||
this.cache.set(cacheKey, inboxConversation.id);
|
||||
this.cache.set(cacheKey, inboxConversation.id, 1800);
|
||||
return inboxConversation.id;
|
||||
}
|
||||
}
|
||||
@ -783,14 +861,6 @@ export class ChatwootService {
|
||||
data['status'] = 'pending';
|
||||
}
|
||||
|
||||
/*
|
||||
Triple check after lock
|
||||
Utilizei uma nova verificação para evitar que outra thread execute entre o terminio do while e o set lock
|
||||
*/
|
||||
if (await this.cache.has(cacheKey)) {
|
||||
return (await this.cache.get(cacheKey)) as number;
|
||||
}
|
||||
|
||||
const conversation = await client.conversations.create({
|
||||
accountId: this.provider.accountId,
|
||||
data,
|
||||
@ -802,7 +872,7 @@ export class ChatwootService {
|
||||
}
|
||||
|
||||
this.logger.verbose(`New conversation created of ${remoteJid} with ID: ${conversation.id}`);
|
||||
this.cache.set(cacheKey, conversation.id);
|
||||
this.cache.set(cacheKey, conversation.id, 1800);
|
||||
return conversation.id;
|
||||
} finally {
|
||||
await this.cache.delete(lockKey);
|
||||
@ -1158,7 +1228,7 @@ export class ChatwootService {
|
||||
const data: SendAudioDto = {
|
||||
number: number,
|
||||
audio: media,
|
||||
delay: 1200,
|
||||
delay: Math.floor(Math.random() * (2000 - 500 + 1)) + 500,
|
||||
quoted: options?.quoted,
|
||||
};
|
||||
|
||||
@ -1169,7 +1239,7 @@ export class ChatwootService {
|
||||
return messageSent;
|
||||
}
|
||||
|
||||
const documentExtensions = ['.gif', '.svg', '.tiff', '.tif'];
|
||||
const documentExtensions = ['.gif', '.svg', '.tiff', '.tif', '.dxf', '.dwg'];
|
||||
if (type === 'image' && parsedMedia && documentExtensions.includes(parsedMedia?.ext)) {
|
||||
type = 'document';
|
||||
}
|
||||
@ -1194,6 +1264,7 @@ export class ChatwootService {
|
||||
return messageSent;
|
||||
} catch (error) {
|
||||
this.logger.error(error);
|
||||
throw error; // Re-throw para que o erro seja tratado pelo caller
|
||||
}
|
||||
}
|
||||
|
||||
@ -1275,6 +1346,7 @@ export class ChatwootService {
|
||||
|
||||
const senderName = body?.conversation?.messages[0]?.sender?.available_name || body?.sender?.name;
|
||||
const waInstance = this.waMonitor.waInstances[instance.instanceName];
|
||||
instance.instanceId = waInstance.instanceId;
|
||||
|
||||
if (body.event === 'message_updated' && body.content_attributes?.deleted) {
|
||||
const message = await this.prismaRepository.message.findFirst({
|
||||
@ -1285,7 +1357,7 @@ export class ChatwootService {
|
||||
});
|
||||
|
||||
if (message) {
|
||||
const key = message.key as ExtendedMessageKey;
|
||||
const key = message.key as WAMessageKey;
|
||||
|
||||
await waInstance?.client.sendMessage(key.remoteJid, { delete: key });
|
||||
|
||||
@ -1417,7 +1489,6 @@ export class ChatwootService {
|
||||
await this.updateChatwootMessageId(
|
||||
{
|
||||
...messageSent,
|
||||
owner: instance.instanceName,
|
||||
},
|
||||
{
|
||||
messageId: body.id,
|
||||
@ -1432,7 +1503,7 @@ export class ChatwootService {
|
||||
const data: SendTextDto = {
|
||||
number: chatId,
|
||||
text: formatText,
|
||||
delay: 1200,
|
||||
delay: Math.floor(Math.random() * (2000 - 500 + 1)) + 500,
|
||||
quoted: await this.getQuotedMessage(body, instance),
|
||||
};
|
||||
|
||||
@ -1452,7 +1523,6 @@ export class ChatwootService {
|
||||
await this.updateChatwootMessageId(
|
||||
{
|
||||
...messageSent,
|
||||
instanceId: instance.instanceId,
|
||||
},
|
||||
{
|
||||
messageId: body.id,
|
||||
@ -1483,7 +1553,7 @@ export class ChatwootService {
|
||||
},
|
||||
});
|
||||
if (lastMessage && !lastMessage.chatwootIsRead) {
|
||||
const key = lastMessage.key as ExtendedMessageKey;
|
||||
const key = lastMessage.key as WAMessageKey;
|
||||
|
||||
waInstance?.markMessageAsRead({
|
||||
readMessages: [
|
||||
@ -1520,7 +1590,7 @@ export class ChatwootService {
|
||||
const data: SendTextDto = {
|
||||
number: chatId,
|
||||
text: body.content.replace(/\\\r\n|\\\n|\n/g, '\n'),
|
||||
delay: 1200,
|
||||
delay: Math.floor(Math.random() * (2000 - 500 + 1)) + 500,
|
||||
};
|
||||
|
||||
sendTelemetry('/message/sendText');
|
||||
@ -1541,14 +1611,14 @@ export class ChatwootService {
|
||||
chatwootMessageIds: ChatwootMessage,
|
||||
instance: InstanceDto,
|
||||
) {
|
||||
const key = message.key as ExtendedMessageKey;
|
||||
const key = message.key as WAMessageKey;
|
||||
|
||||
if (!chatwootMessageIds.messageId || !key?.id) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Use raw SQL to avoid JSON path issues
|
||||
await this.prismaRepository.$executeRaw`
|
||||
const result = await this.prismaRepository.$executeRaw`
|
||||
UPDATE "Message"
|
||||
SET
|
||||
"chatwootMessageId" = ${chatwootMessageIds.messageId},
|
||||
@ -1560,8 +1630,14 @@ export class ChatwootService {
|
||||
AND "key"->>'id' = ${key.id}
|
||||
`;
|
||||
|
||||
this.logger.verbose(`Update result: ${result} rows affected`);
|
||||
|
||||
if (this.isImportHistoryAvailable()) {
|
||||
chatwootImport.updateMessageSourceID(chatwootMessageIds.messageId, key.id);
|
||||
try {
|
||||
await chatwootImport.updateMessageSourceID(chatwootMessageIds.messageId, key.id);
|
||||
} catch (error) {
|
||||
this.logger.error(`Error updating Chatwoot message source ID: ${error}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -1609,12 +1685,13 @@ export class ChatwootService {
|
||||
},
|
||||
});
|
||||
|
||||
const key = message?.key as ExtendedMessageKey;
|
||||
const key = message?.key as WAMessageKey;
|
||||
const messageContent = message?.message as WAMessageContent;
|
||||
|
||||
if (message && key?.id) {
|
||||
if (messageContent && key?.id) {
|
||||
return {
|
||||
key: message.key as proto.IMessageKey,
|
||||
message: message.message as proto.IMessage,
|
||||
key: key,
|
||||
message: messageContent,
|
||||
};
|
||||
}
|
||||
}
|
||||
@ -1640,6 +1717,10 @@ export class ChatwootService {
|
||||
return result;
|
||||
}
|
||||
|
||||
private isInteractiveButtonMessage(messageType: string, message: any) {
|
||||
return messageType === 'interactiveMessage' && message.interactiveMessage?.nativeFlowMessage?.buttons?.length > 0;
|
||||
}
|
||||
|
||||
private getAdsMessage(msg: any) {
|
||||
interface AdsMessage {
|
||||
title: string;
|
||||
@ -1913,6 +1994,7 @@ export class ChatwootService {
|
||||
}
|
||||
|
||||
if (event === 'messages.upsert' || event === 'send.message') {
|
||||
this.logger.info(`[${event}] New message received - Instance: ${JSON.stringify(body, null, 2)}`);
|
||||
if (body.key.remoteJid === 'status@broadcast') {
|
||||
return;
|
||||
}
|
||||
@ -1957,8 +2039,9 @@ export class ChatwootService {
|
||||
const adsMessage = this.getAdsMessage(body);
|
||||
|
||||
const reactionMessage = this.getReactionMessage(body.message);
|
||||
const isInteractiveButtonMessage = this.isInteractiveButtonMessage(body.messageType, body.message);
|
||||
|
||||
if (!bodyMessage && !isMedia && !reactionMessage) {
|
||||
if (!bodyMessage && !isMedia && !reactionMessage && !isInteractiveButtonMessage) {
|
||||
this.logger.warn('no body message found');
|
||||
return;
|
||||
}
|
||||
@ -2003,23 +2086,20 @@ export class ChatwootService {
|
||||
|
||||
if (body.key.remoteJid.includes('@g.us')) {
|
||||
const participantName = body.pushName;
|
||||
const rawPhoneNumber = body.key.participant.split('@')[0];
|
||||
const phoneMatch = rawPhoneNumber.match(/^(\d{2})(\d{2})(\d{4})(\d{4})$/);
|
||||
|
||||
let formattedPhoneNumber: string;
|
||||
|
||||
if (phoneMatch) {
|
||||
formattedPhoneNumber = `+${phoneMatch[1]} (${phoneMatch[2]}) ${phoneMatch[3]}-${phoneMatch[4]}`;
|
||||
} else {
|
||||
formattedPhoneNumber = `+${rawPhoneNumber}`;
|
||||
}
|
||||
const rawPhoneNumber =
|
||||
body.key.addressingMode === 'lid' && !body.key.fromMe && body.key.participantAlt
|
||||
? body.key.participantAlt.split('@')[0].split(':')[0]
|
||||
: body.key.participant.split('@')[0].split(':')[0];
|
||||
const formattedPhoneNumber = parsePhoneNumberFromString(`+${rawPhoneNumber}`).formatInternational();
|
||||
|
||||
let content: string;
|
||||
|
||||
if (!body.key.fromMe) {
|
||||
content = `**${formattedPhoneNumber} - ${participantName}:**\n\n${bodyMessage}`;
|
||||
content = bodyMessage
|
||||
? `**${formattedPhoneNumber} - ${participantName}:**\n\n${bodyMessage}`
|
||||
: `**${formattedPhoneNumber} - ${participantName}:**`;
|
||||
} else {
|
||||
content = `${bodyMessage}`;
|
||||
content = bodyMessage || '';
|
||||
}
|
||||
|
||||
const send = await this.sendData(
|
||||
@ -2086,6 +2166,50 @@ export class ChatwootService {
|
||||
return;
|
||||
}
|
||||
|
||||
if (isInteractiveButtonMessage) {
|
||||
const buttons = body.message.interactiveMessage.nativeFlowMessage.buttons;
|
||||
this.logger.info('is Interactive Button Message: ' + JSON.stringify(buttons));
|
||||
|
||||
for (const button of buttons) {
|
||||
const buttonParams = JSON.parse(button.buttonParamsJson);
|
||||
const paymentSettings = buttonParams.payment_settings;
|
||||
|
||||
if (button.name === 'payment_info' && paymentSettings[0].type === 'pix_static_code') {
|
||||
const pixSettings = paymentSettings[0].pix_static_code;
|
||||
const pixKeyType = (() => {
|
||||
switch (pixSettings.key_type) {
|
||||
case 'EVP':
|
||||
return 'Chave Aleatória';
|
||||
case 'EMAIL':
|
||||
return 'E-mail';
|
||||
case 'PHONE':
|
||||
return 'Telefone';
|
||||
default:
|
||||
return pixSettings.key_type;
|
||||
}
|
||||
})();
|
||||
const pixKey = pixSettings.key_type === 'PHONE' ? pixSettings.key.replace('+55', '') : pixSettings.key;
|
||||
const content = `*${pixSettings.merchant_name}*\nChave PIX: ${pixKey} (${pixKeyType})`;
|
||||
|
||||
const send = await this.createMessage(
|
||||
instance,
|
||||
getConversation,
|
||||
content,
|
||||
messageType,
|
||||
false,
|
||||
[],
|
||||
body,
|
||||
'WAID:' + body.key.id,
|
||||
quotedMsg,
|
||||
);
|
||||
if (!send) this.logger.warn('message not sent');
|
||||
} else {
|
||||
this.logger.warn('Interactive Button Message not mapped');
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const isAdsMessage = (adsMessage && adsMessage.title) || adsMessage.body || adsMessage.thumbnailUrl;
|
||||
if (isAdsMessage) {
|
||||
const imgBuffer = await axios.get(adsMessage.thumbnailUrl, { responseType: 'arraybuffer' });
|
||||
@ -2144,16 +2268,11 @@ export class ChatwootService {
|
||||
|
||||
if (body.key.remoteJid.includes('@g.us')) {
|
||||
const participantName = body.pushName;
|
||||
const rawPhoneNumber = body.key.participant.split('@')[0];
|
||||
const phoneMatch = rawPhoneNumber.match(/^(\d{2})(\d{2})(\d{4})(\d{4})$/);
|
||||
|
||||
let formattedPhoneNumber: string;
|
||||
|
||||
if (phoneMatch) {
|
||||
formattedPhoneNumber = `+${phoneMatch[1]} (${phoneMatch[2]}) ${phoneMatch[3]}-${phoneMatch[4]}`;
|
||||
} else {
|
||||
formattedPhoneNumber = `+${rawPhoneNumber}`;
|
||||
}
|
||||
const rawPhoneNumber =
|
||||
body.key.addressingMode === 'lid' && !body.key.fromMe && body.key.participantAlt
|
||||
? body.key.participantAlt.split('@')[0].split(':')[0]
|
||||
: body.key.participant.split('@')[0].split(':')[0];
|
||||
const formattedPhoneNumber = parsePhoneNumberFromString(`+${rawPhoneNumber}`).formatInternational();
|
||||
|
||||
let content: string;
|
||||
|
||||
@ -2235,9 +2354,21 @@ export class ChatwootService {
|
||||
}
|
||||
|
||||
if (event === 'messages.edit' || event === 'send.message.update') {
|
||||
const editedText = `${
|
||||
body?.editedMessage?.conversation || body?.editedMessage?.extendedTextMessage?.text
|
||||
}\n\n_\`${i18next.t('cw.message.edited')}.\`_`;
|
||||
const editedMessageContentRaw =
|
||||
body?.editedMessage?.conversation ??
|
||||
body?.editedMessage?.extendedTextMessage?.text ??
|
||||
body?.editedMessage?.imageMessage?.caption ??
|
||||
body?.editedMessage?.videoMessage?.caption ??
|
||||
body?.editedMessage?.documentMessage?.caption ??
|
||||
(typeof body?.text === 'string' ? body.text : undefined);
|
||||
|
||||
const editedMessageContent = (editedMessageContentRaw ?? '').trim();
|
||||
|
||||
if (!editedMessageContent) {
|
||||
this.logger.info('[CW.EDIT] Conteúdo vazio — ignorando (DELETE tratará se for revoke).');
|
||||
return;
|
||||
}
|
||||
|
||||
const message = await this.getMessageByKeyId(instance, body?.key?.id);
|
||||
|
||||
if (!message) {
|
||||
@ -2245,11 +2376,14 @@ export class ChatwootService {
|
||||
return;
|
||||
}
|
||||
|
||||
const key = message.key as ExtendedMessageKey;
|
||||
const key = message.key as WAMessageKey;
|
||||
|
||||
const messageType = key?.fromMe ? 'outgoing' : 'incoming';
|
||||
|
||||
if (message && message.chatwootConversationId) {
|
||||
if (message && message.chatwootConversationId && message.chatwootMessageId) {
|
||||
// Criar nova mensagem com formato: "Mensagem editada:\n\nteste1"
|
||||
const editedText = `\n\n\`${i18next.t('cw.message.edited')}:\`\n\n${editedMessageContent}`;
|
||||
|
||||
const send = await this.createMessage(
|
||||
instance,
|
||||
message.chatwootConversationId,
|
||||
@ -2301,7 +2435,7 @@ export class ChatwootService {
|
||||
const url =
|
||||
`/public/api/v1/inboxes/${inbox.inbox_identifier}/contacts/${sourceId}` +
|
||||
`/conversations/${conversationId}/update_last_seen`;
|
||||
chatwootRequest(this.getClientCwConfig(), {
|
||||
await chatwootRequest(this.getClientCwConfig(), {
|
||||
method: 'POST',
|
||||
url: url,
|
||||
});
|
||||
@ -2327,15 +2461,30 @@ export class ChatwootService {
|
||||
await this.createBotMessage(instance, msgStatus, 'incoming');
|
||||
}
|
||||
|
||||
if (event === 'connection.update') {
|
||||
if (body.status === 'open') {
|
||||
// if we have qrcode count then we understand that a new connection was established
|
||||
if (this.waMonitor.waInstances[instance.instanceName].qrCode.count > 0) {
|
||||
const msgConnection = i18next.t('cw.inbox.connected');
|
||||
await this.createBotMessage(instance, msgConnection, 'incoming');
|
||||
this.waMonitor.waInstances[instance.instanceName].qrCode.count = 0;
|
||||
chatwootImport.clearAll(instance);
|
||||
}
|
||||
if (event === 'connection.update' && body.status === 'open') {
|
||||
const waInstance = this.waMonitor.waInstances[instance.instanceName];
|
||||
if (!waInstance) return;
|
||||
|
||||
const now = Date.now();
|
||||
const timeSinceLastNotification = now - (waInstance.lastConnectionNotification || 0);
|
||||
|
||||
// Se a conexão foi estabelecida via QR code, notifica imediatamente.
|
||||
if (waInstance.qrCode && waInstance.qrCode.count > 0) {
|
||||
const msgConnection = i18next.t('cw.inbox.connected');
|
||||
await this.createBotMessage(instance, msgConnection, 'incoming');
|
||||
waInstance.qrCode.count = 0;
|
||||
waInstance.lastConnectionNotification = now;
|
||||
chatwootImport.clearAll(instance);
|
||||
}
|
||||
// Se não foi via QR code, verifica o throttling.
|
||||
else if (timeSinceLastNotification >= 30000) {
|
||||
const msgConnection = i18next.t('cw.inbox.connected');
|
||||
await this.createBotMessage(instance, msgConnection, 'incoming');
|
||||
waInstance.lastConnectionNotification = now;
|
||||
} else {
|
||||
this.logger.warn(
|
||||
`Connection notification skipped for ${instance.instanceName} - too frequent (${timeSinceLastNotification}ms since last)`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -2378,7 +2527,13 @@ export class ChatwootService {
|
||||
}
|
||||
}
|
||||
|
||||
public getNumberFromRemoteJid(remoteJid: string) {
|
||||
public normalizeJidIdentifier(remoteJid: string) {
|
||||
if (!remoteJid) {
|
||||
return '';
|
||||
}
|
||||
if (remoteJid.includes('@lid')) {
|
||||
return remoteJid;
|
||||
}
|
||||
return remoteJid.replace(/:\d+/, '').split('@')[0];
|
||||
}
|
||||
|
||||
|
||||
@ -112,12 +112,19 @@ class ChatwootImport {
|
||||
const bindInsert = [provider.accountId];
|
||||
|
||||
for (const contact of contactsChunk) {
|
||||
bindInsert.push(contact.pushName);
|
||||
const isGroup = this.isIgnorePhoneNumber(contact.remoteJid);
|
||||
|
||||
const contactName = isGroup ? `${contact.pushName} (GROUP)` : contact.pushName;
|
||||
bindInsert.push(contactName);
|
||||
const bindName = `$${bindInsert.length}`;
|
||||
|
||||
bindInsert.push(`+${contact.remoteJid.split('@')[0]}`);
|
||||
const bindPhoneNumber = `$${bindInsert.length}`;
|
||||
|
||||
let bindPhoneNumber: string;
|
||||
if (!isGroup) {
|
||||
bindInsert.push(`+${contact.remoteJid.split('@')[0]}`);
|
||||
bindPhoneNumber = `$${bindInsert.length}`;
|
||||
} else {
|
||||
bindPhoneNumber = 'NULL';
|
||||
}
|
||||
bindInsert.push(contact.remoteJid);
|
||||
const bindIdentifier = `$${bindInsert.length}`;
|
||||
|
||||
@ -130,7 +137,7 @@ class ChatwootImport {
|
||||
DO UPDATE SET
|
||||
name = EXCLUDED.name,
|
||||
phone_number = EXCLUDED.phone_number,
|
||||
identifier = EXCLUDED.identifier`;
|
||||
updated_at = NOW()`;
|
||||
|
||||
totalContactsImported += (await pgClient.query(sqlInsert, bindInsert))?.rowCount ?? 0;
|
||||
|
||||
|
||||
@ -51,6 +51,7 @@ export class N8nService extends BaseChatbotService<N8n, N8nSetting> {
|
||||
pushName: pushName,
|
||||
keyId: msg?.key?.id,
|
||||
fromMe: msg?.key?.fromMe,
|
||||
quotedMessage: msg?.contextInfo?.quotedMessage,
|
||||
instanceName: instance.instanceName,
|
||||
serverUrl: this.configService.get<HttpServer>('SERVER').URL,
|
||||
apiKey: instance.token,
|
||||
|
||||
@ -327,7 +327,7 @@ export class TypebotService extends BaseChatbotService<TypebotModel, any> {
|
||||
if (message.type === 'image') {
|
||||
await instance.mediaMessage(
|
||||
{
|
||||
number: session.remoteJid.split('@')[0],
|
||||
number: session.remoteJid,
|
||||
delay: settings?.delayMessage || 1000,
|
||||
mediatype: 'image',
|
||||
media: message.content.url,
|
||||
@ -342,7 +342,7 @@ export class TypebotService extends BaseChatbotService<TypebotModel, any> {
|
||||
if (message.type === 'video') {
|
||||
await instance.mediaMessage(
|
||||
{
|
||||
number: session.remoteJid.split('@')[0],
|
||||
number: session.remoteJid,
|
||||
delay: settings?.delayMessage || 1000,
|
||||
mediatype: 'video',
|
||||
media: message.content.url,
|
||||
@ -357,7 +357,7 @@ export class TypebotService extends BaseChatbotService<TypebotModel, any> {
|
||||
if (message.type === 'audio') {
|
||||
await instance.audioWhatsapp(
|
||||
{
|
||||
number: session.remoteJid.split('@')[0],
|
||||
number: session.remoteJid,
|
||||
delay: settings?.delayMessage || 1000,
|
||||
encoding: true,
|
||||
audio: message.content.url,
|
||||
@ -441,7 +441,7 @@ export class TypebotService extends BaseChatbotService<TypebotModel, any> {
|
||||
*/
|
||||
private async processListMessage(instance: any, formattedText: string, remoteJid: string) {
|
||||
const listJson = {
|
||||
number: remoteJid.split('@')[0],
|
||||
number: remoteJid,
|
||||
title: '',
|
||||
description: '',
|
||||
buttonText: '',
|
||||
@ -490,7 +490,7 @@ export class TypebotService extends BaseChatbotService<TypebotModel, any> {
|
||||
*/
|
||||
private async processButtonMessage(instance: any, formattedText: string, remoteJid: string) {
|
||||
const buttonJson = {
|
||||
number: remoteJid.split('@')[0],
|
||||
number: remoteJid,
|
||||
thumbnailUrl: undefined,
|
||||
title: '',
|
||||
description: '',
|
||||
|
||||
@ -14,12 +14,24 @@ export type EmitData = {
|
||||
apiKey?: string;
|
||||
local?: boolean;
|
||||
integration?: string[];
|
||||
extra?: Record<string, any>;
|
||||
};
|
||||
|
||||
export interface EventControllerInterface {
|
||||
set(instanceName: string, data: any): Promise<any>;
|
||||
get(instanceName: string): Promise<any>;
|
||||
emit({ instanceName, origin, event, data, serverUrl, dateTime, sender, apiKey, local }: EmitData): Promise<void>;
|
||||
emit({
|
||||
instanceName,
|
||||
origin,
|
||||
event,
|
||||
data,
|
||||
serverUrl,
|
||||
dateTime,
|
||||
sender,
|
||||
apiKey,
|
||||
local,
|
||||
extra,
|
||||
}: EmitData): Promise<void>;
|
||||
}
|
||||
|
||||
export class EventController {
|
||||
|
||||
@ -123,6 +123,7 @@ export class EventManager {
|
||||
apiKey?: string;
|
||||
local?: boolean;
|
||||
integration?: string[];
|
||||
extra?: Record<string, any>;
|
||||
}): Promise<void> {
|
||||
await this.websocket.emit(eventData);
|
||||
await this.rabbitmq.emit(eventData);
|
||||
|
||||
@ -262,6 +262,7 @@ export class KafkaController extends EventController implements EventControllerI
|
||||
sender,
|
||||
apiKey,
|
||||
integration,
|
||||
extra,
|
||||
}: EmitData): Promise<void> {
|
||||
if (integration && !integration.includes('kafka')) {
|
||||
return;
|
||||
@ -284,6 +285,7 @@ export class KafkaController extends EventController implements EventControllerI
|
||||
const logEnabled = configService.get<Log>('LOG').LEVEL.includes('WEBHOOKS');
|
||||
|
||||
const message = {
|
||||
...(extra ?? {}),
|
||||
event,
|
||||
instance: instanceName,
|
||||
data,
|
||||
|
||||
@ -47,6 +47,7 @@ export class NatsController extends EventController implements EventControllerIn
|
||||
sender,
|
||||
apiKey,
|
||||
integration,
|
||||
extra,
|
||||
}: EmitData): Promise<void> {
|
||||
if (integration && !integration.includes('nats')) {
|
||||
return;
|
||||
@ -65,6 +66,7 @@ export class NatsController extends EventController implements EventControllerIn
|
||||
const logEnabled = configService.get<Log>('LOG').LEVEL.includes('WEBHOOKS');
|
||||
|
||||
const message = {
|
||||
...(extra ?? {}),
|
||||
event,
|
||||
instance: instanceName,
|
||||
data,
|
||||
|
||||
@ -121,6 +121,7 @@ export class PusherController extends EventController implements EventController
|
||||
apiKey,
|
||||
local,
|
||||
integration,
|
||||
extra,
|
||||
}: EmitData): Promise<void> {
|
||||
if (integration && !integration.includes('pusher')) {
|
||||
return;
|
||||
@ -133,6 +134,7 @@ export class PusherController extends EventController implements EventController
|
||||
const enabledLog = configService.get<Log>('LOG').LEVEL.includes('WEBHOOKS');
|
||||
const eventName = event.replace(/_/g, '.').toLowerCase();
|
||||
const pusherData = {
|
||||
...(extra ?? {}),
|
||||
event,
|
||||
instance: instanceName,
|
||||
data,
|
||||
|
||||
@ -209,6 +209,7 @@ export class RabbitmqController extends EventController implements EventControll
|
||||
sender,
|
||||
apiKey,
|
||||
integration,
|
||||
extra,
|
||||
}: EmitData): Promise<void> {
|
||||
if (integration && !integration.includes('rabbitmq')) {
|
||||
return;
|
||||
@ -233,6 +234,7 @@ export class RabbitmqController extends EventController implements EventControll
|
||||
const logEnabled = configService.get<Log>('LOG').LEVEL.includes('WEBHOOKS');
|
||||
|
||||
const message = {
|
||||
...(extra ?? {}),
|
||||
event,
|
||||
instance: instanceName,
|
||||
data,
|
||||
|
||||
@ -93,6 +93,7 @@ export class SqsController extends EventController implements EventControllerInt
|
||||
sender,
|
||||
apiKey,
|
||||
integration,
|
||||
extra,
|
||||
}: EmitData): Promise<void> {
|
||||
if (integration && !integration.includes('sqs')) {
|
||||
return;
|
||||
@ -128,6 +129,7 @@ export class SqsController extends EventController implements EventControllerInt
|
||||
const sqsUrl = `https://sqs.${sqsConfig.REGION}.amazonaws.com/${sqsConfig.ACCOUNT_ID}/${queueName}`;
|
||||
|
||||
const message = {
|
||||
...(extra ?? {}),
|
||||
event,
|
||||
instance: instanceName,
|
||||
dataType: 'json',
|
||||
|
||||
@ -65,6 +65,7 @@ export class WebhookController extends EventController implements EventControlle
|
||||
apiKey,
|
||||
local,
|
||||
integration,
|
||||
extra,
|
||||
}: EmitData): Promise<void> {
|
||||
if (integration && !integration.includes('webhook')) {
|
||||
return;
|
||||
@ -90,6 +91,7 @@ export class WebhookController extends EventController implements EventControlle
|
||||
const regex = /^(https?:\/\/)/;
|
||||
|
||||
const webhookData = {
|
||||
...(extra ?? {}),
|
||||
event,
|
||||
instance: instanceName,
|
||||
data,
|
||||
|
||||
@ -33,10 +33,13 @@ export class WebsocketController extends EventController implements EventControl
|
||||
const { remoteAddress } = req.socket;
|
||||
const websocketConfig = configService.get<Websocket>('WEBSOCKET');
|
||||
const allowedHosts = websocketConfig.ALLOWED_HOSTS || '127.0.0.1,::1,::ffff:127.0.0.1';
|
||||
const isAllowedHost = allowedHosts
|
||||
.split(',')
|
||||
.map((h) => h.trim())
|
||||
.includes(remoteAddress);
|
||||
const allowAllHosts = allowedHosts.trim() === '*';
|
||||
const isAllowedHost =
|
||||
allowAllHosts ||
|
||||
allowedHosts
|
||||
.split(',')
|
||||
.map((h) => h.trim())
|
||||
.includes(remoteAddress);
|
||||
|
||||
if (params.has('EIO') && isAllowedHost) {
|
||||
return callback(null, true);
|
||||
@ -115,6 +118,7 @@ export class WebsocketController extends EventController implements EventControl
|
||||
sender,
|
||||
apiKey,
|
||||
integration,
|
||||
extra,
|
||||
}: EmitData): Promise<void> {
|
||||
if (integration && !integration.includes('websocket')) {
|
||||
return;
|
||||
@ -127,6 +131,7 @@ export class WebsocketController extends EventController implements EventControl
|
||||
const configEv = event.replace(/[.-]/gm, '_').toUpperCase();
|
||||
const logEnabled = configService.get<Log>('LOG').LEVEL.includes('WEBSOCKET');
|
||||
const message = {
|
||||
...(extra ?? {}),
|
||||
event,
|
||||
instance: instanceName,
|
||||
data,
|
||||
|
||||
@ -48,9 +48,14 @@ const packageJson = JSON.parse(fs.readFileSync('./package.json', 'utf8'));
|
||||
const metricsIPWhitelist = (req: Request, res: Response, next: NextFunction) => {
|
||||
const metricsConfig = configService.get('METRICS');
|
||||
const allowedIPs = metricsConfig.ALLOWED_IPS?.split(',').map((ip) => ip.trim()) || ['127.0.0.1'];
|
||||
const clientIP = req.ip || req.connection.remoteAddress || req.socket.remoteAddress;
|
||||
const clientIPs = [
|
||||
req.ip,
|
||||
req.connection.remoteAddress,
|
||||
req.socket.remoteAddress,
|
||||
req.headers['x-forwarded-for'],
|
||||
].filter((ip) => ip !== undefined);
|
||||
|
||||
if (!allowedIPs.includes(clientIP)) {
|
||||
if (allowedIPs.filter((ip) => clientIPs.includes(ip)) === 0) {
|
||||
return res.status(403).send('Forbidden: IP not allowed');
|
||||
}
|
||||
|
||||
|
||||
@ -1,9 +1,11 @@
|
||||
import { RouterBroker } from '@api/abstract/abstract.router';
|
||||
import { InstanceDto } from '@api/dto/instance.dto';
|
||||
import { TemplateDto } from '@api/dto/template.dto';
|
||||
import { TemplateDeleteDto, TemplateDto, TemplateEditDto } from '@api/dto/template.dto';
|
||||
import { templateController } from '@api/server.module';
|
||||
import { ConfigService } from '@config/env.config';
|
||||
import { createMetaErrorResponse } from '@utils/errorResponse';
|
||||
import { templateDeleteSchema } from '@validate/templateDelete.schema';
|
||||
import { templateEditSchema } from '@validate/templateEdit.schema';
|
||||
import { instanceSchema, templateSchema } from '@validate/validate.schema';
|
||||
import { RequestHandler, Router } from 'express';
|
||||
|
||||
@ -35,6 +37,38 @@ export class TemplateRouter extends RouterBroker {
|
||||
res.status(errorResponse.status).json(errorResponse);
|
||||
}
|
||||
})
|
||||
.post(this.routerPath('edit'), ...guards, async (req, res) => {
|
||||
try {
|
||||
const response = await this.dataValidate<TemplateEditDto>({
|
||||
request: req,
|
||||
schema: templateEditSchema,
|
||||
ClassRef: TemplateEditDto,
|
||||
execute: (instance, data) => templateController.editTemplate(instance, data),
|
||||
});
|
||||
|
||||
res.status(HttpStatus.OK).json(response);
|
||||
} catch (error) {
|
||||
console.error('Template edit error:', error);
|
||||
const errorResponse = createMetaErrorResponse(error, 'template_edit');
|
||||
res.status(errorResponse.status).json(errorResponse);
|
||||
}
|
||||
})
|
||||
.delete(this.routerPath('delete'), ...guards, async (req, res) => {
|
||||
try {
|
||||
const response = await this.dataValidate<TemplateDeleteDto>({
|
||||
request: req,
|
||||
schema: templateDeleteSchema,
|
||||
ClassRef: TemplateDeleteDto,
|
||||
execute: (instance, data) => templateController.deleteTemplate(instance, data),
|
||||
});
|
||||
|
||||
res.status(HttpStatus.OK).json(response);
|
||||
} catch (error) {
|
||||
console.error('Template delete error:', error);
|
||||
const errorResponse = createMetaErrorResponse(error, 'template_delete');
|
||||
res.status(errorResponse.status).json(errorResponse);
|
||||
}
|
||||
})
|
||||
.get(this.routerPath('find'), ...guards, async (req, res) => {
|
||||
try {
|
||||
const response = await this.dataValidate<InstanceDto>({
|
||||
|
||||
@ -82,7 +82,7 @@ const proxyService = new ProxyService(waMonitor);
|
||||
export const proxyController = new ProxyController(proxyService, waMonitor);
|
||||
|
||||
const chatwootService = new ChatwootService(waMonitor, configService, prismaRepository, chatwootCache);
|
||||
export const chatwootController = new ChatwootController(chatwootService, configService, prismaRepository);
|
||||
export const chatwootController = new ChatwootController(chatwootService, configService);
|
||||
|
||||
const settingsService = new SettingsService(waMonitor);
|
||||
export const settingsController = new SettingsController(settingsService);
|
||||
|
||||
@ -60,6 +60,7 @@ export class ChannelStartupService {
|
||||
this.instance.number = instance.number;
|
||||
this.instance.token = instance.token;
|
||||
this.instance.businessId = instance.businessId;
|
||||
this.instance.ownerJid = instance.ownerJid;
|
||||
|
||||
if (this.configService.get<Chatwoot>('CHATWOOT').ENABLED && this.localChatwoot?.enabled) {
|
||||
this.chatwootService.eventWhatsapp(
|
||||
@ -431,7 +432,13 @@ export class ChannelStartupService {
|
||||
return data;
|
||||
}
|
||||
|
||||
public async sendDataWebhook<T extends object = any>(event: Events, data: T, local = true, integration?: string[]) {
|
||||
public async sendDataWebhook<T extends object = any>(
|
||||
event: Events,
|
||||
data: T,
|
||||
local = true,
|
||||
integration?: string[],
|
||||
extra?: Record<string, any>,
|
||||
) {
|
||||
const serverUrl = this.configService.get<HttpServer>('SERVER').URL;
|
||||
const tzoffset = new Date().getTimezoneOffset() * 60000; //offset in milliseconds
|
||||
const localISOTime = new Date(Date.now() - tzoffset).toISOString();
|
||||
@ -452,6 +459,7 @@ export class ChannelStartupService {
|
||||
apiKey: expose && instanceApikey ? instanceApikey : null,
|
||||
local,
|
||||
integration,
|
||||
extra,
|
||||
});
|
||||
}
|
||||
|
||||
@ -490,20 +498,23 @@ export class ChannelStartupService {
|
||||
}
|
||||
|
||||
public async fetchContacts(query: Query<Contact>) {
|
||||
const remoteJid = query?.where?.remoteJid
|
||||
? query?.where?.remoteJid.includes('@')
|
||||
? query.where?.remoteJid
|
||||
: createJid(query.where?.remoteJid)
|
||||
: null;
|
||||
|
||||
const where = {
|
||||
const where: any = {
|
||||
instanceId: this.instanceId,
|
||||
};
|
||||
|
||||
if (remoteJid) {
|
||||
if (query?.where?.remoteJid) {
|
||||
const remoteJid = query.where.remoteJid.includes('@') ? query.where.remoteJid : createJid(query.where.remoteJid);
|
||||
where['remoteJid'] = remoteJid;
|
||||
}
|
||||
|
||||
if (query?.where?.id) {
|
||||
where['id'] = query.where.id;
|
||||
}
|
||||
|
||||
if (query?.where?.pushName) {
|
||||
where['pushName'] = query.where.pushName;
|
||||
}
|
||||
|
||||
const contactFindManyArgs: Prisma.ContactFindManyArgs = {
|
||||
where,
|
||||
};
|
||||
@ -532,14 +543,12 @@ export class ChannelStartupService {
|
||||
|
||||
public cleanMessageData(message: any) {
|
||||
if (!message) return message;
|
||||
|
||||
const cleanedMessage = { ...message };
|
||||
|
||||
const mediaUrl = cleanedMessage.message.mediaUrl;
|
||||
|
||||
delete cleanedMessage.message.base64;
|
||||
|
||||
if (cleanedMessage.message) {
|
||||
const { mediaUrl } = cleanedMessage.message;
|
||||
delete cleanedMessage.message.base64;
|
||||
|
||||
// Limpa imageMessage
|
||||
if (cleanedMessage.message.imageMessage) {
|
||||
cleanedMessage.message.imageMessage = {
|
||||
@ -581,9 +590,9 @@ export class ChannelStartupService {
|
||||
name: cleanedMessage.message.documentWithCaptionMessage.name,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (mediaUrl) cleanedMessage.message.mediaUrl = mediaUrl;
|
||||
if (mediaUrl) cleanedMessage.message.mediaUrl = mediaUrl;
|
||||
}
|
||||
|
||||
return cleanedMessage;
|
||||
}
|
||||
@ -826,7 +835,7 @@ export class ChannelStartupService {
|
||||
const msg = message.message;
|
||||
|
||||
// Se só tem messageContextInfo, não é mídia válida
|
||||
if (Object.keys(msg).length === 1 && 'messageContextInfo' in msg) {
|
||||
if (Object.keys(msg).length === 1 && Object.prototype.hasOwnProperty.call(msg, 'messageContextInfo')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
@ -38,25 +38,37 @@ export class WAMonitoringService {
|
||||
|
||||
private readonly logger = new Logger('WAMonitoringService');
|
||||
public readonly waInstances: Record<string, any> = {};
|
||||
private readonly delInstanceTimeouts: Record<string, NodeJS.Timeout> = {};
|
||||
|
||||
private readonly providerSession: ProviderSession;
|
||||
|
||||
public delInstanceTime(instance: string) {
|
||||
const time = this.configService.get<DelInstance>('DEL_INSTANCE');
|
||||
if (typeof time === 'number' && time > 0) {
|
||||
setTimeout(
|
||||
// Clear previous timeout if exists
|
||||
if (this.delInstanceTimeouts[instance]) {
|
||||
clearTimeout(this.delInstanceTimeouts[instance]);
|
||||
}
|
||||
|
||||
// Set new timeout and store reference
|
||||
this.delInstanceTimeouts[instance] = setTimeout(
|
||||
async () => {
|
||||
if (this.waInstances[instance]?.connectionStatus?.state !== 'open') {
|
||||
if (this.waInstances[instance]?.connectionStatus?.state === 'connecting') {
|
||||
if ((await this.waInstances[instance].integration) === Integration.WHATSAPP_BAILEYS) {
|
||||
await this.waInstances[instance]?.client?.logout('Log out instance: ' + instance);
|
||||
this.waInstances[instance]?.client?.ws?.close();
|
||||
this.waInstances[instance]?.client?.end(undefined);
|
||||
try {
|
||||
if (this.waInstances[instance]?.connectionStatus?.state !== 'open') {
|
||||
if (this.waInstances[instance]?.connectionStatus?.state === 'connecting') {
|
||||
if ((await this.waInstances[instance].integration) === Integration.WHATSAPP_BAILEYS) {
|
||||
await this.waInstances[instance]?.client?.logout('Log out instance: ' + instance);
|
||||
this.waInstances[instance]?.client?.ws?.close();
|
||||
this.waInstances[instance]?.client?.end(undefined);
|
||||
}
|
||||
this.eventEmitter.emit('remove.instance', instance, 'inner');
|
||||
} else {
|
||||
this.eventEmitter.emit('remove.instance', instance, 'inner');
|
||||
}
|
||||
this.eventEmitter.emit('remove.instance', instance, 'inner');
|
||||
} else {
|
||||
this.eventEmitter.emit('remove.instance', instance, 'inner');
|
||||
}
|
||||
} finally {
|
||||
// Clean up timeout reference
|
||||
delete this.delInstanceTimeouts[instance];
|
||||
}
|
||||
},
|
||||
1000 * 60 * time,
|
||||
@ -64,6 +76,13 @@ export class WAMonitoringService {
|
||||
}
|
||||
}
|
||||
|
||||
public clearDelInstanceTime(instance: string) {
|
||||
if (this.delInstanceTimeouts[instance]) {
|
||||
clearTimeout(this.delInstanceTimeouts[instance]);
|
||||
delete this.delInstanceTimeouts[instance];
|
||||
}
|
||||
}
|
||||
|
||||
public async instanceInfo(instanceNames?: string[]): Promise<any> {
|
||||
if (instanceNames && instanceNames.length > 0) {
|
||||
const inexistentInstances = instanceNames ? instanceNames.filter((instance) => !this.waInstances[instance]) : [];
|
||||
@ -271,9 +290,19 @@ export class WAMonitoringService {
|
||||
token: instanceData.token,
|
||||
number: instanceData.number,
|
||||
businessId: instanceData.businessId,
|
||||
ownerJid: instanceData.ownerJid,
|
||||
});
|
||||
|
||||
await instance.connectToWhatsapp();
|
||||
if (instanceData.connectionStatus === 'open' || instanceData.connectionStatus === 'connecting') {
|
||||
this.logger.info(
|
||||
`Auto-connecting instance "${instanceData.instanceName}" (status: ${instanceData.connectionStatus})`,
|
||||
);
|
||||
await instance.connectToWhatsapp();
|
||||
} else {
|
||||
this.logger.info(
|
||||
`Skipping auto-connect for instance "${instanceData.instanceName}" (status: ${instanceData.connectionStatus || 'close'})`,
|
||||
);
|
||||
}
|
||||
|
||||
this.waInstances[instanceData.instanceName] = instance;
|
||||
}
|
||||
@ -299,6 +328,7 @@ export class WAMonitoringService {
|
||||
token: instanceData.token,
|
||||
number: instanceData.number,
|
||||
businessId: instanceData.businessId,
|
||||
connectionStatus: instanceData.connectionStatus as any, // Pass connection status
|
||||
};
|
||||
|
||||
this.setInstance(instance);
|
||||
@ -327,6 +357,8 @@ export class WAMonitoringService {
|
||||
token: instance.token,
|
||||
number: instance.number,
|
||||
businessId: instance.businessId,
|
||||
ownerJid: instance.ownerJid,
|
||||
connectionStatus: instance.connectionStatus as any, // Pass connection status
|
||||
});
|
||||
}),
|
||||
);
|
||||
@ -351,6 +383,7 @@ export class WAMonitoringService {
|
||||
integration: instance.integration,
|
||||
token: instance.token,
|
||||
businessId: instance.businessId,
|
||||
connectionStatus: instance.connectionStatus as any, // Pass connection status
|
||||
});
|
||||
}),
|
||||
);
|
||||
@ -361,6 +394,8 @@ export class WAMonitoringService {
|
||||
try {
|
||||
await this.waInstances[instanceName]?.sendDataWebhook(Events.REMOVE_INSTANCE, null);
|
||||
|
||||
this.clearDelInstanceTime(instanceName);
|
||||
|
||||
this.cleaningUp(instanceName);
|
||||
this.cleaningStoreData(instanceName);
|
||||
} finally {
|
||||
@ -377,6 +412,8 @@ export class WAMonitoringService {
|
||||
try {
|
||||
await this.waInstances[instanceName]?.sendDataWebhook(Events.LOGOUT_INSTANCE, null);
|
||||
|
||||
this.clearDelInstanceTime(instanceName);
|
||||
|
||||
if (this.configService.get<Chatwoot>('CHATWOOT').ENABLED) {
|
||||
this.waInstances[instanceName]?.clearCacheChatwoot();
|
||||
}
|
||||
|
||||
@ -88,6 +88,77 @@ export class TemplateService {
|
||||
}
|
||||
}
|
||||
|
||||
public async edit(
|
||||
instance: InstanceDto,
|
||||
data: { templateId: string; category?: string; components?: any; allowCategoryChange?: boolean; ttl?: number },
|
||||
) {
|
||||
const getInstance = await this.waMonitor.waInstances[instance.instanceName].instance;
|
||||
if (!getInstance) {
|
||||
throw new Error('Instance not found');
|
||||
}
|
||||
|
||||
this.businessId = getInstance.businessId;
|
||||
this.token = getInstance.token;
|
||||
|
||||
const payload: Record<string, unknown> = {};
|
||||
if (typeof data.category === 'string') payload.category = data.category;
|
||||
if (typeof data.allowCategoryChange === 'boolean') payload.allow_category_change = data.allowCategoryChange;
|
||||
if (typeof data.ttl === 'number') payload.time_to_live = data.ttl;
|
||||
if (data.components) payload.components = data.components;
|
||||
|
||||
const response = await this.requestEditTemplate(data.templateId, payload);
|
||||
|
||||
if (!response || response.error) {
|
||||
if (response && response.error) {
|
||||
const metaError = new Error(response.error.message || 'WhatsApp API Error');
|
||||
(metaError as any).template = response.error;
|
||||
throw metaError;
|
||||
}
|
||||
throw new Error('Error to edit template');
|
||||
}
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
public async delete(instance: InstanceDto, data: { name: string; hsmId?: string }) {
|
||||
const getInstance = await this.waMonitor.waInstances[instance.instanceName].instance;
|
||||
if (!getInstance) {
|
||||
throw new Error('Instance not found');
|
||||
}
|
||||
|
||||
this.businessId = getInstance.businessId;
|
||||
this.token = getInstance.token;
|
||||
|
||||
const response = await this.requestDeleteTemplate({ name: data.name, hsm_id: data.hsmId });
|
||||
|
||||
if (!response || response.error) {
|
||||
if (response && response.error) {
|
||||
const metaError = new Error(response.error.message || 'WhatsApp API Error');
|
||||
(metaError as any).template = response.error;
|
||||
throw metaError;
|
||||
}
|
||||
throw new Error('Error to delete template');
|
||||
}
|
||||
|
||||
try {
|
||||
// Best-effort local cleanup of stored template metadata
|
||||
await this.prismaRepository.template.deleteMany({
|
||||
where: {
|
||||
OR: [
|
||||
{ name: data.name, instanceId: getInstance.id },
|
||||
data.hsmId ? { templateId: data.hsmId, instanceId: getInstance.id } : undefined,
|
||||
].filter(Boolean) as any,
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
this.logger.warn(
|
||||
`Failed to cleanup local template records after delete: ${(err as Error)?.message || String(err)}`,
|
||||
);
|
||||
}
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
private async requestTemplate(data: any, method: string) {
|
||||
try {
|
||||
let urlServer = this.configService.get<WaBusiness>('WA_BUSINESS').URL;
|
||||
@ -116,4 +187,38 @@ export class TemplateService {
|
||||
throw new Error(`Connection error: ${e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
private async requestEditTemplate(templateId: string, data: any) {
|
||||
try {
|
||||
let urlServer = this.configService.get<WaBusiness>('WA_BUSINESS').URL;
|
||||
const version = this.configService.get<WaBusiness>('WA_BUSINESS').VERSION;
|
||||
urlServer = `${urlServer}/${version}/${templateId}`;
|
||||
const headers = { 'Content-Type': 'application/json', Authorization: `Bearer ${this.token}` };
|
||||
const result = await axios.post(urlServer, data, { headers });
|
||||
return result.data;
|
||||
} catch (e) {
|
||||
this.logger.error(
|
||||
'WhatsApp API request error: ' + (e.response?.data ? JSON.stringify(e.response?.data) : e.message),
|
||||
);
|
||||
if (e.response?.data) return e.response.data;
|
||||
throw new Error(`Connection error: ${e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
private async requestDeleteTemplate(params: { name: string; hsm_id?: string }) {
|
||||
try {
|
||||
let urlServer = this.configService.get<WaBusiness>('WA_BUSINESS').URL;
|
||||
const version = this.configService.get<WaBusiness>('WA_BUSINESS').VERSION;
|
||||
urlServer = `${urlServer}/${version}/${this.businessId}/message_templates`;
|
||||
const headers = { Authorization: `Bearer ${this.token}` };
|
||||
const result = await axios.delete(urlServer, { headers, params });
|
||||
return result.data;
|
||||
} catch (e) {
|
||||
this.logger.error(
|
||||
'WhatsApp API request error: ' + (e.response?.data ? JSON.stringify(e.response?.data) : e.message),
|
||||
);
|
||||
if (e.response?.data) return e.response.data;
|
||||
throw new Error(`Connection error: ${e.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -52,6 +52,7 @@ export declare namespace wa {
|
||||
pairingCode?: string;
|
||||
authState?: { state: AuthenticationState; saveCreds: () => void };
|
||||
name?: string;
|
||||
ownerJid?: string;
|
||||
wuid?: string;
|
||||
profileName?: string;
|
||||
profilePictureUrl?: string;
|
||||
|
||||
@ -26,8 +26,8 @@ import cors from 'cors';
|
||||
import express, { json, NextFunction, Request, Response, urlencoded } from 'express';
|
||||
import { join } from 'path';
|
||||
|
||||
function initWA() {
|
||||
waMonitor.loadInstance();
|
||||
async function initWA() {
|
||||
await waMonitor.loadInstance();
|
||||
}
|
||||
|
||||
async function bootstrap() {
|
||||
@ -159,7 +159,9 @@ async function bootstrap() {
|
||||
|
||||
server.listen(httpServer.PORT, () => logger.log(httpServer.TYPE.toUpperCase() + ' - ON: ' + httpServer.PORT));
|
||||
|
||||
initWA();
|
||||
initWA().catch((error) => {
|
||||
logger.error('Error loading instances: ' + error);
|
||||
});
|
||||
|
||||
onUnexpectedError();
|
||||
}
|
||||
|
||||
@ -3,8 +3,6 @@ import fs from 'fs';
|
||||
import i18next from 'i18next';
|
||||
import path from 'path';
|
||||
|
||||
const __dirname = path.resolve(process.cwd(), 'src', 'utils');
|
||||
|
||||
const languages = ['en', 'pt-BR', 'es'];
|
||||
const translationsPath = path.join(__dirname, 'translations');
|
||||
const configService: ConfigService = new ConfigService();
|
||||
|
||||
@ -1,5 +1,7 @@
|
||||
import { socksDispatcher } from 'fetch-socks';
|
||||
import { HttpsProxyAgent } from 'https-proxy-agent';
|
||||
import { SocksProxyAgent } from 'socks-proxy-agent';
|
||||
import { ProxyAgent } from 'undici';
|
||||
|
||||
type Proxy = {
|
||||
host: string;
|
||||
@ -17,12 +19,23 @@ function selectProxyAgent(proxyUrl: string): HttpsProxyAgent<string> | SocksProx
|
||||
// the end so, we add the protocol constants without the `:` to avoid confusion.
|
||||
const PROXY_HTTP_PROTOCOL = 'http:';
|
||||
const PROXY_SOCKS_PROTOCOL = 'socks:';
|
||||
const PROXY_SOCKS5_PROTOCOL = 'socks5:';
|
||||
|
||||
switch (url.protocol) {
|
||||
case PROXY_HTTP_PROTOCOL:
|
||||
return new HttpsProxyAgent(url);
|
||||
case PROXY_SOCKS_PROTOCOL:
|
||||
return new SocksProxyAgent(url);
|
||||
case PROXY_SOCKS5_PROTOCOL: {
|
||||
let urlSocks = '';
|
||||
|
||||
if (url.username && url.password) {
|
||||
urlSocks = `socks://${url.username}:${url.password}@${url.hostname}:${url.port}`;
|
||||
} else {
|
||||
urlSocks = `socks://${url.hostname}:${url.port}`;
|
||||
}
|
||||
|
||||
return new SocksProxyAgent(urlSocks);
|
||||
}
|
||||
default:
|
||||
throw new Error(`Unsupported proxy protocol: ${url.protocol}`);
|
||||
}
|
||||
@ -42,3 +55,57 @@ export function makeProxyAgent(proxy: Proxy | string): HttpsProxyAgent<string> |
|
||||
|
||||
return selectProxyAgent(proxyUrl);
|
||||
}
|
||||
|
||||
export function makeProxyAgentUndici(proxy: Proxy | string): ProxyAgent {
|
||||
let proxyUrl: string;
|
||||
let protocol: string;
|
||||
|
||||
if (typeof proxy === 'string') {
|
||||
const url = new URL(proxy);
|
||||
protocol = url.protocol.replace(':', '');
|
||||
proxyUrl = proxy;
|
||||
} else {
|
||||
const { host, password, port, protocol: proto, username } = proxy;
|
||||
protocol = (proto || 'http').replace(':', '');
|
||||
|
||||
if (protocol === 'socks') {
|
||||
protocol = 'socks5';
|
||||
}
|
||||
|
||||
const auth = username && password ? `${username}:${password}@` : '';
|
||||
proxyUrl = `${protocol}://${auth}${host}:${port}`;
|
||||
}
|
||||
|
||||
protocol = protocol.toLowerCase();
|
||||
|
||||
const PROXY_HTTP_PROTOCOL = 'http';
|
||||
const PROXY_HTTPS_PROTOCOL = 'https';
|
||||
const PROXY_SOCKS4_PROTOCOL = 'socks4';
|
||||
const PROXY_SOCKS5_PROTOCOL = 'socks5';
|
||||
|
||||
switch (protocol) {
|
||||
case PROXY_HTTP_PROTOCOL:
|
||||
case PROXY_HTTPS_PROTOCOL:
|
||||
return new ProxyAgent(proxyUrl);
|
||||
|
||||
case PROXY_SOCKS4_PROTOCOL:
|
||||
case PROXY_SOCKS5_PROTOCOL: {
|
||||
let type: 4 | 5 = 5;
|
||||
|
||||
if (PROXY_SOCKS4_PROTOCOL === protocol) type = 4;
|
||||
|
||||
const url = new URL(proxyUrl);
|
||||
|
||||
return socksDispatcher({
|
||||
type: type,
|
||||
host: url.hostname,
|
||||
port: Number(url.port),
|
||||
userId: url.username || undefined,
|
||||
password: url.password || undefined,
|
||||
});
|
||||
}
|
||||
|
||||
default:
|
||||
throw new Error(`Unsupported proxy protocol: ${protocol}`);
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,7 +1,10 @@
|
||||
import { prismaRepository } from '@api/server.module';
|
||||
import { configService, Database } from '@config/env.config';
|
||||
import { Logger } from '@config/logger.config';
|
||||
import dayjs from 'dayjs';
|
||||
|
||||
const logger = new Logger('OnWhatsappCache');
|
||||
|
||||
function getAvailableNumbers(remoteJid: string) {
|
||||
const numbersAvailable: string[] = [];
|
||||
|
||||
@ -11,6 +14,11 @@ function getAvailableNumbers(remoteJid: string) {
|
||||
|
||||
const [number, domain] = remoteJid.split('@');
|
||||
|
||||
// TODO: Se já for @lid, retornar apenas ele mesmo SEM adicionar @domain novamente
|
||||
if (domain === 'lid' || domain === 'g.us') {
|
||||
return [remoteJid]; // Retorna direto para @lid e @g.us
|
||||
}
|
||||
|
||||
// Brazilian numbers
|
||||
if (remoteJid.startsWith('55')) {
|
||||
const numberWithDigit =
|
||||
@ -47,36 +55,128 @@ function getAvailableNumbers(remoteJid: string) {
|
||||
numbersAvailable.push(remoteJid);
|
||||
}
|
||||
|
||||
// TODO: Adiciona @domain apenas para números que não são @lid
|
||||
return numbersAvailable.map((number) => `${number}@${domain}`);
|
||||
}
|
||||
|
||||
interface ISaveOnWhatsappCacheParams {
|
||||
remoteJid: string;
|
||||
lid?: string;
|
||||
remoteJidAlt?: string;
|
||||
lid?: 'lid' | undefined;
|
||||
}
|
||||
|
||||
function normalizeJid(jid: string | null | undefined): string | null {
|
||||
if (!jid) return null;
|
||||
return jid.startsWith('+') ? jid.slice(1) : jid;
|
||||
}
|
||||
|
||||
export async function saveOnWhatsappCache(data: ISaveOnWhatsappCacheParams[]) {
|
||||
if (configService.get<Database>('DATABASE').SAVE_DATA.IS_ON_WHATSAPP) {
|
||||
const upsertsQuery = data.map((item) => {
|
||||
const remoteJid = item.remoteJid.startsWith('+') ? item.remoteJid.slice(1) : item.remoteJid;
|
||||
const numbersAvailable = getAvailableNumbers(remoteJid);
|
||||
|
||||
return prismaRepository.isOnWhatsapp.upsert({
|
||||
create: {
|
||||
remoteJid: remoteJid,
|
||||
jidOptions: numbersAvailable.join(','),
|
||||
lid: item.lid,
|
||||
},
|
||||
update: {
|
||||
jidOptions: numbersAvailable.join(','),
|
||||
lid: item.lid,
|
||||
},
|
||||
where: { remoteJid: remoteJid },
|
||||
});
|
||||
});
|
||||
|
||||
await prismaRepository.$transaction(upsertsQuery);
|
||||
if (!configService.get<Database>('DATABASE').SAVE_DATA.IS_ON_WHATSAPP) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Processa todos os itens em paralelo para melhor performance
|
||||
const processingPromises = data.map(async (item) => {
|
||||
try {
|
||||
const remoteJid = normalizeJid(item.remoteJid);
|
||||
if (!remoteJid) {
|
||||
logger.warn('[saveOnWhatsappCache] Item skipped, missing remoteJid.');
|
||||
return;
|
||||
}
|
||||
|
||||
const altJidNormalized = normalizeJid(item.remoteJidAlt);
|
||||
const lidAltJid = altJidNormalized && altJidNormalized.includes('@lid') ? altJidNormalized : null;
|
||||
|
||||
const baseJids = [remoteJid]; // Garante que o remoteJid esteja na lista inicial
|
||||
if (lidAltJid) {
|
||||
baseJids.push(lidAltJid);
|
||||
}
|
||||
|
||||
const expandedJids = baseJids.flatMap((jid) => getAvailableNumbers(jid));
|
||||
|
||||
// 1. Busca entrada por jidOptions e também remoteJid
|
||||
// Às vezes acontece do remoteJid atual NÃO ESTAR no jidOptions ainda, ocasionando o erro:
|
||||
// 'Unique constraint failed on the fields: (`remoteJid`)'
|
||||
// Isso acontece principalmente em grupos que possuem o número do criador no ID (ex.: '559911223345-1234567890@g.us')
|
||||
const existingRecord = await prismaRepository.isOnWhatsapp.findFirst({
|
||||
where: {
|
||||
OR: [
|
||||
...expandedJids.map((jid) => ({ jidOptions: { contains: jid } })),
|
||||
{ remoteJid: remoteJid }, // TODO: Descobrir o motivo que causa o remoteJid não estar (às vezes) incluso na lista de jidOptions
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
logger.verbose(
|
||||
`[saveOnWhatsappCache] Register exists for [${expandedJids.join(',')}]? => ${existingRecord ? existingRecord.remoteJid : 'Not found'}`,
|
||||
);
|
||||
|
||||
// 2. Unifica todos os JIDs usando um Set para garantir valores únicos
|
||||
const finalJidOptions = new Set(expandedJids);
|
||||
|
||||
if (lidAltJid) {
|
||||
finalJidOptions.add(lidAltJid);
|
||||
}
|
||||
|
||||
if (existingRecord?.jidOptions) {
|
||||
existingRecord.jidOptions.split(',').forEach((jid) => finalJidOptions.add(jid));
|
||||
}
|
||||
|
||||
// 3. Prepara o payload final
|
||||
// Ordena os JIDs para garantir consistência na string final
|
||||
const sortedJidOptions = [...finalJidOptions].sort();
|
||||
const newJidOptionsString = sortedJidOptions.join(',');
|
||||
const newLid = item.lid === 'lid' || item.remoteJid?.includes('@lid') ? 'lid' : null;
|
||||
|
||||
const dataPayload = {
|
||||
remoteJid: remoteJid,
|
||||
jidOptions: newJidOptionsString,
|
||||
lid: newLid,
|
||||
};
|
||||
|
||||
// 4. Decide entre Criar ou Atualizar
|
||||
if (existingRecord) {
|
||||
// Compara a string de JIDs ordenada existente com a nova
|
||||
const existingJidOptionsString = existingRecord.jidOptions
|
||||
? existingRecord.jidOptions.split(',').sort().join(',')
|
||||
: '';
|
||||
|
||||
const isDataSame =
|
||||
existingRecord.remoteJid === dataPayload.remoteJid &&
|
||||
existingJidOptionsString === dataPayload.jidOptions &&
|
||||
existingRecord.lid === dataPayload.lid;
|
||||
|
||||
if (isDataSame) {
|
||||
logger.verbose(`[saveOnWhatsappCache] Data for ${remoteJid} is already up-to-date. Skipping update.`);
|
||||
return; // Pula para o próximo item
|
||||
}
|
||||
|
||||
// Os dados são diferentes, então atualiza
|
||||
logger.verbose(
|
||||
`[saveOnWhatsappCache] Register exists, updating: remoteJid=${remoteJid}, jidOptions=${dataPayload.jidOptions}, lid=${dataPayload.lid}`,
|
||||
);
|
||||
await prismaRepository.isOnWhatsapp.update({
|
||||
where: { id: existingRecord.id },
|
||||
data: dataPayload,
|
||||
});
|
||||
} else {
|
||||
// Cria nova entrada
|
||||
logger.verbose(
|
||||
`[saveOnWhatsappCache] Register does not exist, creating: remoteJid=${remoteJid}, jidOptions=${dataPayload.jidOptions}, lid=${dataPayload.lid}`,
|
||||
);
|
||||
await prismaRepository.isOnWhatsapp.create({
|
||||
data: dataPayload,
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
// Loga o erro mas não para a execução dos outros promises
|
||||
logger.error(`[saveOnWhatsappCache] Error processing item for ${item.remoteJid}: `);
|
||||
logger.error(e);
|
||||
}
|
||||
});
|
||||
|
||||
// Espera todas as operações paralelas terminarem
|
||||
await Promise.allSettled(processingPromises);
|
||||
}
|
||||
|
||||
export async function getOnWhatsappCache(remoteJids: string[]) {
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
import { prismaRepository } from '@api/server.module';
|
||||
import { CacheService } from '@api/services/cache.service';
|
||||
import { CacheConf, configService } from '@config/env.config';
|
||||
import { Logger } from '@config/logger.config';
|
||||
import { INSTANCE_DIR } from '@config/path.config';
|
||||
import { AuthenticationState, BufferJSON, initAuthCreds, WAProto as proto } from 'baileys';
|
||||
import fs from 'fs/promises';
|
||||
@ -73,12 +74,15 @@ async function fileExists(file: string): Promise<any> {
|
||||
}
|
||||
}
|
||||
|
||||
const logger = new Logger('useMultiFileAuthStatePrisma');
|
||||
|
||||
export default async function useMultiFileAuthStatePrisma(
|
||||
sessionId: string,
|
||||
cache: CacheService,
|
||||
): Promise<{
|
||||
state: AuthenticationState;
|
||||
saveCreds: () => Promise<void>;
|
||||
removeCreds: () => Promise<void>;
|
||||
}> {
|
||||
const localFolder = path.join(INSTANCE_DIR, sessionId);
|
||||
const localFile = (key: string) => path.join(localFolder, fixFileName(key) + '.json');
|
||||
@ -142,6 +146,26 @@ export default async function useMultiFileAuthStatePrisma(
|
||||
}
|
||||
}
|
||||
|
||||
async function removeCreds(): Promise<any> {
|
||||
const cacheConfig = configService.get<CacheConf>('CACHE');
|
||||
|
||||
// Redis
|
||||
try {
|
||||
if (cacheConfig.REDIS.ENABLED) {
|
||||
await cache.delete(sessionId);
|
||||
logger.info({ action: 'redis.delete', sessionId });
|
||||
|
||||
return;
|
||||
}
|
||||
} catch (err) {
|
||||
logger.warn({ action: 'redis.delete', sessionId, err });
|
||||
}
|
||||
|
||||
logger.info({ action: 'auth.key.delete', sessionId });
|
||||
|
||||
await deleteAuthKey(sessionId);
|
||||
}
|
||||
|
||||
let creds = await readData('creds');
|
||||
if (!creds) {
|
||||
creds = initAuthCreds();
|
||||
@ -183,5 +207,7 @@ export default async function useMultiFileAuthStatePrisma(
|
||||
saveCreds: () => {
|
||||
return writeData(creds, 'creds');
|
||||
},
|
||||
|
||||
removeCreds,
|
||||
};
|
||||
}
|
||||
|
||||
@ -39,7 +39,11 @@ import { Logger } from '@config/logger.config';
|
||||
import { AuthenticationCreds, AuthenticationState, BufferJSON, initAuthCreds, proto, SignalDataTypeMap } from 'baileys';
|
||||
import { isNotEmpty } from 'class-validator';
|
||||
|
||||
export type AuthState = { state: AuthenticationState; saveCreds: () => Promise<void> };
|
||||
export type AuthState = {
|
||||
state: AuthenticationState;
|
||||
saveCreds: () => Promise<void>;
|
||||
removeCreds: () => Promise<void>;
|
||||
};
|
||||
|
||||
export class AuthStateProvider {
|
||||
constructor(private readonly providerFiles: ProviderFiles) {}
|
||||
@ -86,6 +90,18 @@ export class AuthStateProvider {
|
||||
return response;
|
||||
};
|
||||
|
||||
const removeCreds = async () => {
|
||||
const [response, error] = await this.providerFiles.removeSession(instance);
|
||||
if (error) {
|
||||
// this.logger.error(['removeData', error?.message, error?.stack]);
|
||||
return;
|
||||
}
|
||||
|
||||
logger.info({ action: 'remove.session', instance, response });
|
||||
|
||||
return;
|
||||
};
|
||||
|
||||
const creds: AuthenticationCreds = (await readData('creds')) || initAuthCreds();
|
||||
|
||||
return {
|
||||
@ -126,6 +142,10 @@ export class AuthStateProvider {
|
||||
saveCreds: async () => {
|
||||
return await writeData(creds, 'creds');
|
||||
},
|
||||
|
||||
removeCreds,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const logger = new Logger('useMultiFileAuthStatePrisma');
|
||||
|
||||
@ -8,6 +8,7 @@ export async function useMultiFileAuthStateRedisDb(
|
||||
): Promise<{
|
||||
state: AuthenticationState;
|
||||
saveCreds: () => Promise<void>;
|
||||
removeCreds: () => Promise<void>;
|
||||
}> {
|
||||
const logger = new Logger('useMultiFileAuthStateRedisDb');
|
||||
|
||||
@ -36,6 +37,16 @@ export async function useMultiFileAuthStateRedisDb(
|
||||
}
|
||||
};
|
||||
|
||||
async function removeCreds(): Promise<any> {
|
||||
try {
|
||||
logger.warn({ action: 'redis.delete', instanceName });
|
||||
|
||||
return await cache.delete(instanceName);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const creds: AuthenticationCreds = (await readData('creds')) || initAuthCreds();
|
||||
|
||||
return {
|
||||
@ -76,5 +87,7 @@ export async function useMultiFileAuthStateRedisDb(
|
||||
saveCreds: async () => {
|
||||
return await writeData(creds, 'creds');
|
||||
},
|
||||
|
||||
removeCreds,
|
||||
};
|
||||
}
|
||||
|
||||
@ -195,8 +195,9 @@ export const contactValidateSchema: JSONSchema7 = {
|
||||
_id: { type: 'string', minLength: 1 },
|
||||
pushName: { type: 'string', minLength: 1 },
|
||||
id: { type: 'string', minLength: 1 },
|
||||
remoteJid: { type: 'string', minLength: 1 },
|
||||
},
|
||||
...isNotEmpty('_id', 'id', 'pushName'),
|
||||
...isNotEmpty('_id', 'id', 'pushName', 'remoteJid'),
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
32
src/validate/templateDelete.schema.ts
Normal file
32
src/validate/templateDelete.schema.ts
Normal file
@ -0,0 +1,32 @@
|
||||
import { JSONSchema7 } from 'json-schema';
|
||||
import { v4 } from 'uuid';
|
||||
|
||||
const isNotEmpty = (...propertyNames: string[]): JSONSchema7 => {
|
||||
const properties: Record<string, unknown> = {};
|
||||
propertyNames.forEach(
|
||||
(property) =>
|
||||
(properties[property] = {
|
||||
minLength: 1,
|
||||
description: `The "${property}" cannot be empty`,
|
||||
}),
|
||||
);
|
||||
return {
|
||||
if: {
|
||||
propertyNames: {
|
||||
enum: [...propertyNames],
|
||||
},
|
||||
},
|
||||
then: { properties },
|
||||
} as JSONSchema7;
|
||||
};
|
||||
|
||||
export const templateDeleteSchema: JSONSchema7 = {
|
||||
$id: v4(),
|
||||
type: 'object',
|
||||
properties: {
|
||||
name: { type: 'string' },
|
||||
hsmId: { type: 'string' },
|
||||
},
|
||||
required: ['name'],
|
||||
...isNotEmpty('name'),
|
||||
};
|
||||
35
src/validate/templateEdit.schema.ts
Normal file
35
src/validate/templateEdit.schema.ts
Normal file
@ -0,0 +1,35 @@
|
||||
import { JSONSchema7 } from 'json-schema';
|
||||
import { v4 } from 'uuid';
|
||||
|
||||
const isNotEmpty = (...propertyNames: string[]): JSONSchema7 => {
|
||||
const properties: Record<string, unknown> = {};
|
||||
propertyNames.forEach(
|
||||
(property) =>
|
||||
(properties[property] = {
|
||||
minLength: 1,
|
||||
description: `The "${property}" cannot be empty`,
|
||||
}),
|
||||
);
|
||||
return {
|
||||
if: {
|
||||
propertyNames: {
|
||||
enum: [...propertyNames],
|
||||
},
|
||||
},
|
||||
then: { properties },
|
||||
} as JSONSchema7;
|
||||
};
|
||||
|
||||
export const templateEditSchema: JSONSchema7 = {
|
||||
$id: v4(),
|
||||
type: 'object',
|
||||
properties: {
|
||||
templateId: { type: 'string' },
|
||||
category: { type: 'string', enum: ['AUTHENTICATION', 'MARKETING', 'UTILITY'] },
|
||||
allowCategoryChange: { type: 'boolean' },
|
||||
ttl: { type: 'number' },
|
||||
components: { type: 'array' },
|
||||
},
|
||||
required: ['templateId'],
|
||||
...isNotEmpty('templateId'),
|
||||
};
|
||||
@ -8,5 +8,7 @@ export * from './message.schema';
|
||||
export * from './proxy.schema';
|
||||
export * from './settings.schema';
|
||||
export * from './template.schema';
|
||||
export * from './templateDelete.schema';
|
||||
export * from './templateEdit.schema';
|
||||
export * from '@api/integrations/chatbot/chatbot.schema';
|
||||
export * from '@api/integrations/event/event.schema';
|
||||
|
||||
Loading…
Reference in New Issue
Block a user