Merge branch 'release/1.7.6'

This commit is contained in:
Davidson Gomes 2024-05-27 15:51:19 -03:00
commit ceee6a7e74
19 changed files with 445 additions and 107 deletions

View File

@ -2,18 +2,13 @@ name: Build Docker image
on: on:
push: push:
branches:
- develop
- main
tags: tags:
- v* - "v*.*.*"
workflow_dispatch:
jobs: jobs:
build: build_deploy:
name: Build and Deploy
runs-on: ubuntu-latest runs-on: ubuntu-latest
env:
GIT_REF: ${{ github.head_ref || github.ref_name }} # ref_name to get tags/branches
permissions: permissions:
contents: read contents: read
packages: write packages: write
@ -21,33 +16,35 @@ jobs:
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v4
- name: Docker meta
id: meta
uses: docker/metadata-action@v5
with:
images: atendai/evolution-api
tags: |
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
- name: Set up QEMU - name: Set up QEMU
uses: docker/setup-qemu-action@v3 uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx - name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3 uses: docker/setup-buildx-action@v3
- name: set docker tag
run: |
echo "DOCKER_TAG=ghcr.io/atendai/evolution-api:$GIT_REF" >> $GITHUB_ENV
- name: replace docker tag if main
if: github.ref_name == 'main'
run: |
echo "DOCKER_TAG=ghcr.io/atendai/evolution-api:latest" >> $GITHUB_ENV
- name: Login to GitHub Container Registry - name: Login to GitHub Container Registry
uses: docker/login-action@v3 uses: docker/login-action@v3
with: with:
registry: ghcr.io username: ${{ secrets.DOCKER_USERNAME }}
username: ${{ github.actor }} password: ${{ secrets.DOCKER_PASSWORD }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Build and push - name: Build and push
uses: docker/build-push-action@v2 id: docker_build
uses: docker/build-push-action@v5
with: with:
context: .
file: ./Dockerfile
platforms: linux/amd64,linux/arm64 platforms: linux/amd64,linux/arm64
push: true push: true
tags: ${{ env.DOCKER_TAG }} tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
- name: Image digest
run: echo ${{ steps.docker_build.outputs.digest }}

View File

@ -1,3 +1,13 @@
# 1.8.0 (develop)
### Feature
* Now in the manager, when logging in with the client's apikey, the listing only shows the instance corresponding to the provided apikey (only with MongoDB)
* New global mode for rabbitmq events
### Fixed
* Correction in message formatting when generated by AI as markdown in typebot
# 1.7.5 (2024-05-21 08:50) # 1.7.5 (2024-05-21 08:50)
### Fixed ### Fixed

View File

@ -47,9 +47,33 @@ DATABASE_SAVE_DATA_CONTACTS=false
DATABASE_SAVE_DATA_CHATS=false DATABASE_SAVE_DATA_CHATS=false
RABBITMQ_ENABLED=false RABBITMQ_ENABLED=false
RABBITMQ_RABBITMQ_MODE=global
RABBITMQ_EXCHANGE_NAME=evolution_exchange
RABBITMQ_URI=amqp://guest:guest@rabbitmq:5672 RABBITMQ_URI=amqp://guest:guest@rabbitmq:5672
RABBITMQ_EXCHANGE_NAME=evolution_exchange
RABBITMQ_GLOBAL_ENABLED=false
RABBITMQ_EVENTS_APPLICATION_STARTUP=false
RABBITMQ_EVENTS_QRCODE_UPDATED=true
RABBITMQ_EVENTS_MESSAGES_SET=true
RABBITMQ_EVENTS_MESSAGES_UPSERT=true
RABBITMQ_EVENTS_MESSAGES_UPDATE=true
RABBITMQ_EVENTS_MESSAGES_DELETE=true
RABBITMQ_EVENTS_SEND_MESSAGE=true
RABBITMQ_EVENTS_CONTACTS_SET=true
RABBITMQ_EVENTS_CONTACTS_UPSERT=true
RABBITMQ_EVENTS_CONTACTS_UPDATE=true
RABBITMQ_EVENTS_PRESENCE_UPDATE=true
RABBITMQ_EVENTS_CHATS_SET=true
RABBITMQ_EVENTS_CHATS_UPSERT=true
RABBITMQ_EVENTS_CHATS_UPDATE=true
RABBITMQ_EVENTS_CHATS_DELETE=true
RABBITMQ_EVENTS_GROUPS_UPSERT=true
RABBITMQ_EVENTS_GROUPS_UPDATE=true
RABBITMQ_EVENTS_GROUP_PARTICIPANTS_UPDATE=true
RABBITMQ_EVENTS_CONNECTION_UPDATE=true
RABBITMQ_EVENTS_LABELS_EDIT=true
RABBITMQ_EVENTS_LABELS_ASSOCIATION=true
RABBITMQ_EVENTS_CALL=true
RABBITMQ_EVENTS_TYPEBOT_START=false
RABBITMQ_EVENTS_TYPEBOT_CHANGE_STATUS=false
WEBSOCKET_ENABLED=false WEBSOCKET_ENABLED=false
WEBSOCKET_GLOBAL_EVENTS=false WEBSOCKET_GLOBAL_EVENTS=false
@ -125,7 +149,7 @@ CHATWOOT_MESSAGE_DELETE=false # false | true
# If you leave this option as true, when sending a message in Chatwoot, the client's last message will be marked as read on WhatsApp. # If you leave this option as true, when sending a message in Chatwoot, the client's last message will be marked as read on WhatsApp.
CHATWOOT_MESSAGE_READ=false # false | true CHATWOOT_MESSAGE_READ=false # false | true
# This db connection is used to import messages from whatsapp to chatwoot database # This db connection is used to import messages from whatsapp to chatwoot database
CHATWOOT_IMPORT_DATABASE_CONNECTION_URI=postgres://user:password@hostname:port/dbname CHATWOOT_IMPORT_DATABASE_CONNECTION_URI=postgres://user:password@hostname:port/dbname?sslmode=disable
CHATWOOT_IMPORT_DATABASE_PLACEHOLDER_MEDIA_MESSAGE=true CHATWOOT_IMPORT_DATABASE_PLACEHOLDER_MEDIA_MESSAGE=true
CACHE_REDIS_ENABLED=false CACHE_REDIS_ENABLED=false

View File

@ -1,6 +1,6 @@
FROM node:20.7.0-alpine AS builder FROM node:20.7.0-alpine AS builder
LABEL version="1.7.5" description="Api to control whatsapp features through http requests." LABEL version="1.8.0" description="Api to control whatsapp features through http requests."
LABEL maintainer="Davidson Gomes" git="https://github.com/DavidsonGomes" LABEL maintainer="Davidson Gomes" git="https://github.com/DavidsonGomes"
LABEL contact="contato@agenciadgcode.com" LABEL contact="contato@agenciadgcode.com"
@ -59,9 +59,35 @@ ENV DATABASE_SAVE_DATA_CONTACTS=false
ENV DATABASE_SAVE_DATA_CHATS=false ENV DATABASE_SAVE_DATA_CHATS=false
ENV RABBITMQ_ENABLED=false ENV RABBITMQ_ENABLED=false
ENV RABBITMQ_MODE=global
ENV RABBITMQ_EXCHANGE_NAME=evolution_exchange
ENV RABBITMQ_URI=amqp://guest:guest@rabbitmq:5672 ENV RABBITMQ_URI=amqp://guest:guest@rabbitmq:5672
ENV RABBITMQ_EXCHANGE_NAME=evolution_exchange
ENV RABBITMQ_GLOBAL_ENABLED=false
ENV RABBITMQ_EVENTS_APPLICATION_STARTUP=false
ENV RABBITMQ_EVENTS_INSTANCE_CREATE=false
ENV RABBITMQ_EVENTS_INSTANCE_DELETE=false
ENV RABBITMQ_EVENTS_QRCODE_UPDATED=true
ENV RABBITMQ_EVENTS_MESSAGES_SET=true
ENV RABBITMQ_EVENTS_MESSAGES_UPSERT=true
ENV RABBITMQ_EVENTS_MESSAGES_UPDATE=true
ENV RABBITMQ_EVENTS_MESSAGES_DELETE=true
ENV RABBITMQ_EVENTS_SEND_MESSAGE=true
ENV RABBITMQ_EVENTS_CONTACTS_SET=true
ENV RABBITMQ_EVENTS_CONTACTS_UPSERT=true
ENV RABBITMQ_EVENTS_CONTACTS_UPDATE=true
ENV RABBITMQ_EVENTS_PRESENCE_UPDATE=true
ENV RABBITMQ_EVENTS_CHATS_SET=true
ENV RABBITMQ_EVENTS_CHATS_UPSERT=true
ENV RABBITMQ_EVENTS_CHATS_UPDATE=true
ENV RABBITMQ_EVENTS_CHATS_DELETE=true
ENV RABBITMQ_EVENTS_GROUPS_UPSERT=true
ENV RABBITMQ_EVENTS_GROUPS_UPDATE=true
ENV RABBITMQ_EVENTS_GROUP_PARTICIPANTS_UPDATE=true
ENV RABBITMQ_EVENTS_CONNECTION_UPDATE=true
ENV RABBITMQ_EVENTS_LABELS_EDIT=true
ENV RABBITMQ_EVENTS_LABELS_ASSOCIATION=true
ENV RABBITMQ_EVENTS_CALL=true
ENV RABBITMQ_EVENTS_TYPEBOT_START=false
ENV RABBITMQ_EVENTS_TYPEBOT_CHANGE_STATUS=false
ENV WEBSOCKET_ENABLED=false ENV WEBSOCKET_ENABLED=false
ENV WEBSOCKET_GLOBAL_EVENTS=false ENV WEBSOCKET_GLOBAL_EVENTS=false

View File

@ -1,6 +1,6 @@
{ {
"name": "evolution-api", "name": "evolution-api",
"version": "1.7.5", "version": "1.8.0",
"description": "Rest api for communication with WhatsApp", "description": "Rest api for communication with WhatsApp",
"main": "./dist/src/main.js", "main": "./dist/src/main.js",
"scripts": { "scripts": {

View File

@ -3,9 +3,9 @@ import { isURL } from 'class-validator';
import EventEmitter2 from 'eventemitter2'; import EventEmitter2 from 'eventemitter2';
import { v4 } from 'uuid'; import { v4 } from 'uuid';
import { ConfigService, HttpServer, WaBusiness } from '../../config/env.config'; import { Auth, ConfigService, HttpServer, WaBusiness } from '../../config/env.config';
import { Logger } from '../../config/logger.config'; import { Logger } from '../../config/logger.config';
import { BadRequestException, InternalServerErrorException } from '../../exceptions'; import { BadRequestException, InternalServerErrorException, UnauthorizedException } from '../../exceptions';
import { InstanceDto, SetPresenceDto } from '../dto/instance.dto'; import { InstanceDto, SetPresenceDto } from '../dto/instance.dto';
import { ChatwootService } from '../integrations/chatwoot/services/chatwoot.service'; import { ChatwootService } from '../integrations/chatwoot/services/chatwoot.service';
import { RabbitmqService } from '../integrations/rabbitmq/services/rabbitmq.service'; import { RabbitmqService } from '../integrations/rabbitmq/services/rabbitmq.service';
@ -679,11 +679,26 @@ export class InstanceController {
}; };
} }
public async fetchInstances({ instanceName, instanceId, number }: InstanceDto) { public async fetchInstances({ instanceName, instanceId, number }: InstanceDto, key: string) {
if (instanceName) { const env = this.configService.get<Auth>('AUTHENTICATION').API_KEY;
this.logger.verbose('requested fetchInstances from ' + instanceName + ' instance');
this.logger.verbose('instanceName: ' + instanceName); let name = instanceName;
return this.waMonitor.instanceInfo(instanceName); let arrayReturn = false;
if (env.KEY !== key) {
const instanceByKey = await this.repository.auth.findByKey(key);
if (instanceByKey) {
name = instanceByKey._id;
arrayReturn = true;
} else {
throw new UnauthorizedException();
}
}
if (name) {
this.logger.verbose('requested fetchInstances from ' + name + ' instance');
this.logger.verbose('instanceName: ' + name);
return this.waMonitor.instanceInfo(name, arrayReturn);
} else if (instanceId || number) { } else if (instanceId || number) {
return this.waMonitor.instanceInfoById(instanceId, number); return this.waMonitor.instanceInfoById(instanceId, number);
} }

View File

@ -59,6 +59,10 @@ async function apikey(req: Request, _: Response, next: NextFunction) {
const env = configService.get<Auth>('AUTHENTICATION').API_KEY; const env = configService.get<Auth>('AUTHENTICATION').API_KEY;
const key = req.get('apikey'); const key = req.get('apikey');
if (!key) {
throw new UnauthorizedException();
}
if (env.KEY === key) { if (env.KEY === key) {
return next(); return next();
} }
@ -66,12 +70,21 @@ async function apikey(req: Request, _: Response, next: NextFunction) {
if ((req.originalUrl.includes('/instance/create') || req.originalUrl.includes('/instance/fetchInstances')) && !key) { if ((req.originalUrl.includes('/instance/create') || req.originalUrl.includes('/instance/fetchInstances')) && !key) {
throw new ForbiddenException('Missing global api key', 'The global api key must be set'); throw new ForbiddenException('Missing global api key', 'The global api key must be set');
} }
const param = req.params as unknown as InstanceDto;
try { try {
const param = req.params as unknown as InstanceDto; if (param?.instanceName) {
const instanceKey = await repository.auth.find(param.instanceName); const instanceKey = await repository.auth.find(param.instanceName);
if (instanceKey.apikey === key) { if (instanceKey?.apikey === key) {
return next(); return next();
}
} else {
if (req.originalUrl.includes('/instance/fetchInstances')) {
const instanceByKey = await repository.auth.findByKey(key);
if (instanceByKey) {
return next();
}
}
} }
} catch (error) { } catch (error) {
logger.error(error); logger.error(error);

View File

@ -42,6 +42,41 @@ export const getAMQP = (): amqp.Channel | null => {
return amqpChannel; return amqpChannel;
}; };
export const initGlobalQueues = () => {
logger.info('Initializing global queues');
const events = configService.get<Rabbitmq>('RABBITMQ').EVENTS;
if (!events) {
logger.warn('No events to initialize on AMQP');
return;
}
const eventKeys = Object.keys(events);
eventKeys.forEach((event) => {
if (events[event] === false) return;
const queueName = `${event.replace(/_/g, '.').toLowerCase()}`;
const amqp = getAMQP();
const exchangeName = 'evolution_exchange';
amqp.assertExchange(exchangeName, 'topic', {
durable: true,
autoDelete: false,
});
amqp.assertQueue(queueName, {
durable: true,
autoDelete: false,
arguments: {
'x-queue-type': 'quorum',
},
});
amqp.bindQueue(queueName, exchangeName, event);
});
};
export const initQueues = (instanceName: string, events: string[]) => { export const initQueues = (instanceName: string, events: string[]) => {
if (!events || !events.length) return; if (!events || !events.length) return;

View File

@ -519,18 +519,32 @@ export class TypebotService {
text += element.text; text += element.text;
} }
if ( if (element.children && element.type !== 'a') {
element.children &&
(element.type === 'p' ||
element.type === 'a' ||
element.type === 'inline-variable' ||
element.type === 'variable')
) {
for (const child of element.children) { for (const child of element.children) {
text += applyFormatting(child); text += applyFormatting(child);
} }
} }
if (element.type === 'p') {
text = text.trim() + '\n';
}
if (element.type === 'ol') {
text =
'\n' +
text
.split('\n')
.map((line, index) => (line ? `${index + 1}. ${line}` : ''))
.join('\n');
}
if (element.type === 'li') {
text = text
.split('\n')
.map((line) => (line ? ` ${line}` : ''))
.join('\n');
}
let formats = ''; let formats = '';
if (element.bold) { if (element.bold) {

View File

@ -68,6 +68,20 @@ export class AuthRepository extends Repository {
} }
} }
public async findByKey(key: string): Promise<AuthRaw> {
try {
this.logger.verbose('finding auth');
if (this.dbSettings.ENABLED) {
this.logger.verbose('finding auth in db');
return await this.authModel.findOne({ apikey: key });
}
return {};
} catch (error) {
return {};
}
}
public async list(): Promise<AuthRaw[]> { public async list(): Promise<AuthRaw[]> {
try { try {
if (this.dbSettings.ENABLED) { if (this.dbSettings.ENABLED) {

View File

@ -103,13 +103,15 @@ export class InstanceRouter extends RouterBroker {
logger.verbose('request body: '); logger.verbose('request body: ');
logger.verbose(req.body); logger.verbose(req.body);
const key = req.get('apikey');
logger.verbose('request query: '); logger.verbose('request query: ');
logger.verbose(req.query); logger.verbose(req.query);
const response = await this.dataValidate<InstanceDto>({ const response = await this.dataValidate<InstanceDto>({
request: req, request: req,
schema: null, schema: null,
ClassRef: InstanceDto, ClassRef: InstanceDto,
execute: (instance) => instanceController.fetchInstances(instance), execute: (instance) => instanceController.fetchInstances(instance, key),
}); });
return res.status(HttpStatus.OK).json(response); return res.status(HttpStatus.OK).json(response);

View File

@ -13,6 +13,7 @@ import {
Database, Database,
HttpServer, HttpServer,
Log, Log,
Rabbitmq,
Sqs, Sqs,
Webhook, Webhook,
Websocket, Websocket,
@ -305,6 +306,9 @@ export class ChannelStartupService {
this.localChatwoot.conversation_pending = data?.conversation_pending; this.localChatwoot.conversation_pending = data?.conversation_pending;
this.logger.verbose(`Chatwoot conversation pending: ${this.localChatwoot.conversation_pending}`); this.logger.verbose(`Chatwoot conversation pending: ${this.localChatwoot.conversation_pending}`);
this.localChatwoot.merge_brazil_contacts = data?.merge_brazil_contacts;
this.logger.verbose(`Chatwoot merge brazil contacts: ${this.localChatwoot.merge_brazil_contacts}`);
this.localChatwoot.import_contacts = data?.import_contacts; this.localChatwoot.import_contacts = data?.import_contacts;
this.logger.verbose(`Chatwoot import contacts: ${this.localChatwoot.import_contacts}`); this.logger.verbose(`Chatwoot import contacts: ${this.localChatwoot.import_contacts}`);
@ -328,6 +332,7 @@ export class ChannelStartupService {
this.logger.verbose(`Chatwoot sign delimiter: ${data.sign_delimiter}`); this.logger.verbose(`Chatwoot sign delimiter: ${data.sign_delimiter}`);
this.logger.verbose(`Chatwoot reopen conversation: ${data.reopen_conversation}`); this.logger.verbose(`Chatwoot reopen conversation: ${data.reopen_conversation}`);
this.logger.verbose(`Chatwoot conversation pending: ${data.conversation_pending}`); this.logger.verbose(`Chatwoot conversation pending: ${data.conversation_pending}`);
this.logger.verbose(`Chatwoot merge brazil contacts: ${data.merge_brazil_contacts}`);
this.logger.verbose(`Chatwoot import contacts: ${data.import_contacts}`); this.logger.verbose(`Chatwoot import contacts: ${data.import_contacts}`);
this.logger.verbose(`Chatwoot import messages: ${data.import_messages}`); this.logger.verbose(`Chatwoot import messages: ${data.import_messages}`);
this.logger.verbose(`Chatwoot days limit import messages: ${data.days_limit_import_messages}`); this.logger.verbose(`Chatwoot days limit import messages: ${data.days_limit_import_messages}`);
@ -356,7 +361,7 @@ export class ChannelStartupService {
this.logger.verbose(`Chatwoot sign delimiter: ${data.sign_delimiter}`); this.logger.verbose(`Chatwoot sign delimiter: ${data.sign_delimiter}`);
this.logger.verbose(`Chatwoot reopen conversation: ${data.reopen_conversation}`); this.logger.verbose(`Chatwoot reopen conversation: ${data.reopen_conversation}`);
this.logger.verbose(`Chatwoot conversation pending: ${data.conversation_pending}`); this.logger.verbose(`Chatwoot conversation pending: ${data.conversation_pending}`);
this.logger.verbose(`Chatwoot merge brazilian contacts: ${data.import_contacts}`); this.logger.verbose(`Chatwoot merge brazilian contacts: ${data.merge_brazil_contacts}`);
this.logger.verbose(`Chatwoot import contacts: ${data.import_contacts}`); this.logger.verbose(`Chatwoot import contacts: ${data.import_contacts}`);
this.logger.verbose(`Chatwoot import messages: ${data.import_messages}`); this.logger.verbose(`Chatwoot import messages: ${data.import_messages}`);
this.logger.verbose(`Chatwoot days limit import messages: ${data.days_limit_import_messages}`); this.logger.verbose(`Chatwoot days limit import messages: ${data.days_limit_import_messages}`);
@ -688,6 +693,9 @@ export class ChannelStartupService {
const rabbitmqLocal = this.localRabbitmq.events; const rabbitmqLocal = this.localRabbitmq.events;
const sqsLocal = this.localSqs.events; const sqsLocal = this.localSqs.events;
const serverUrl = this.configService.get<HttpServer>('SERVER').URL; const serverUrl = this.configService.get<HttpServer>('SERVER').URL;
const rabbitmqEnabled = this.configService.get<Rabbitmq>('RABBITMQ').ENABLED;
const rabbitmqGlobal = this.configService.get<Rabbitmq>('RABBITMQ').GLOBAL_ENABLED;
const rabbitmqEvents = this.configService.get<Rabbitmq>('RABBITMQ').EVENTS;
const we = event.replace(/[.-]/gm, '_').toUpperCase(); const we = event.replace(/[.-]/gm, '_').toUpperCase();
const transformedWe = we.replace(/_/gm, '-').toLowerCase(); const transformedWe = we.replace(/_/gm, '-').toLowerCase();
const tzoffset = new Date().getTimezoneOffset() * 60000; //offset in milliseconds const tzoffset = new Date().getTimezoneOffset() * 60000; //offset in milliseconds
@ -698,67 +706,134 @@ export class ChannelStartupService {
const tokenStore = await this.repository.auth.find(this.instanceName); const tokenStore = await this.repository.auth.find(this.instanceName);
const instanceApikey = tokenStore?.apikey || 'Apikey not found'; const instanceApikey = tokenStore?.apikey || 'Apikey not found';
if (this.localRabbitmq.enabled) { if (rabbitmqEnabled) {
const amqp = getAMQP(); const amqp = getAMQP();
if (this.localRabbitmq.enabled && amqp) {
if (amqp) {
if (Array.isArray(rabbitmqLocal) && rabbitmqLocal.includes(we)) { if (Array.isArray(rabbitmqLocal) && rabbitmqLocal.includes(we)) {
const exchangeName = this.instanceName ?? 'evolution_exchange'; const exchangeName = this.instanceName ?? 'evolution_exchange';
// await amqp.assertExchange(exchangeName, 'topic', { let retry = 0;
// durable: true,
// autoDelete: false,
// });
await this.assertExchangeAsync(amqp, exchangeName, 'topic', { while (retry < 3) {
durable: true, try {
autoDelete: false, await amqp.assertExchange(exchangeName, 'topic', {
}); durable: true,
autoDelete: false,
});
const queueName = `${this.instanceName}.${event}`; const queueName = `${this.instanceName}.${event}`;
await amqp.assertQueue(queueName, { await amqp.assertQueue(queueName, {
durable: true, durable: true,
autoDelete: false, autoDelete: false,
arguments: { arguments: {
'x-queue-type': 'quorum', 'x-queue-type': 'quorum',
}, },
}); });
await amqp.bindQueue(queueName, exchangeName, event); await amqp.bindQueue(queueName, exchangeName, event);
const message = { const message = {
event, event,
instance: this.instance.name, instance: this.instance.name,
data, data,
server_url: serverUrl, server_url: serverUrl,
date_time: now, date_time: now,
sender: this.wuid, sender: this.wuid,
}; };
if (expose && instanceApikey) { if (expose && instanceApikey) {
message['apikey'] = instanceApikey; message['apikey'] = instanceApikey;
}
await amqp.publish(exchangeName, event, Buffer.from(JSON.stringify(message)));
if (this.configService.get<Log>('LOG').LEVEL.includes('WEBHOOKS')) {
const logData = {
local: ChannelStartupService.name + '.sendData-RabbitMQ',
event,
instance: this.instance.name,
data,
server_url: serverUrl,
apikey: (expose && instanceApikey) || null,
date_time: now,
sender: this.wuid,
};
if (expose && instanceApikey) {
logData['apikey'] = instanceApikey;
}
this.logger.log(logData);
}
break;
} catch (error) {
retry++;
}
} }
}
}
await amqp.publish(exchangeName, event, Buffer.from(JSON.stringify(message))); if (rabbitmqGlobal && rabbitmqEvents[we] && amqp) {
const exchangeName = 'evolution_exchange';
if (this.configService.get<Log>('LOG').LEVEL.includes('WEBHOOKS')) { let retry = 0;
const logData = {
local: ChannelStartupService.name + '.sendData-RabbitMQ', while (retry < 3) {
try {
await amqp.assertExchange(exchangeName, 'topic', {
durable: true,
autoDelete: false,
});
const queueName = transformedWe;
await amqp.assertQueue(queueName, {
durable: true,
autoDelete: false,
arguments: {
'x-queue-type': 'quorum',
},
});
await amqp.bindQueue(queueName, exchangeName, event);
const message = {
event, event,
instance: this.instance.name, instance: this.instance.name,
data, data,
server_url: serverUrl, server_url: serverUrl,
apikey: (expose && instanceApikey) || null,
date_time: now, date_time: now,
sender: this.wuid, sender: this.wuid,
}; };
if (expose && instanceApikey) { if (expose && instanceApikey) {
logData['apikey'] = instanceApikey; message['apikey'] = instanceApikey;
}
await amqp.publish(exchangeName, event, Buffer.from(JSON.stringify(message)));
if (this.configService.get<Log>('LOG').LEVEL.includes('WEBHOOKS')) {
const logData = {
local: ChannelStartupService.name + '.sendData-RabbitMQ-Global',
event,
instance: this.instance.name,
data,
server_url: serverUrl,
apikey: (expose && instanceApikey) || null,
date_time: now,
sender: this.wuid,
};
if (expose && instanceApikey) {
logData['apikey'] = instanceApikey;
}
this.logger.log(logData);
} }
this.logger.log(logData); break;
} catch (error) {
retry++;
} }
} }
} }

View File

@ -1995,18 +1995,37 @@ export class BaileysStartupService extends ChannelStartupService {
const sender = isWA.jid; const sender = isWA.jid;
this.logger.verbose('Sending presence'); if (data?.options?.delay && data?.options?.delay > 20000) {
await this.client.presenceSubscribe(sender); let remainingDelay = data?.options.delay;
this.logger.verbose('Subscribing to presence'); while (remainingDelay > 20000) {
await this.client.presenceSubscribe(sender);
await this.client.sendPresenceUpdate(data.options?.presence ?? 'composing', sender); await this.client.sendPresenceUpdate((data?.options?.presence as WAPresence) ?? 'composing', sender);
this.logger.verbose('Sending presence update: ' + data.options?.presence ?? 'composing');
await delay(data.options.delay); await delay(20000);
this.logger.verbose('Set delay: ' + data.options.delay);
await this.client.sendPresenceUpdate('paused', sender); await this.client.sendPresenceUpdate('paused', sender);
this.logger.verbose('Sending presence update: paused');
remainingDelay -= 20000;
}
if (remainingDelay > 0) {
await this.client.presenceSubscribe(sender);
await this.client.sendPresenceUpdate((data?.options?.presence as WAPresence) ?? 'composing', sender);
await delay(remainingDelay);
await this.client.sendPresenceUpdate('paused', sender);
}
} else {
await this.client.presenceSubscribe(sender);
await this.client.sendPresenceUpdate((data?.options?.presence as WAPresence) ?? 'composing', sender);
await delay(data?.options?.delay);
await this.client.sendPresenceUpdate('paused', sender);
}
} catch (error) { } catch (error) {
this.logger.error(error); this.logger.error(error);
throw new BadRequestException(error.toString()); throw new BadRequestException(error.toString());

View File

@ -83,7 +83,7 @@ export class WAMonitoringService {
} }
} }
public async instanceInfo(instanceName?: string) { public async instanceInfo(instanceName?: string, arrayReturn = false) {
this.logger.verbose('get instance info'); this.logger.verbose('get instance info');
if (instanceName && !this.waInstances[instanceName]) { if (instanceName && !this.waInstances[instanceName]) {
throw new NotFoundException(`Instance "${instanceName}" not found`); throw new NotFoundException(`Instance "${instanceName}" not found`);
@ -171,6 +171,9 @@ export class WAMonitoringService {
this.logger.verbose('return instance info: ' + instances.length); this.logger.verbose('return instance info: ' + instances.length);
if (arrayReturn) {
return [instances.find((i) => i.instance.instanceName === instanceName) ?? instances];
}
return instances.find((i) => i.instance.instanceName === instanceName) ?? instances; return instances.find((i) => i.instance.instanceName === instanceName) ?? instances;
} }

View File

@ -69,6 +69,7 @@ export declare namespace wa {
number?: string; number?: string;
reopen_conversation?: boolean; reopen_conversation?: boolean;
conversation_pending?: boolean; conversation_pending?: boolean;
merge_brazil_contacts?: boolean;
import_contacts?: boolean; import_contacts?: boolean;
import_messages?: boolean; import_messages?: boolean;
days_limit_import_messages?: number; days_limit_import_messages?: number;

View File

@ -63,11 +63,42 @@ export type Database = {
SAVE_DATA: SaveData; SAVE_DATA: SaveData;
}; };
export type EventsRabbitmq = {
APPLICATION_STARTUP: boolean;
INSTANCE_CREATE: boolean;
INSTANCE_DELETE: boolean;
QRCODE_UPDATED: boolean;
MESSAGES_SET: boolean;
MESSAGES_UPSERT: boolean;
MESSAGES_UPDATE: boolean;
MESSAGES_DELETE: boolean;
SEND_MESSAGE: boolean;
CONTACTS_SET: boolean;
CONTACTS_UPDATE: boolean;
CONTACTS_UPSERT: boolean;
PRESENCE_UPDATE: boolean;
CHATS_SET: boolean;
CHATS_UPDATE: boolean;
CHATS_DELETE: boolean;
CHATS_UPSERT: boolean;
CONNECTION_UPDATE: boolean;
LABELS_EDIT: boolean;
LABELS_ASSOCIATION: boolean;
GROUPS_UPSERT: boolean;
GROUP_UPDATE: boolean;
GROUP_PARTICIPANTS_UPDATE: boolean;
CALL: boolean;
NEW_JWT_TOKEN: boolean;
TYPEBOT_START: boolean;
TYPEBOT_CHANGE_STATUS: boolean;
};
export type Rabbitmq = { export type Rabbitmq = {
ENABLED: boolean; ENABLED: boolean;
MODE: string; // global, single, isolated
EXCHANGE_NAME: string; // available for global and single, isolated mode will use instance name as exchange
URI: string; URI: string;
EXCHANGE_NAME: string;
GLOBAL_ENABLED: boolean;
EVENTS: EventsRabbitmq;
}; };
export type Sqs = { export type Sqs = {
@ -276,9 +307,38 @@ export class ConfigService {
}, },
RABBITMQ: { RABBITMQ: {
ENABLED: process.env?.RABBITMQ_ENABLED === 'true', ENABLED: process.env?.RABBITMQ_ENABLED === 'true',
MODE: process.env?.RABBITMQ_MODE || 'isolated', GLOBAL_ENABLED: process.env?.RABBITMQ_GLOBAL_ENABLED === 'true',
EXCHANGE_NAME: process.env?.RABBITMQ_EXCHANGE_NAME || 'evolution_exchange', EXCHANGE_NAME: process.env?.RABBITMQ_EXCHANGE_NAME || 'evolution_exchange',
URI: process.env.RABBITMQ_URI || '', URI: process.env.RABBITMQ_URI || '',
EVENTS: {
APPLICATION_STARTUP: process.env?.RABBITMQ_EVENTS_APPLICATION_STARTUP === 'true',
INSTANCE_CREATE: process.env?.RABBITMQ_EVENTS_INSTANCE_CREATE === 'true',
INSTANCE_DELETE: process.env?.RABBITMQ_EVENTS_INSTANCE_DELETE === 'true',
QRCODE_UPDATED: process.env?.RABBITMQ_EVENTS_QRCODE_UPDATED === 'true',
MESSAGES_SET: process.env?.RABBITMQ_EVENTS_MESSAGES_SET === 'true',
MESSAGES_UPSERT: process.env?.RABBITMQ_EVENTS_MESSAGES_UPSERT === 'true',
MESSAGES_UPDATE: process.env?.RABBITMQ_EVENTS_MESSAGES_UPDATE === 'true',
MESSAGES_DELETE: process.env?.RABBITMQ_EVENTS_MESSAGES_DELETE === 'true',
SEND_MESSAGE: process.env?.RABBITMQ_EVENTS_SEND_MESSAGE === 'true',
CONTACTS_SET: process.env?.RABBITMQ_EVENTS_CONTACTS_SET === 'true',
CONTACTS_UPDATE: process.env?.RABBITMQ_EVENTS_CONTACTS_UPDATE === 'true',
CONTACTS_UPSERT: process.env?.RABBITMQ_EVENTS_CONTACTS_UPSERT === 'true',
PRESENCE_UPDATE: process.env?.RABBITMQ_EVENTS_PRESENCE_UPDATE === 'true',
CHATS_SET: process.env?.RABBITMQ_EVENTS_CHATS_SET === 'true',
CHATS_UPDATE: process.env?.RABBITMQ_EVENTS_CHATS_UPDATE === 'true',
CHATS_UPSERT: process.env?.RABBITMQ_EVENTS_CHATS_UPSERT === 'true',
CHATS_DELETE: process.env?.RABBITMQ_EVENTS_CHATS_DELETE === 'true',
CONNECTION_UPDATE: process.env?.RABBITMQ_EVENTS_CONNECTION_UPDATE === 'true',
LABELS_EDIT: process.env?.RABBITMQ_EVENTS_LABELS_EDIT === 'true',
LABELS_ASSOCIATION: process.env?.RABBITMQ_EVENTS_LABELS_ASSOCIATION === 'true',
GROUPS_UPSERT: process.env?.RABBITMQ_EVENTS_GROUPS_UPSERT === 'true',
GROUP_UPDATE: process.env?.RABBITMQ_EVENTS_GROUPS_UPDATE === 'true',
GROUP_PARTICIPANTS_UPDATE: process.env?.RABBITMQ_EVENTS_GROUP_PARTICIPANTS_UPDATE === 'true',
CALL: process.env?.RABBITMQ_EVENTS_CALL === 'true',
NEW_JWT_TOKEN: process.env?.RABBITMQ_EVENTS_NEW_JWT_TOKEN === 'true',
TYPEBOT_START: process.env?.RABBITMQ_EVENTS_TYPEBOT_START === 'true',
TYPEBOT_CHANGE_STATUS: process.env?.RABBITMQ_EVENTS_TYPEBOT_CHANGE_STATUS === 'true',
},
}, },
SQS: { SQS: {
ENABLED: process.env?.SQS_ENABLED === 'true', ENABLED: process.env?.SQS_ENABLED === 'true',

View File

@ -79,9 +79,35 @@ DATABASE:
RABBITMQ: RABBITMQ:
ENABLED: false ENABLED: false
MODE: "global"
EXCHANGE_NAME: "evolution_exchange"
URI: "amqp://guest:guest@localhost:5672" URI: "amqp://guest:guest@localhost:5672"
EXCHANGE_NAME: evolution_exchange
GLOBAL_ENABLED: true
EVENTS:
APPLICATION_STARTUP: false
INSTANCE_CREATE: false
INSTANCE_DELETE: false
QRCODE_UPDATED: false
MESSAGES_SET: false
MESSAGES_UPSERT: true
MESSAGES_UPDATE: true
MESSAGES_DELETE: false
SEND_MESSAGE: false
CONTACTS_SET: false
CONTACTS_UPSERT: false
CONTACTS_UPDATE: false
PRESENCE_UPDATE: false
CHATS_SET: false
CHATS_UPSERT: false
CHATS_UPDATE: false
CHATS_DELETE: false
GROUPS_UPSERT: true
GROUP_UPDATE: true
GROUP_PARTICIPANTS_UPDATE: true
CONNECTION_UPDATE: true
CALL: false
# This events is used with Typebot
TYPEBOT_START: false
TYPEBOT_CHANGE_STATUS: false
SQS: SQS:
ENABLED: true ENABLED: true
@ -168,7 +194,7 @@ CHATWOOT:
# This db connection is used to import messages from whatsapp to chatwoot database # This db connection is used to import messages from whatsapp to chatwoot database
DATABASE: DATABASE:
CONNECTION: CONNECTION:
URI: "postgres://user:password@hostname:port/dbname" URI: "postgres://user:password@hostname:port/dbname?sslmode=disable"
PLACEHOLDER_MEDIA_MESSAGE: true PLACEHOLDER_MEDIA_MESSAGE: true
# Cache to optimize application performance # Cache to optimize application performance

View File

@ -25,7 +25,7 @@ info:
</font> </font>
[![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/26869335-5546d063-156b-4529-915f-909dd628c090?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D26869335-5546d063-156b-4529-915f-909dd628c090%26entityType%3Dcollection%26workspaceId%3D339a4ee7-378b-45c9-b5b8-fd2c0a9c2442) [![Run in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/26869335-5546d063-156b-4529-915f-909dd628c090?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D26869335-5546d063-156b-4529-915f-909dd628c090%26entityType%3Dcollection%26workspaceId%3D339a4ee7-378b-45c9-b5b8-fd2c0a9c2442)
version: 1.7.5 version: 1.8.0
contact: contact:
name: DavidsonGomes name: DavidsonGomes
email: contato@agenciadgcode.com email: contato@agenciadgcode.com

View File

@ -6,7 +6,7 @@ import cors from 'cors';
import express, { json, NextFunction, Request, Response, urlencoded } from 'express'; import express, { json, NextFunction, Request, Response, urlencoded } from 'express';
import { join } from 'path'; import { join } from 'path';
import { initAMQP } from './api/integrations/rabbitmq/libs/amqp.server'; import { initAMQP, initGlobalQueues } from './api/integrations/rabbitmq/libs/amqp.server';
import { initSQS } from './api/integrations/sqs/libs/sqs.server'; import { initSQS } from './api/integrations/sqs/libs/sqs.server';
import { initIO } from './api/integrations/websocket/libs/socket.server'; import { initIO } from './api/integrations/websocket/libs/socket.server';
import { HttpStatus, router } from './api/routes/index.router'; import { HttpStatus, router } from './api/routes/index.router';
@ -128,7 +128,11 @@ function bootstrap() {
initIO(server); initIO(server);
if (configService.get<Rabbitmq>('RABBITMQ')?.ENABLED) initAMQP(); if (configService.get<Rabbitmq>('RABBITMQ')?.ENABLED) {
initAMQP().then(() => {
if (configService.get<Rabbitmq>('RABBITMQ')?.GLOBAL_ENABLED) initGlobalQueues();
});
}
if (configService.get<Sqs>('SQS')?.ENABLED) initSQS(); if (configService.get<Sqs>('SQS')?.ENABLED) initSQS();