mirror of
https://github.com/EvolutionAPI/evolution-api.git
synced 2025-12-19 11:52:20 -06:00
Compare commits
52 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
633dbb82d3 | ||
|
|
95907b3cea | ||
|
|
14c210c771 | ||
|
|
00e7fcc46b | ||
|
|
720efcbcbf | ||
|
|
d95791cc18 | ||
|
|
d45b7af3b6 | ||
|
|
0ad3acaf07 | ||
|
|
e27818ecda | ||
|
|
ff21cf4d4c | ||
|
|
dc19c7fdec | ||
|
|
6c8ffd8ec6 | ||
|
|
96fdb210be | ||
|
|
84ad8e0d6e | ||
|
|
53361682f4 | ||
|
|
0ee243f284 | ||
|
|
26ff0b634f | ||
|
|
f44ab0f678 | ||
|
|
1f128747bb | ||
|
|
3bf975d90f | ||
|
|
92f8951be4 | ||
|
|
e071f56767 | ||
|
|
c85619efcf | ||
|
|
27f9ae1e56 | ||
|
|
7449102d95 | ||
|
|
234a2c71b5 | ||
|
|
4dd5533202 | ||
|
|
a4d1740754 | ||
|
|
1a2ea1c38a | ||
|
|
371ec9b8d5 | ||
|
|
5e288d57ea | ||
|
|
61bd5b3484 | ||
|
|
bb974e10f5 | ||
|
|
4ed1335f89 | ||
|
|
4274c7afdb | ||
|
|
27f67142c8 | ||
|
|
ac8aba6ba4 | ||
|
|
07ff61c070 | ||
|
|
3645ac6704 | ||
|
|
9764719245 | ||
|
|
b3aeed7fc1 | ||
|
|
5ae5d8546e | ||
|
|
d190d8b1af | ||
|
|
c45538684d | ||
|
|
575e7bf4c4 | ||
|
|
a4338d8472 | ||
|
|
7d542cf115 | ||
|
|
9c9a542bbe | ||
|
|
b6c56551bc | ||
|
|
1379228196 | ||
|
|
d6e19b9273 | ||
|
|
5e0e4051dc |
22
CHANGELOG.md
22
CHANGELOG.md
@@ -1,3 +1,25 @@
|
||||
# 1.7.4 (2024-04-28 09:46)
|
||||
|
||||
### Fixed
|
||||
* Adjusts in proxy on fetchAgent
|
||||
* Recovering messages lost with redis cache
|
||||
* Log when init redis cache service
|
||||
* Recovering messages lost with redis cache
|
||||
* Chatwoot inbox name
|
||||
* Update Baileys version
|
||||
|
||||
# 1.7.3 (2024-04-18 12:07)
|
||||
|
||||
### Fixed
|
||||
* Revert fix audio encoding
|
||||
* Recovering messages lost with redis cache
|
||||
* Adjusts in redis for save instances
|
||||
* Adjusts in proxy
|
||||
* Revert pull request #523
|
||||
* Added instance name on logs
|
||||
* Added support for Spanish
|
||||
* Fix error: invalid operator. The allowed operators for identifier are equal_to,not_equal_to in chatwoot
|
||||
|
||||
# 1.7.2 (2024-04-12 17:31)
|
||||
|
||||
### Feature
|
||||
|
||||
@@ -33,7 +33,10 @@ CLEAN_STORE_CHATS=true
|
||||
|
||||
# Permanent data storage
|
||||
DATABASE_ENABLED=false
|
||||
DATABASE_CONNECTION_URI=mongodb://root:root@mongodb:27017/?authSource=admin&readPreference=primary&ssl=false&directConnection=true
|
||||
DATABASE_CONNECTION_URI=mongodb://root:root@mongodb:27017/?authSource=admin &
|
||||
readPreference=primary &
|
||||
ssl=false &
|
||||
directConnection=true
|
||||
DATABASE_CONNECTION_DB_PREFIX_NAME=evdocker
|
||||
|
||||
# Choose the data you want to save in the application's database or store
|
||||
@@ -43,10 +46,6 @@ DATABASE_SAVE_MESSAGE_UPDATE=false
|
||||
DATABASE_SAVE_DATA_CONTACTS=false
|
||||
DATABASE_SAVE_DATA_CHATS=false
|
||||
|
||||
REDIS_ENABLED=false
|
||||
REDIS_URI=redis://redis:6379
|
||||
REDIS_PREFIX_KEY=evdocker
|
||||
|
||||
RABBITMQ_ENABLED=false
|
||||
RABBITMQ_RABBITMQ_MODE=global
|
||||
RABBITMQ_EXCHANGE_NAME=evolution_exchange
|
||||
@@ -129,6 +128,14 @@ CHATWOOT_MESSAGE_READ=false # false | true
|
||||
CHATWOOT_IMPORT_DATABASE_CONNECTION_URI=postgres://user:password@hostname:port/dbname
|
||||
CHATWOOT_IMPORT_DATABASE_PLACEHOLDER_MEDIA_MESSAGE=true
|
||||
|
||||
CACHE_REDIS_ENABLED=false
|
||||
CACHE_REDIS_URI=redis://redis:6379
|
||||
CACHE_REDIS_PREFIX_KEY=evolution
|
||||
CACHE_REDIS_TTL=604800
|
||||
CACHE_REDIS_SAVE_INSTANCES=false
|
||||
CACHE_LOCAL_ENABLED=false
|
||||
CACHE_LOCAL_TTL=604800
|
||||
|
||||
# Defines an authentication type for the api
|
||||
# We recommend using the apikey because it will allow you to use a custom token,
|
||||
# if you use jwt, a random token will be generated and may be expired and you will have to generate a new token
|
||||
|
||||
@@ -33,7 +33,10 @@ CLEAN_STORE_CHATS=true
|
||||
|
||||
# Permanent data storage
|
||||
DATABASE_ENABLED=true
|
||||
DATABASE_CONNECTION_URI=mongodb://root:root@mongodb:27017/?authSource=admin&readPreference=primary&ssl=false&directConnection=true
|
||||
DATABASE_CONNECTION_URI=mongodb://root:root@mongodb:27017/?authSource=admin &
|
||||
readPreference=primary &
|
||||
ssl=false &
|
||||
directConnection=true
|
||||
DATABASE_CONNECTION_DB_PREFIX_NAME=evolution
|
||||
|
||||
# Choose the data you want to save in the application's database or store
|
||||
@@ -43,10 +46,6 @@ DATABASE_SAVE_MESSAGE_UPDATE=false
|
||||
DATABASE_SAVE_DATA_CONTACTS=false
|
||||
DATABASE_SAVE_DATA_CHATS=false
|
||||
|
||||
REDIS_ENABLED=true
|
||||
REDIS_URI=redis://redis:6379
|
||||
REDIS_PREFIX_KEY=evolution
|
||||
|
||||
# Global Webhook Settings
|
||||
# Each instance's Webhook URL and events will be requested at the time it is created
|
||||
## Define a global webhook that will listen for enabled events from all instances
|
||||
@@ -87,6 +86,14 @@ CONFIG_SESSION_PHONE_NAME=chrome
|
||||
# Set qrcode display limit
|
||||
QRCODE_LIMIT=30
|
||||
|
||||
CACHE_REDIS_ENABLED=false
|
||||
CACHE_REDIS_URI=redis://redis:6379
|
||||
CACHE_REDIS_PREFIX_KEY=evolution
|
||||
CACHE_REDIS_TTL=604800
|
||||
CACHE_REDIS_SAVE_INSTANCES=false
|
||||
CACHE_LOCAL_ENABLED=false
|
||||
CACHE_LOCAL_TTL=604800
|
||||
|
||||
# Defines an authentication type for the api
|
||||
# We recommend using the apikey because it will allow you to use a custom token,
|
||||
# if you use jwt, a random token will be generated and may be expired and you will have to generate a new token
|
||||
|
||||
14
Dockerfile
14
Dockerfile
@@ -1,6 +1,6 @@
|
||||
FROM node:20.7.0-alpine AS builder
|
||||
|
||||
LABEL version="1.7.2" description="Api to control whatsapp features through http requests."
|
||||
LABEL version="1.7.4" description="Api to control whatsapp features through http requests."
|
||||
LABEL maintainer="Davidson Gomes" git="https://github.com/DavidsonGomes"
|
||||
LABEL contact="contato@agenciadgcode.com"
|
||||
|
||||
@@ -58,10 +58,6 @@ ENV DATABASE_SAVE_MESSAGE_UPDATE=false
|
||||
ENV DATABASE_SAVE_DATA_CONTACTS=false
|
||||
ENV DATABASE_SAVE_DATA_CHATS=false
|
||||
|
||||
ENV REDIS_ENABLED=false
|
||||
ENV REDIS_URI=redis://redis:6379
|
||||
ENV REDIS_PREFIX_KEY=evolution
|
||||
|
||||
ENV RABBITMQ_ENABLED=false
|
||||
ENV RABBITMQ_MODE=global
|
||||
ENV RABBITMQ_EXCHANGE_NAME=evolution_exchange
|
||||
@@ -129,6 +125,14 @@ ENV QRCODE_COLOR=#198754
|
||||
|
||||
ENV TYPEBOT_API_VERSION=latest
|
||||
|
||||
ENV CACHE_REDIS_ENABLED=false
|
||||
ENV CACHE_REDIS_URI=redis://redis:6379
|
||||
ENV CACHE_REDIS_PREFIX_KEY=evolution
|
||||
ENV CACHE_REDIS_TTL=604800
|
||||
ENV CACHE_REDIS_SAVE_INSTANCES=false
|
||||
ENV CACHE_LOCAL_ENABLED=false
|
||||
ENV CACHE_LOCAL_TTL=604800
|
||||
|
||||
ENV AUTHENTICATION_TYPE=apikey
|
||||
|
||||
ENV AUTHENTICATION_API_KEY=B6D711FCDE4D4FD5936544120E713976
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "evolution-api",
|
||||
"version": "1.7.2",
|
||||
"version": "1.7.4",
|
||||
"description": "Rest api for communication with WhatsApp",
|
||||
"main": "./dist/src/main.js",
|
||||
"scripts": {
|
||||
@@ -46,10 +46,10 @@
|
||||
"@figuro/chatwoot-sdk": "^1.1.16",
|
||||
"@hapi/boom": "^10.0.1",
|
||||
"@sentry/node": "^7.59.2",
|
||||
"@whiskeysockets/baileys": "github:AtendAI/Baileys",
|
||||
"amqplib": "^0.10.3",
|
||||
"aws-sdk": "^2.1499.0",
|
||||
"axios": "^1.6.5",
|
||||
"baileys": "^6.7.0",
|
||||
"class-validator": "^0.14.1",
|
||||
"compression": "^1.7.4",
|
||||
"cors": "^2.8.5",
|
||||
|
||||
@@ -1,13 +1,19 @@
|
||||
export interface ICache {
|
||||
get(key: string): Promise<any>;
|
||||
|
||||
hGet(key: string, field: string): Promise<any>;
|
||||
|
||||
set(key: string, value: any, ttl?: number): void;
|
||||
|
||||
hSet(key: string, field: string, value: any): Promise<void>;
|
||||
|
||||
has(key: string): Promise<boolean>;
|
||||
|
||||
keys(appendCriteria?: string): Promise<string[]>;
|
||||
|
||||
delete(key: string | string[]): Promise<number>;
|
||||
|
||||
hDelete(key: string, field: string): Promise<any>;
|
||||
|
||||
deleteAll(appendCriteria?: string): Promise<number>;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { delay } from '@whiskeysockets/baileys';
|
||||
import { delay } from 'baileys';
|
||||
import { isURL } from 'class-validator';
|
||||
import EventEmitter2 from 'eventemitter2';
|
||||
import { v4 } from 'uuid';
|
||||
@@ -6,7 +6,6 @@ import { v4 } from 'uuid';
|
||||
import { ConfigService, HttpServer, WaBusiness } from '../../config/env.config';
|
||||
import { Logger } from '../../config/logger.config';
|
||||
import { BadRequestException, InternalServerErrorException } from '../../exceptions';
|
||||
import { RedisCache } from '../../libs/redis.client';
|
||||
import { InstanceDto, SetPresenceDto } from '../dto/instance.dto';
|
||||
import { ChatwootService } from '../integrations/chatwoot/services/chatwoot.service';
|
||||
import { RabbitmqService } from '../integrations/rabbitmq/services/rabbitmq.service';
|
||||
@@ -16,12 +15,12 @@ import { WebsocketService } from '../integrations/websocket/services/websocket.s
|
||||
import { RepositoryBroker } from '../repository/repository.manager';
|
||||
import { AuthService, OldToken } from '../services/auth.service';
|
||||
import { CacheService } from '../services/cache.service';
|
||||
import { BaileysStartupService } from '../services/channels/whatsapp.baileys.service';
|
||||
import { BusinessStartupService } from '../services/channels/whatsapp.business.service';
|
||||
import { IntegrationService } from '../services/integration.service';
|
||||
import { WAMonitoringService } from '../services/monitor.service';
|
||||
import { SettingsService } from '../services/settings.service';
|
||||
import { WebhookService } from '../services/webhook.service';
|
||||
import { BaileysStartupService } from '../services/whatsapp/whatsapp.baileys.service';
|
||||
import { BusinessStartupService } from '../services/whatsapp/whatsapp.business.service';
|
||||
import { Events, Integration, wa } from '../types/wa.types';
|
||||
import { ProxyController } from './proxy.controller';
|
||||
|
||||
@@ -41,8 +40,9 @@ export class InstanceController {
|
||||
private readonly typebotService: TypebotService,
|
||||
private readonly integrationService: IntegrationService,
|
||||
private readonly proxyService: ProxyController,
|
||||
private readonly cache: RedisCache,
|
||||
private readonly cache: CacheService,
|
||||
private readonly chatwootCache: CacheService,
|
||||
private readonly messagesLostCache: CacheService,
|
||||
) {}
|
||||
|
||||
private readonly logger = new Logger(InstanceController.name);
|
||||
@@ -65,6 +65,7 @@ export class InstanceController {
|
||||
chatwoot_reopen_conversation,
|
||||
chatwoot_conversation_pending,
|
||||
chatwoot_import_contacts,
|
||||
chatwoot_name_inbox,
|
||||
chatwoot_import_messages,
|
||||
chatwoot_days_limit_import_messages,
|
||||
reject_call,
|
||||
@@ -108,6 +109,7 @@ export class InstanceController {
|
||||
this.repository,
|
||||
this.cache,
|
||||
this.chatwootCache,
|
||||
this.messagesLostCache,
|
||||
);
|
||||
} else {
|
||||
instance = new BaileysStartupService(
|
||||
@@ -116,6 +118,7 @@ export class InstanceController {
|
||||
this.repository,
|
||||
this.cache,
|
||||
this.chatwootCache,
|
||||
this.messagesLostCache,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -511,7 +514,7 @@ export class InstanceController {
|
||||
token: chatwoot_token,
|
||||
url: chatwoot_url,
|
||||
sign_msg: chatwoot_sign_msg || false,
|
||||
name_inbox: instance.instanceName.split('-cwId-')[0],
|
||||
name_inbox: chatwoot_name_inbox ?? instance.instanceName.split('-cwId-')[0],
|
||||
number,
|
||||
reopen_conversation: chatwoot_reopen_conversation || false,
|
||||
conversation_pending: chatwoot_conversation_pending || false,
|
||||
@@ -575,7 +578,7 @@ export class InstanceController {
|
||||
import_messages: chatwoot_import_messages ?? true,
|
||||
days_limit_import_messages: chatwoot_days_limit_import_messages || 60,
|
||||
number,
|
||||
name_inbox: instance.instanceName,
|
||||
name_inbox: chatwoot_name_inbox ?? instance.instanceName,
|
||||
webhook_url: `${urlServer}/chatwoot/webhook/${encodeURIComponent(instance.instanceName)}`,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { proto, WAPresence, WAPrivacyOnlineValue, WAPrivacyValue, WAReadReceiptsValue } from '@whiskeysockets/baileys';
|
||||
import { proto, WAPresence, WAPrivacyOnlineValue, WAPrivacyValue, WAReadReceiptsValue } from 'baileys';
|
||||
|
||||
export class OnWhatsAppDto {
|
||||
constructor(
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { WAPresence } from '@whiskeysockets/baileys';
|
||||
import { WAPresence } from 'baileys';
|
||||
|
||||
import { ProxyDto } from './proxy.dto';
|
||||
|
||||
@@ -30,6 +30,7 @@ export class InstanceDto {
|
||||
chatwoot_import_contacts?: boolean;
|
||||
chatwoot_import_messages?: boolean;
|
||||
chatwoot_days_limit_import_messages?: number;
|
||||
chatwoot_name_inbox?: string;
|
||||
websocket_enabled?: boolean;
|
||||
websocket_events?: string[];
|
||||
rabbitmq_enabled?: boolean;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { proto, WAPresence } from '@whiskeysockets/baileys';
|
||||
import { proto, WAPresence } from 'baileys';
|
||||
|
||||
export class Quoted {
|
||||
key: proto.IMessageKey;
|
||||
|
||||
@@ -2,7 +2,7 @@ import { NextFunction, Request, Response } from 'express';
|
||||
import { existsSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
|
||||
import { configService, Database, Redis } from '../../config/env.config';
|
||||
import { CacheConf, configService, Database } from '../../config/env.config';
|
||||
import { INSTANCE_DIR } from '../../config/path.config';
|
||||
import {
|
||||
BadRequestException,
|
||||
@@ -17,12 +17,13 @@ import { cache, waMonitor } from '../server.module';
|
||||
async function getInstance(instanceName: string) {
|
||||
try {
|
||||
const db = configService.get<Database>('DATABASE');
|
||||
const redisConf = configService.get<Redis>('REDIS');
|
||||
const cacheConf = configService.get<CacheConf>('CACHE');
|
||||
|
||||
const exists = !!waMonitor.waInstances[instanceName];
|
||||
|
||||
if (redisConf.ENABLED) {
|
||||
const keyExists = await cache.keyExists();
|
||||
if (cacheConf.REDIS.ENABLED && cacheConf.REDIS.SAVE_INSTANCES) {
|
||||
const keyExists = await cache.has(instanceName);
|
||||
|
||||
return exists || keyExists;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { isURL } from 'class-validator';
|
||||
|
||||
import { CacheEngine } from '../../../../cache/cacheengine';
|
||||
import { ConfigService, HttpServer } from '../../../../config/env.config';
|
||||
import { Logger } from '../../../../config/logger.config';
|
||||
import { BadRequestException } from '../../../../exceptions';
|
||||
@@ -7,7 +8,6 @@ import { InstanceDto } from '../../../dto/instance.dto';
|
||||
import { RepositoryBroker } from '../../../repository/repository.manager';
|
||||
import { waMonitor } from '../../../server.module';
|
||||
import { CacheService } from '../../../services/cache.service';
|
||||
import { CacheEngine } from '../cache/cacheengine';
|
||||
import { ChatwootDto } from '../dto/chatwoot.dto';
|
||||
import { ChatwootService } from '../services/chatwoot.service';
|
||||
|
||||
@@ -55,9 +55,12 @@ export class ChatwootController {
|
||||
data.import_messages = false;
|
||||
data.days_limit_import_messages = 0;
|
||||
data.auto_create = false;
|
||||
data.name_inbox = '';
|
||||
}
|
||||
|
||||
data.name_inbox = instance.instanceName;
|
||||
if (!data.name_inbox || data.name_inbox === '') {
|
||||
data.name_inbox = instance.instanceName;
|
||||
}
|
||||
|
||||
const result = await this.chatwootService.create(instance, data);
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ import ChatwootClient, {
|
||||
} from '@figuro/chatwoot-sdk';
|
||||
import { request as chatwootRequest } from '@figuro/chatwoot-sdk/dist/core/request';
|
||||
import axios from 'axios';
|
||||
import { proto } from 'baileys';
|
||||
import FormData from 'form-data';
|
||||
import { createReadStream, unlinkSync, writeFileSync } from 'fs';
|
||||
import Jimp from 'jimp';
|
||||
@@ -85,12 +86,13 @@ export class ChatwootService {
|
||||
return client;
|
||||
}
|
||||
|
||||
public getClientCwConfig(): ChatwootAPIConfig {
|
||||
public getClientCwConfig(): ChatwootAPIConfig & { name_inbox: string } {
|
||||
return {
|
||||
basePath: this.provider.url,
|
||||
with_credentials: true,
|
||||
credentials: 'include',
|
||||
token: this.provider.token,
|
||||
name_inbox: this.provider.name_inbox,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -110,7 +112,7 @@ export class ChatwootService {
|
||||
|
||||
await this.initInstanceChatwoot(
|
||||
instance,
|
||||
instance.instanceName.split('-cwId-')[0],
|
||||
data.name_inbox ?? instance.instanceName.split('-cwId-')[0],
|
||||
`${urlServer}/chatwoot/webhook/${encodeURIComponent(instance.instanceName)}`,
|
||||
true,
|
||||
data.number,
|
||||
@@ -461,7 +463,7 @@ export class ChatwootService {
|
||||
const queryOperator = fieldsToSearch.length - 1 === index1 && numbers.length - 1 === index2 ? null : 'OR';
|
||||
filterPayload.push({
|
||||
attribute_key: field,
|
||||
filter_operator: field == 'phone_number' ? 'equal_to' : 'contains',
|
||||
filter_operator: ['phone_number', 'identifier'].includes(field) ? 'equal_to' : 'contains',
|
||||
values: [number.replace('+', '')],
|
||||
query_operator: queryOperator,
|
||||
});
|
||||
@@ -628,7 +630,7 @@ export class ChatwootService {
|
||||
id: contactId,
|
||||
})) as any;
|
||||
|
||||
if (contactConversations) {
|
||||
if (contactConversations?.payload?.length) {
|
||||
let conversation: any;
|
||||
if (this.provider.reopen_conversation) {
|
||||
conversation = contactConversations.payload.find((conversation) => conversation.inbox_id == filterInbox.id);
|
||||
@@ -710,7 +712,7 @@ export class ChatwootService {
|
||||
}
|
||||
|
||||
this.logger.verbose('find inbox by name');
|
||||
const findByName = inbox.payload.find((inbox) => inbox.name === instance.instanceName.split('-cwId-')[0]);
|
||||
const findByName = inbox.payload.find((inbox) => inbox.name === this.getClientCwConfig().name_inbox);
|
||||
|
||||
if (!findByName) {
|
||||
this.logger.warn('inbox not found');
|
||||
@@ -1106,6 +1108,26 @@ export class ChatwootService {
|
||||
}
|
||||
}
|
||||
|
||||
public async onSendMessageError(instance: InstanceDto, conversation: number, error?: string) {
|
||||
const client = await this.clientCw(instance);
|
||||
|
||||
if (!client) {
|
||||
return;
|
||||
}
|
||||
|
||||
client.messages.create({
|
||||
accountId: this.provider.account_id,
|
||||
conversationId: conversation,
|
||||
data: {
|
||||
content: i18next.t('cw.message.notsent', {
|
||||
error: error?.length > 0 ? `_${error}_` : '',
|
||||
}),
|
||||
message_type: 'outgoing',
|
||||
private: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
public async receiveWebhook(instance: InstanceDto, body: any) {
|
||||
try {
|
||||
await new Promise((resolve) => setTimeout(resolve, 500));
|
||||
@@ -1274,6 +1296,11 @@ export class ChatwootService {
|
||||
return { message: 'bot' };
|
||||
}
|
||||
|
||||
if (!waInstance && body.conversation?.id) {
|
||||
this.onSendMessageError(instance, body.conversation?.id, 'Instance not found');
|
||||
return { message: 'bot' };
|
||||
}
|
||||
|
||||
this.logger.verbose('Format message to send');
|
||||
let formatText: string;
|
||||
if (senderName === null || senderName === undefined) {
|
||||
@@ -1310,6 +1337,9 @@ export class ChatwootService {
|
||||
formatText,
|
||||
options,
|
||||
);
|
||||
if (!messageSent && body.conversation?.id) {
|
||||
this.onSendMessageError(instance, body.conversation?.id);
|
||||
}
|
||||
|
||||
this.updateChatwootMessageId(
|
||||
{
|
||||
@@ -1343,23 +1373,34 @@ export class ChatwootService {
|
||||
},
|
||||
};
|
||||
|
||||
const messageSent = await waInstance?.textMessage(data, true);
|
||||
let messageSent: MessageRaw | proto.WebMessageInfo;
|
||||
try {
|
||||
messageSent = await waInstance?.textMessage(data, true);
|
||||
if (!messageSent) {
|
||||
throw new Error('Message not sent');
|
||||
}
|
||||
|
||||
this.updateChatwootMessageId(
|
||||
{
|
||||
...messageSent,
|
||||
owner: instance.instanceName,
|
||||
},
|
||||
{
|
||||
messageId: body.id,
|
||||
inboxId: body.inbox?.id,
|
||||
conversationId: body.conversation?.id,
|
||||
contactInbox: {
|
||||
sourceId: body.conversation?.contact_inbox?.source_id,
|
||||
this.updateChatwootMessageId(
|
||||
{
|
||||
...messageSent,
|
||||
owner: instance.instanceName,
|
||||
},
|
||||
},
|
||||
instance,
|
||||
);
|
||||
{
|
||||
messageId: body.id,
|
||||
inboxId: body.inbox?.id,
|
||||
conversationId: body.conversation?.id,
|
||||
contactInbox: {
|
||||
sourceId: body.conversation?.contact_inbox?.source_id,
|
||||
},
|
||||
},
|
||||
instance,
|
||||
);
|
||||
} catch (error) {
|
||||
if (!messageSent && body.conversation?.id) {
|
||||
this.onSendMessageError(instance, body.conversation?.id, error.toString());
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { inbox } from '@figuro/chatwoot-sdk';
|
||||
import { proto } from '@whiskeysockets/baileys';
|
||||
import { proto } from 'baileys';
|
||||
|
||||
import { InstanceDto } from '../../../../api/dto/instance.dto';
|
||||
import { ChatwootRaw, ContactRaw, MessageRaw } from '../../../../api/models';
|
||||
|
||||
@@ -30,6 +30,7 @@ export const chatwootSchema: JSONSchema7 = {
|
||||
url: { type: 'string' },
|
||||
sign_msg: { type: 'boolean', enum: [true, false] },
|
||||
sign_delimiter: { type: ['string', 'null'] },
|
||||
name_inbox: { type: ['string', 'null'] },
|
||||
reopen_conversation: { type: 'boolean', enum: [true, false] },
|
||||
conversation_pending: { type: 'boolean', enum: [true, false] },
|
||||
auto_create: { type: 'boolean', enum: [true, false] },
|
||||
|
||||
@@ -57,7 +57,7 @@ export class TypebotService {
|
||||
|
||||
if (session) {
|
||||
if (status === 'closed') {
|
||||
const found_session: Session[] = findData.sessions.splice(findData.sessions.indexOf(session), 1);
|
||||
findData.sessions.splice(findData.sessions.indexOf(session), 1);
|
||||
|
||||
const typebotData = {
|
||||
enabled: findData.enabled,
|
||||
@@ -68,7 +68,7 @@ export class TypebotService {
|
||||
delay_message: findData.delay_message,
|
||||
unknown_message: findData.unknown_message,
|
||||
listening_from_me: findData.listening_from_me,
|
||||
sessions: found_session,
|
||||
sessions: findData.sessions,
|
||||
};
|
||||
|
||||
this.create(instance, typebotData);
|
||||
@@ -106,7 +106,7 @@ export class TypebotService {
|
||||
delay_message: findData.delay_message,
|
||||
unknown_message: findData.unknown_message,
|
||||
listening_from_me: findData.listening_from_me,
|
||||
sessions: findData.sessions.splice(findData.sessions.indexOf(session), 1),
|
||||
sessions: findData.sessions,
|
||||
};
|
||||
|
||||
this.create(instance, typebotData);
|
||||
|
||||
@@ -32,6 +32,7 @@ export class MessageRaw {
|
||||
source_reply_id?: string;
|
||||
chatwoot?: ChatwootMessage;
|
||||
contextInfo?: any;
|
||||
status?: wa.StatusMessage | any;
|
||||
}
|
||||
|
||||
type MessageRawBoolean<T> = {
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { CacheEngine } from '../cache/cacheengine';
|
||||
import { configService } from '../config/env.config';
|
||||
import { eventEmitter } from '../config/event.config';
|
||||
import { Logger } from '../config/logger.config';
|
||||
import { dbserver } from '../libs/db.connect';
|
||||
import { RedisCache } from '../libs/redis.client';
|
||||
import { ChatController } from './controllers/chat.controller';
|
||||
import { GroupController } from './controllers/group.controller';
|
||||
import { InstanceController } from './controllers/instance.controller';
|
||||
@@ -14,7 +14,6 @@ import { WebhookController } from './controllers/webhook.controller';
|
||||
import { ChamaaiController } from './integrations/chamaai/controllers/chamaai.controller';
|
||||
import { ChamaaiRepository } from './integrations/chamaai/repository/chamaai.repository';
|
||||
import { ChamaaiService } from './integrations/chamaai/services/chamaai.service';
|
||||
import { CacheEngine } from './integrations/chatwoot/cache/cacheengine';
|
||||
import { ChatwootController } from './integrations/chatwoot/controllers/chatwoot.controller';
|
||||
import { ChatwootRepository } from './integrations/chatwoot/repository/chatwoot.repository';
|
||||
import { ChatwootService } from './integrations/chatwoot/services/chatwoot.service';
|
||||
@@ -107,10 +106,18 @@ export const repository = new RepositoryBroker(
|
||||
dbserver?.getClient(),
|
||||
);
|
||||
|
||||
export const cache = new RedisCache();
|
||||
export const cache = new CacheService(new CacheEngine(configService, 'instance').getEngine());
|
||||
const chatwootCache = new CacheService(new CacheEngine(configService, ChatwootService.name).getEngine());
|
||||
const messagesLostCache = new CacheService(new CacheEngine(configService, 'baileys').getEngine());
|
||||
|
||||
export const waMonitor = new WAMonitoringService(eventEmitter, configService, repository, cache, chatwootCache);
|
||||
export const waMonitor = new WAMonitoringService(
|
||||
eventEmitter,
|
||||
configService,
|
||||
repository,
|
||||
cache,
|
||||
chatwootCache,
|
||||
messagesLostCache,
|
||||
);
|
||||
|
||||
const authService = new AuthService(configService, waMonitor, repository);
|
||||
|
||||
@@ -160,6 +167,7 @@ export const instanceController = new InstanceController(
|
||||
proxyController,
|
||||
cache,
|
||||
chatwootCache,
|
||||
messagesLostCache,
|
||||
);
|
||||
export const sendMessageController = new SendMessageController(waMonitor);
|
||||
export const chatController = new ChatController(waMonitor);
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { BufferJSON } from 'baileys';
|
||||
|
||||
import { Logger } from '../../config/logger.config';
|
||||
import { ICache } from '../abstract/abstract.cache';
|
||||
|
||||
@@ -20,6 +22,21 @@ export class CacheService {
|
||||
return this.cache.get(key);
|
||||
}
|
||||
|
||||
public async hGet(key: string, field: string) {
|
||||
try {
|
||||
const data = await this.cache.hGet(key, field);
|
||||
|
||||
if (data) {
|
||||
return JSON.parse(data, BufferJSON.reviver);
|
||||
}
|
||||
|
||||
return null;
|
||||
} catch (error) {
|
||||
this.logger.error(error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async set(key: string, value: any) {
|
||||
if (!this.cache) {
|
||||
return;
|
||||
@@ -28,6 +45,16 @@ export class CacheService {
|
||||
this.cache.set(key, value);
|
||||
}
|
||||
|
||||
public async hSet(key: string, field: string, value: any) {
|
||||
try {
|
||||
const json = JSON.stringify(value, BufferJSON.replacer);
|
||||
|
||||
await this.cache.hSet(key, field, json);
|
||||
} catch (error) {
|
||||
this.logger.error(error);
|
||||
}
|
||||
}
|
||||
|
||||
async has(key: string) {
|
||||
if (!this.cache) {
|
||||
return;
|
||||
@@ -44,6 +71,16 @@ export class CacheService {
|
||||
return this.cache.delete(key);
|
||||
}
|
||||
|
||||
async hDelete(key: string, field: string) {
|
||||
try {
|
||||
await this.cache.hDelete(key, field);
|
||||
return true;
|
||||
} catch (error) {
|
||||
this.logger.error(error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async deleteAll(appendCriteria?: string) {
|
||||
if (!this.cache) {
|
||||
return;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { WASocket } from '@whiskeysockets/baileys';
|
||||
import axios from 'axios';
|
||||
import { WASocket } from 'baileys';
|
||||
import { execSync } from 'child_process';
|
||||
import { isURL } from 'class-validator';
|
||||
import EventEmitter2 from 'eventemitter2';
|
||||
@@ -38,17 +38,17 @@ import { waMonitor } from '../server.module';
|
||||
import { Events, wa } from '../types/wa.types';
|
||||
import { CacheService } from './cache.service';
|
||||
|
||||
export class WAStartupService {
|
||||
export class ChannelStartupService {
|
||||
constructor(
|
||||
public readonly configService: ConfigService,
|
||||
public readonly eventEmitter: EventEmitter2,
|
||||
public readonly repository: RepositoryBroker,
|
||||
public readonly chatwootCache: CacheService,
|
||||
) {
|
||||
this.logger.verbose('WAStartupService initialized');
|
||||
this.logger.verbose('ChannelStartupService initialized');
|
||||
}
|
||||
|
||||
public readonly logger = new Logger(WAStartupService.name);
|
||||
public readonly logger = new Logger(ChannelStartupService.name);
|
||||
|
||||
public client: WASocket;
|
||||
public readonly instance: wa.Instance = {};
|
||||
@@ -71,6 +71,8 @@ export class WAStartupService {
|
||||
public chamaaiService = new ChamaaiService(waMonitor, this.configService);
|
||||
|
||||
public set instanceName(name: string) {
|
||||
this.logger.setInstance(name);
|
||||
|
||||
this.logger.verbose(`Initializing instance '${name}'`);
|
||||
if (!name) {
|
||||
this.logger.verbose('Instance name not found, generating random name with uuid');
|
||||
@@ -134,11 +136,13 @@ export class WAStartupService {
|
||||
|
||||
public async findIntegration() {
|
||||
this.logger.verbose('Finding integration');
|
||||
const data = await this.repository.integration.find(this.instanceName);
|
||||
let data: any;
|
||||
|
||||
data = await this.repository.integration.find(this.instanceName);
|
||||
|
||||
if (!data) {
|
||||
this.logger.verbose('Integration not found');
|
||||
throw new NotFoundException('Integration not found');
|
||||
this.repository.integration.create({ integration: 'WHATSAPP-BAILEYS', number: '', token: '' }, this.instanceName);
|
||||
data = { integration: 'WHATSAPP-BAILEYS', number: '', token: '' };
|
||||
}
|
||||
|
||||
this.logger.verbose(`Integration: ${data.integration}`);
|
||||
@@ -583,7 +587,7 @@ export class WAStartupService {
|
||||
this.logger.verbose(`Proxy enabled: ${this.localProxy.enabled}`);
|
||||
|
||||
this.localProxy.proxy = data?.proxy;
|
||||
this.logger.verbose(`Proxy proxy: ${this.localProxy.proxy.host}`);
|
||||
this.logger.verbose(`Proxy proxy: ${this.localProxy.proxy?.host}`);
|
||||
|
||||
this.logger.verbose('Proxy loaded');
|
||||
}
|
||||
@@ -738,7 +742,7 @@ export class WAStartupService {
|
||||
|
||||
if (this.configService.get<Log>('LOG').LEVEL.includes('WEBHOOKS')) {
|
||||
const logData = {
|
||||
local: WAStartupService.name + '.sendData-RabbitMQ',
|
||||
local: ChannelStartupService.name + '.sendData-RabbitMQ',
|
||||
event,
|
||||
instance: this.instance.name,
|
||||
data,
|
||||
@@ -794,7 +798,7 @@ export class WAStartupService {
|
||||
sqs.sendMessage(params, (err, data) => {
|
||||
if (err) {
|
||||
this.logger.error({
|
||||
local: WAStartupService.name + '.sendData-SQS',
|
||||
local: ChannelStartupService.name + '.sendData-SQS',
|
||||
message: err?.message,
|
||||
hostName: err?.hostname,
|
||||
code: err?.code,
|
||||
@@ -806,7 +810,7 @@ export class WAStartupService {
|
||||
} else {
|
||||
if (this.configService.get<Log>('LOG').LEVEL.includes('WEBHOOKS')) {
|
||||
const logData = {
|
||||
local: WAStartupService.name + '.sendData-SQS',
|
||||
local: ChannelStartupService.name + '.sendData-SQS',
|
||||
event,
|
||||
instance: this.instance.name,
|
||||
data,
|
||||
@@ -850,7 +854,7 @@ export class WAStartupService {
|
||||
|
||||
if (this.configService.get<Log>('LOG').LEVEL.includes('WEBHOOKS')) {
|
||||
const logData = {
|
||||
local: WAStartupService.name + '.sendData-WebsocketGlobal',
|
||||
local: ChannelStartupService.name + '.sendData-WebsocketGlobal',
|
||||
event,
|
||||
instance: this.instance.name,
|
||||
data,
|
||||
@@ -880,7 +884,7 @@ export class WAStartupService {
|
||||
|
||||
if (this.configService.get<Log>('LOG').LEVEL.includes('WEBHOOKS')) {
|
||||
const logData = {
|
||||
local: WAStartupService.name + '.sendData-Websocket',
|
||||
local: ChannelStartupService.name + '.sendData-Websocket',
|
||||
event,
|
||||
instance: this.instance.name,
|
||||
data,
|
||||
@@ -914,7 +918,7 @@ export class WAStartupService {
|
||||
|
||||
if (this.configService.get<Log>('LOG').LEVEL.includes('WEBHOOKS')) {
|
||||
const logData = {
|
||||
local: WAStartupService.name + '.sendDataWebhook-local',
|
||||
local: ChannelStartupService.name + '.sendDataWebhook-local',
|
||||
url: baseURL,
|
||||
event,
|
||||
instance: this.instance.name,
|
||||
@@ -954,7 +958,7 @@ export class WAStartupService {
|
||||
}
|
||||
} catch (error) {
|
||||
this.logger.error({
|
||||
local: WAStartupService.name + '.sendDataWebhook-local',
|
||||
local: ChannelStartupService.name + '.sendDataWebhook-local',
|
||||
message: error?.message,
|
||||
hostName: error?.hostname,
|
||||
syscall: error?.syscall,
|
||||
@@ -986,7 +990,7 @@ export class WAStartupService {
|
||||
|
||||
if (this.configService.get<Log>('LOG').LEVEL.includes('WEBHOOKS')) {
|
||||
const logData = {
|
||||
local: WAStartupService.name + '.sendDataWebhook-global',
|
||||
local: ChannelStartupService.name + '.sendDataWebhook-global',
|
||||
url: globalURL,
|
||||
event,
|
||||
instance: this.instance.name,
|
||||
@@ -1025,7 +1029,7 @@ export class WAStartupService {
|
||||
}
|
||||
} catch (error) {
|
||||
this.logger.error({
|
||||
local: WAStartupService.name + '.sendDataWebhook-global',
|
||||
local: ChannelStartupService.name + '.sendDataWebhook-global',
|
||||
message: error?.message,
|
||||
hostName: error?.hostname,
|
||||
syscall: error?.syscall,
|
||||
@@ -1,5 +1,6 @@
|
||||
import ffmpegPath from '@ffmpeg-installer/ffmpeg';
|
||||
import { Boom } from '@hapi/boom';
|
||||
import axios from 'axios';
|
||||
import makeWASocket, {
|
||||
AnyMessageContent,
|
||||
BufferedEventData,
|
||||
@@ -35,13 +36,13 @@ import makeWASocket, {
|
||||
WAMessageUpdate,
|
||||
WAPresence,
|
||||
WASocket,
|
||||
} from '@whiskeysockets/baileys';
|
||||
import { Label } from '@whiskeysockets/baileys/lib/Types/Label';
|
||||
import { LabelAssociation } from '@whiskeysockets/baileys/lib/Types/LabelAssociation';
|
||||
import axios from 'axios';
|
||||
import { arrayUnique, isBase64, isURL } from 'class-validator';
|
||||
} from 'baileys';
|
||||
import { Label } from 'baileys/lib/Types/Label';
|
||||
import { LabelAssociation } from 'baileys/lib/Types/LabelAssociation';
|
||||
import { exec } from 'child_process';
|
||||
import { isBase64, isURL } from 'class-validator';
|
||||
import EventEmitter2 from 'eventemitter2';
|
||||
import ffmpeg from 'fluent-ffmpeg';
|
||||
// import ffmpeg from 'fluent-ffmpeg';
|
||||
import fs, { existsSync, readFileSync } from 'fs';
|
||||
import { parsePhoneNumber } from 'libphonenumber-js';
|
||||
import Long from 'long';
|
||||
@@ -54,11 +55,10 @@ import qrcode, { QRCodeToDataURLOptions } from 'qrcode';
|
||||
import qrcodeTerminal from 'qrcode-terminal';
|
||||
import sharp from 'sharp';
|
||||
|
||||
import { ConfigService, ConfigSessionPhone, Database, Log, QrCode, Redis } from '../../../config/env.config';
|
||||
import { CacheConf, ConfigService, ConfigSessionPhone, Database, Log, QrCode } from '../../../config/env.config';
|
||||
import { INSTANCE_DIR } from '../../../config/path.config';
|
||||
import { BadRequestException, InternalServerErrorException, NotFoundException } from '../../../exceptions';
|
||||
import { dbserver } from '../../../libs/db.connect';
|
||||
import { RedisCache } from '../../../libs/redis.client';
|
||||
import { makeProxyAgent } from '../../../utils/makeProxyAgent';
|
||||
import { useMultiFileAuthStateDb } from '../../../utils/use-multi-file-auth-state-db';
|
||||
import { useMultiFileAuthStateRedisDb } from '../../../utils/use-multi-file-auth-state-redis-db';
|
||||
@@ -97,7 +97,6 @@ import {
|
||||
MediaMessage,
|
||||
Options,
|
||||
SendAudioDto,
|
||||
SendButtonDto,
|
||||
SendContactDto,
|
||||
SendListDto,
|
||||
SendLocationDto,
|
||||
@@ -118,23 +117,23 @@ import { RepositoryBroker } from '../../repository/repository.manager';
|
||||
import { waMonitor } from '../../server.module';
|
||||
import { Events, MessageSubtype, TypeMediaMessage, wa } from '../../types/wa.types';
|
||||
import { CacheService } from './../cache.service';
|
||||
import { WAStartupService } from './../whatsapp.service';
|
||||
import { ChannelStartupService } from './../channel.service';
|
||||
|
||||
// const retryCache = {};
|
||||
|
||||
export class BaileysStartupService extends WAStartupService {
|
||||
export class BaileysStartupService extends ChannelStartupService {
|
||||
constructor(
|
||||
public readonly configService: ConfigService,
|
||||
public readonly eventEmitter: EventEmitter2,
|
||||
public readonly repository: RepositoryBroker,
|
||||
public readonly cache: RedisCache,
|
||||
public readonly cache: CacheService,
|
||||
public readonly chatwootCache: CacheService,
|
||||
public readonly messagesLostCache: CacheService,
|
||||
) {
|
||||
super(configService, eventEmitter, repository, chatwootCache);
|
||||
this.logger.verbose('BaileysStartupService initialized');
|
||||
this.cleanStore();
|
||||
this.instance.qrcode = { count: 0 };
|
||||
this.mobile = false;
|
||||
this.recoveringMessages();
|
||||
}
|
||||
|
||||
private readonly msgRetryCounterCache: CacheStore = new NodeCache();
|
||||
@@ -147,6 +146,26 @@ export class BaileysStartupService extends WAStartupService {
|
||||
public phoneNumber: string;
|
||||
public mobile: boolean;
|
||||
|
||||
private async recoveringMessages() {
|
||||
this.logger.info('Recovering messages lost');
|
||||
const cacheConf = this.configService.get<CacheConf>('CACHE');
|
||||
|
||||
if ((cacheConf?.REDIS?.ENABLED && cacheConf?.REDIS?.URI !== '') || cacheConf?.LOCAL?.ENABLED) {
|
||||
setInterval(async () => {
|
||||
this.messagesLostCache.keys().then((keys) => {
|
||||
keys.forEach(async (key) => {
|
||||
const message = await this.messagesLostCache.get(key.split(':')[2]);
|
||||
|
||||
if (message.messageStubParameters && message.messageStubParameters[0] === 'Message absent from node') {
|
||||
this.logger.info('Message absent from node, retrying to send, key: ' + key.split(':')[2]);
|
||||
await this.client.sendMessageAck(JSON.parse(message.messageStubParameters[1], BufferJSON.reviver));
|
||||
}
|
||||
});
|
||||
});
|
||||
}, 30000);
|
||||
}
|
||||
}
|
||||
|
||||
public get connectionStatus() {
|
||||
this.logger.verbose('Getting connection status');
|
||||
return this.stateConnection;
|
||||
@@ -377,10 +396,12 @@ export class BaileysStartupService extends WAStartupService {
|
||||
│ CONNECTED TO WHATSAPP │
|
||||
└──────────────────────────────┘`.replace(/^ +/gm, ' '),
|
||||
);
|
||||
this.logger.info(`
|
||||
this.logger.info(
|
||||
`
|
||||
wuid: ${formattedWuid}
|
||||
name: ${formattedName}
|
||||
`);
|
||||
`,
|
||||
);
|
||||
|
||||
if (this.localChatwoot.enabled) {
|
||||
this.chatwootService.eventWhatsapp(
|
||||
@@ -437,12 +458,11 @@ export class BaileysStartupService extends WAStartupService {
|
||||
private async defineAuthState() {
|
||||
this.logger.verbose('Defining auth state');
|
||||
const db = this.configService.get<Database>('DATABASE');
|
||||
const redis = this.configService.get<Redis>('REDIS');
|
||||
const cache = this.configService.get<CacheConf>('CACHE');
|
||||
|
||||
if (redis?.ENABLED) {
|
||||
this.logger.verbose('Redis enabled');
|
||||
this.cache.reference = this.instance.name;
|
||||
return await useMultiFileAuthStateRedisDb(this.cache);
|
||||
if (cache?.REDIS.ENABLED && cache?.REDIS.SAVE_INSTANCES) {
|
||||
this.logger.info('Redis enabled');
|
||||
return await useMultiFileAuthStateRedisDb(this.instance.name, this.cache);
|
||||
}
|
||||
|
||||
if (db.SAVE_DATA.INSTANCE && db.ENABLED) {
|
||||
@@ -485,17 +505,18 @@ export class BaileysStartupService extends WAStartupService {
|
||||
let options;
|
||||
|
||||
if (this.localProxy.enabled) {
|
||||
this.logger.info('Proxy enabled: ' + this.localProxy.proxy.host);
|
||||
this.logger.info('Proxy enabled: ' + this.localProxy.proxy?.host);
|
||||
|
||||
if (this.localProxy?.proxy?.host?.includes('proxyscrape')) {
|
||||
try {
|
||||
const response = await axios.get(this.localProxy.proxy.host);
|
||||
const response = await axios.get(this.localProxy.proxy?.host);
|
||||
const text = response.data;
|
||||
const proxyUrls = text.split('\r\n');
|
||||
const rand = Math.floor(Math.random() * Math.floor(proxyUrls.length));
|
||||
const proxyUrl = 'http://' + proxyUrls[rand];
|
||||
options = {
|
||||
agent: makeProxyAgent(proxyUrl),
|
||||
fetchAgent: makeProxyAgent(proxyUrl),
|
||||
};
|
||||
} catch (error) {
|
||||
this.localProxy.enabled = false;
|
||||
@@ -503,6 +524,7 @@ export class BaileysStartupService extends WAStartupService {
|
||||
} else {
|
||||
options = {
|
||||
agent: makeProxyAgent(this.localProxy.proxy),
|
||||
fetchAgent: makeProxyAgent(this.localProxy.proxy),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -655,17 +677,18 @@ export class BaileysStartupService extends WAStartupService {
|
||||
let options;
|
||||
|
||||
if (this.localProxy.enabled) {
|
||||
this.logger.info('Proxy enabled: ' + this.localProxy.proxy.host);
|
||||
this.logger.info('Proxy enabled: ' + this.localProxy.proxy?.host);
|
||||
|
||||
if (this.localProxy?.proxy?.host?.includes('proxyscrape')) {
|
||||
try {
|
||||
const response = await axios.get(this.localProxy.proxy.host);
|
||||
const response = await axios.get(this.localProxy.proxy?.host);
|
||||
const text = response.data;
|
||||
const proxyUrls = text.split('\r\n');
|
||||
const rand = Math.floor(Math.random() * Math.floor(proxyUrls.length));
|
||||
const proxyUrl = 'http://' + proxyUrls[rand];
|
||||
options = {
|
||||
agent: makeProxyAgent(proxyUrl),
|
||||
fetchAgent: makeProxyAgent(proxyUrl),
|
||||
};
|
||||
} catch (error) {
|
||||
this.localProxy.enabled = false;
|
||||
@@ -673,6 +696,7 @@ export class BaileysStartupService extends WAStartupService {
|
||||
} else {
|
||||
options = {
|
||||
agent: makeProxyAgent(this.localProxy.proxy),
|
||||
fetchAgent: makeProxyAgent(this.localProxy.proxy),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -976,6 +1000,15 @@ export class BaileysStartupService extends WAStartupService {
|
||||
continue;
|
||||
}
|
||||
|
||||
const status: Record<number, wa.StatusMessage> = {
|
||||
0: 'ERROR',
|
||||
1: 'PENDING',
|
||||
2: 'SERVER_ACK',
|
||||
3: 'DELIVERY_ACK',
|
||||
4: 'READ',
|
||||
5: 'PLAYED',
|
||||
};
|
||||
|
||||
messagesRaw.push({
|
||||
key: m.key,
|
||||
pushName: m.pushName || m.key.remoteJid.split('@')[0],
|
||||
@@ -984,6 +1017,7 @@ export class BaileysStartupService extends WAStartupService {
|
||||
messageType: getContentType(m.message),
|
||||
messageTimestamp: m.messageTimestamp as number,
|
||||
owner: this.instance.name,
|
||||
status: m.status ? status[m.status] : null,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1043,6 +1077,20 @@ export class BaileysStartupService extends WAStartupService {
|
||||
}
|
||||
}
|
||||
|
||||
if (received.messageStubParameters && received.messageStubParameters[0] === 'Message absent from node') {
|
||||
this.logger.info('Recovering message lost');
|
||||
|
||||
await this.messagesLostCache.set(received.key.id, received);
|
||||
continue;
|
||||
}
|
||||
|
||||
const retryCache = (await this.messagesLostCache.get(received.key.id)) || null;
|
||||
|
||||
if (retryCache) {
|
||||
this.logger.info('Recovered message lost');
|
||||
await this.messagesLostCache.delete(received.key.id);
|
||||
}
|
||||
|
||||
if (
|
||||
(type !== 'notify' && type !== 'append') ||
|
||||
received.message?.protocolMessage ||
|
||||
@@ -1241,7 +1289,6 @@ export class BaileysStartupService extends WAStartupService {
|
||||
}
|
||||
}
|
||||
|
||||
// if (key.remoteJid !== 'status@broadcast' && !key?.remoteJid?.match(/(:\d+)/)) {
|
||||
if (key.remoteJid !== 'status@broadcast') {
|
||||
this.logger.verbose('Message update is valid');
|
||||
|
||||
@@ -1472,27 +1519,12 @@ export class BaileysStartupService extends WAStartupService {
|
||||
if (events['messages.upsert']) {
|
||||
this.logger.verbose('Listening event: messages.upsert');
|
||||
const payload = events['messages.upsert'];
|
||||
// if (payload.messages.find((a) => a?.messageStubType === 2)) {
|
||||
// const msg = payload.messages[0];
|
||||
// retryCache[msg.key.id] = msg;
|
||||
// return;
|
||||
// }
|
||||
this.messageHandle['messages.upsert'](payload, database, settings);
|
||||
}
|
||||
|
||||
if (events['messages.update']) {
|
||||
this.logger.verbose('Listening event: messages.update');
|
||||
const payload = events['messages.update'];
|
||||
// payload.forEach((message) => {
|
||||
// if (retryCache[message.key.id]) {
|
||||
// this.client.ev.emit('messages.upsert', {
|
||||
// messages: [message],
|
||||
// type: 'notify',
|
||||
// });
|
||||
// delete retryCache[message.key.id];
|
||||
// return;
|
||||
// }
|
||||
// });
|
||||
this.messageHandle['messages.update'](payload, database, settings);
|
||||
}
|
||||
|
||||
@@ -2174,15 +2206,6 @@ export class BaileysStartupService extends WAStartupService {
|
||||
|
||||
mimetype = response.headers['content-type'];
|
||||
}
|
||||
// if (isURL(mediaMessage.media)) {
|
||||
// const response = await axios.get(mediaMessage.media, { responseType: 'arraybuffer' });
|
||||
|
||||
// mimetype = response.headers['content-type'];
|
||||
// console.log('mediaMessage.mimetype2', mimetype);
|
||||
// } else {
|
||||
// mimetype = getMIMEType(mediaMessage.fileName);
|
||||
// console.log('mediaMessage.mimetype3', mimetype);
|
||||
// }
|
||||
}
|
||||
|
||||
this.logger.verbose('Mimetype: ' + mimetype);
|
||||
@@ -2309,7 +2332,7 @@ export class BaileysStartupService extends WAStartupService {
|
||||
if (isURL(audio)) {
|
||||
this.logger.verbose('Audio is url');
|
||||
|
||||
outputAudio = `${join(this.storePath, 'temp', `${hash}.ogg`)}`;
|
||||
outputAudio = `${join(this.storePath, 'temp', `${hash}.mp4`)}`;
|
||||
tempAudioPath = `${join(this.storePath, 'temp', `temp-${hash}.mp3`)}`;
|
||||
|
||||
this.logger.verbose('Output audio path: ' + outputAudio);
|
||||
@@ -2320,25 +2343,14 @@ export class BaileysStartupService extends WAStartupService {
|
||||
|
||||
this.logger.verbose('Including timestamp in url: ' + url);
|
||||
|
||||
let config: any = {
|
||||
responseType: 'arraybuffer',
|
||||
};
|
||||
|
||||
if (this.localProxy.enabled) {
|
||||
config = {
|
||||
...config,
|
||||
httpsAgent: makeProxyAgent(this.localProxy.proxy),
|
||||
};
|
||||
}
|
||||
|
||||
const response = await axios.get(url, config);
|
||||
const response = await axios.get(url, { responseType: 'arraybuffer' });
|
||||
this.logger.verbose('Getting audio from url');
|
||||
|
||||
fs.writeFileSync(tempAudioPath, response.data);
|
||||
} else {
|
||||
this.logger.verbose('Audio is base64');
|
||||
|
||||
outputAudio = `${join(this.storePath, 'temp', `${hash}.ogg`)}`;
|
||||
outputAudio = `${join(this.storePath, 'temp', `${hash}.mp4`)}`;
|
||||
tempAudioPath = `${join(this.storePath, 'temp', `temp-${hash}.mp3`)}`;
|
||||
|
||||
this.logger.verbose('Output audio path: ' + outputAudio);
|
||||
@@ -2351,25 +2363,15 @@ export class BaileysStartupService extends WAStartupService {
|
||||
|
||||
this.logger.verbose('Converting audio to mp4');
|
||||
return new Promise((resolve, reject) => {
|
||||
// This fix was suggested by @PurpShell
|
||||
ffmpeg.setFfmpegPath(ffmpegPath.path);
|
||||
exec(`${ffmpegPath.path} -i ${tempAudioPath} -vn -ab 128k -ar 44100 -f ipod ${outputAudio} -y`, (error) => {
|
||||
fs.unlinkSync(tempAudioPath);
|
||||
this.logger.verbose('Temp audio deleted');
|
||||
|
||||
ffmpeg()
|
||||
.input(tempAudioPath)
|
||||
.outputFormat('ogg')
|
||||
.noVideo()
|
||||
.audioCodec('libopus')
|
||||
.save(outputAudio)
|
||||
.on('error', function (error) {
|
||||
console.log('error', error);
|
||||
fs.unlinkSync(tempAudioPath);
|
||||
if (error) reject(error);
|
||||
})
|
||||
.on('end', async function () {
|
||||
fs.unlinkSync(tempAudioPath);
|
||||
resolve(outputAudio);
|
||||
})
|
||||
.run();
|
||||
if (error) reject(error);
|
||||
|
||||
this.logger.verbose('Audio converted to mp4');
|
||||
resolve(outputAudio);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -2389,7 +2391,7 @@ export class BaileysStartupService extends WAStartupService {
|
||||
{
|
||||
audio: Buffer.from(audio, 'base64'),
|
||||
ptt: true,
|
||||
mimetype: 'audio/ogg; codecs=opus',
|
||||
mimetype: 'audio/mp4',
|
||||
},
|
||||
{ presence: 'recording', delay: data?.options?.delay },
|
||||
isChatwoot,
|
||||
@@ -2418,50 +2420,8 @@ export class BaileysStartupService extends WAStartupService {
|
||||
);
|
||||
}
|
||||
|
||||
public async buttonMessage(data: SendButtonDto) {
|
||||
this.logger.verbose('Sending button message');
|
||||
const embeddedMedia: any = {};
|
||||
let mediatype = 'TEXT';
|
||||
|
||||
if (data.buttonMessage?.mediaMessage) {
|
||||
mediatype = data.buttonMessage.mediaMessage?.mediatype.toUpperCase() ?? 'TEXT';
|
||||
embeddedMedia.mediaKey = mediatype.toLowerCase() + 'Message';
|
||||
const generate = await this.prepareMediaMessage(data.buttonMessage.mediaMessage);
|
||||
embeddedMedia.message = generate.message[embeddedMedia.mediaKey];
|
||||
embeddedMedia.contentText = `*${data.buttonMessage.title}*\n\n${data.buttonMessage.description}`;
|
||||
}
|
||||
|
||||
const btnItems = {
|
||||
text: data.buttonMessage.buttons.map((btn) => btn.buttonText),
|
||||
ids: data.buttonMessage.buttons.map((btn) => btn.buttonId),
|
||||
};
|
||||
|
||||
if (!arrayUnique(btnItems.text) || !arrayUnique(btnItems.ids)) {
|
||||
throw new BadRequestException('Button texts cannot be repeated', 'Button IDs cannot be repeated.');
|
||||
}
|
||||
|
||||
return await this.sendMessageWithTyping(
|
||||
data.number,
|
||||
{
|
||||
buttonsMessage: {
|
||||
text: !embeddedMedia?.mediaKey ? data.buttonMessage.title : undefined,
|
||||
contentText: embeddedMedia?.contentText ?? data.buttonMessage.description,
|
||||
footerText: data.buttonMessage?.footerText,
|
||||
buttons: data.buttonMessage.buttons.map((button) => {
|
||||
return {
|
||||
buttonText: {
|
||||
displayText: button.buttonText,
|
||||
},
|
||||
buttonId: button.buttonId,
|
||||
type: 1,
|
||||
};
|
||||
}),
|
||||
headerType: proto.Message.ButtonsMessage.HeaderType[mediatype],
|
||||
[embeddedMedia?.mediaKey]: embeddedMedia?.message,
|
||||
},
|
||||
},
|
||||
data?.options,
|
||||
);
|
||||
public async buttonMessage() {
|
||||
throw new BadRequestException('Method not available on WhatsApp Baileys');
|
||||
}
|
||||
|
||||
public async locationMessage(data: SendLocationDto) {
|
||||
@@ -7,7 +7,6 @@ import { getMIMEType } from 'node-mime-types';
|
||||
|
||||
import { ConfigService, Database, WaBusiness } from '../../../config/env.config';
|
||||
import { BadRequestException, InternalServerErrorException } from '../../../exceptions';
|
||||
import { RedisCache } from '../../../libs/redis.client';
|
||||
import { NumberBusiness } from '../../dto/chat.dto';
|
||||
import {
|
||||
ContactMessage,
|
||||
@@ -27,15 +26,16 @@ import { ContactRaw, MessageRaw, MessageUpdateRaw, SettingsRaw } from '../../mod
|
||||
import { RepositoryBroker } from '../../repository/repository.manager';
|
||||
import { Events, wa } from '../../types/wa.types';
|
||||
import { CacheService } from './../cache.service';
|
||||
import { WAStartupService } from './../whatsapp.service';
|
||||
import { ChannelStartupService } from './../channel.service';
|
||||
|
||||
export class BusinessStartupService extends WAStartupService {
|
||||
export class BusinessStartupService extends ChannelStartupService {
|
||||
constructor(
|
||||
public readonly configService: ConfigService,
|
||||
public readonly eventEmitter: EventEmitter2,
|
||||
public readonly repository: RepositoryBroker,
|
||||
public readonly cache: RedisCache,
|
||||
public readonly cache: CacheService,
|
||||
public readonly chatwootCache: CacheService,
|
||||
public readonly messagesLostCache: CacheService,
|
||||
) {
|
||||
super(configService, eventEmitter, repository, chatwootCache);
|
||||
this.logger.verbose('BusinessStartupService initialized');
|
||||
@@ -22,7 +22,8 @@ export class IntegrationService {
|
||||
const result = await this.waMonitor.waInstances[instance.instanceName].findIntegration();
|
||||
|
||||
if (Object.keys(result).length === 0) {
|
||||
throw new Error('Integration not found');
|
||||
this.create(instance, { integration: 'WHATSAPP-BAILEYS', number: '', token: '' });
|
||||
return { integration: 'WHATSAPP-BAILEYS', number: '', token: '' };
|
||||
}
|
||||
|
||||
return result;
|
||||
|
||||
@@ -5,11 +5,10 @@ import { Db } from 'mongodb';
|
||||
import { Collection } from 'mongoose';
|
||||
import { join } from 'path';
|
||||
|
||||
import { Auth, ConfigService, Database, DelInstance, HttpServer, Redis } from '../../config/env.config';
|
||||
import { Auth, CacheConf, ConfigService, Database, DelInstance, HttpServer } from '../../config/env.config';
|
||||
import { Logger } from '../../config/logger.config';
|
||||
import { INSTANCE_DIR, STORE_DIR } from '../../config/path.config';
|
||||
import { NotFoundException } from '../../exceptions';
|
||||
import { RedisCache } from '../../libs/redis.client';
|
||||
import {
|
||||
AuthModel,
|
||||
ChamaaiModel,
|
||||
@@ -26,16 +25,17 @@ import {
|
||||
import { RepositoryBroker } from '../repository/repository.manager';
|
||||
import { Integration } from '../types/wa.types';
|
||||
import { CacheService } from './cache.service';
|
||||
import { BaileysStartupService } from './whatsapp/whatsapp.baileys.service';
|
||||
import { BusinessStartupService } from './whatsapp/whatsapp.business.service';
|
||||
import { BaileysStartupService } from './channels/whatsapp.baileys.service';
|
||||
import { BusinessStartupService } from './channels/whatsapp.business.service';
|
||||
|
||||
export class WAMonitoringService {
|
||||
constructor(
|
||||
private readonly eventEmitter: EventEmitter2,
|
||||
private readonly configService: ConfigService,
|
||||
private readonly repository: RepositoryBroker,
|
||||
private readonly cache: RedisCache,
|
||||
private readonly cache: CacheService,
|
||||
private readonly chatwootCache: CacheService,
|
||||
private readonly messagesLostCache: CacheService,
|
||||
) {
|
||||
this.logger.verbose('instance created');
|
||||
|
||||
@@ -43,7 +43,7 @@ export class WAMonitoringService {
|
||||
this.noConnection();
|
||||
|
||||
Object.assign(this.db, configService.get<Database>('DATABASE'));
|
||||
Object.assign(this.redis, configService.get<Redis>('REDIS'));
|
||||
Object.assign(this.redis, configService.get<CacheConf>('CACHE'));
|
||||
|
||||
this.dbInstance = this.db.ENABLED
|
||||
? this.repository.dbServer?.db(this.db.CONNECTION.DB_PREFIX_NAME + '-instances')
|
||||
@@ -51,7 +51,7 @@ export class WAMonitoringService {
|
||||
}
|
||||
|
||||
private readonly db: Partial<Database> = {};
|
||||
private readonly redis: Partial<Redis> = {};
|
||||
private readonly redis: Partial<CacheConf> = {};
|
||||
|
||||
private dbInstance: Db;
|
||||
|
||||
@@ -212,7 +212,7 @@ export class WAMonitoringService {
|
||||
});
|
||||
this.logger.verbose('instance files deleted: ' + name);
|
||||
});
|
||||
} else if (!this.redis.ENABLED) {
|
||||
} else if (!this.redis.REDIS.ENABLED && !this.redis.REDIS.SAVE_INSTANCES) {
|
||||
const dir = opendirSync(INSTANCE_DIR, { encoding: 'utf-8' });
|
||||
for await (const dirent of dir) {
|
||||
if (dirent.isDirectory()) {
|
||||
@@ -247,10 +247,9 @@ export class WAMonitoringService {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.redis.ENABLED) {
|
||||
if (this.redis.REDIS.ENABLED && this.redis.REDIS.SAVE_INSTANCES) {
|
||||
this.logger.verbose('cleaning up instance in redis: ' + instanceName);
|
||||
this.cache.reference = instanceName;
|
||||
await this.cache.delAll();
|
||||
await this.cache.delete(instanceName);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -303,7 +302,7 @@ export class WAMonitoringService {
|
||||
this.logger.verbose('Loading instances');
|
||||
|
||||
try {
|
||||
if (this.redis.ENABLED) {
|
||||
if (this.redis.REDIS.ENABLED && this.redis.REDIS.SAVE_INSTANCES) {
|
||||
await this.loadInstancesFromRedis();
|
||||
} else if (this.db.ENABLED && this.db.SAVE_DATA.INSTANCE) {
|
||||
await this.loadInstancesFromDatabase();
|
||||
@@ -346,6 +345,7 @@ export class WAMonitoringService {
|
||||
this.repository,
|
||||
this.cache,
|
||||
this.chatwootCache,
|
||||
this.messagesLostCache,
|
||||
);
|
||||
|
||||
instance.instanceName = name;
|
||||
@@ -356,6 +356,7 @@ export class WAMonitoringService {
|
||||
this.repository,
|
||||
this.cache,
|
||||
this.chatwootCache,
|
||||
this.messagesLostCache,
|
||||
);
|
||||
|
||||
instance.instanceName = name;
|
||||
@@ -374,12 +375,11 @@ export class WAMonitoringService {
|
||||
|
||||
private async loadInstancesFromRedis() {
|
||||
this.logger.verbose('Redis enabled');
|
||||
await this.cache.connect(this.redis as Redis);
|
||||
const keys = await this.cache.getInstanceKeys();
|
||||
const keys = await this.cache.keys();
|
||||
|
||||
if (keys?.length > 0) {
|
||||
this.logger.verbose('Reading instance keys and setting instances');
|
||||
await Promise.all(keys.map((k) => this.setInstance(k.split(':')[1])));
|
||||
await Promise.all(keys.map((k) => this.setInstance(k.split(':')[2])));
|
||||
} else {
|
||||
this.logger.verbose('No instance keys found');
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/* eslint-disable @typescript-eslint/no-namespace */
|
||||
import { AuthenticationState, WAConnectionState } from '@whiskeysockets/baileys';
|
||||
import { AuthenticationState, WAConnectionState } from 'baileys';
|
||||
|
||||
export enum Events {
|
||||
APPLICATION_STARTUP = 'application.startup',
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
import { CacheConf, ConfigService } from '../../../../config/env.config';
|
||||
import { ICache } from '../../../abstract/abstract.cache';
|
||||
import { ICache } from '../api/abstract/abstract.cache';
|
||||
import { CacheConf, ConfigService } from '../config/env.config';
|
||||
import { Logger } from '../config/logger.config';
|
||||
import { LocalCache } from './localcache';
|
||||
import { RedisCache } from './rediscache';
|
||||
|
||||
const logger = new Logger('Redis');
|
||||
|
||||
export class CacheEngine {
|
||||
private engine: ICache;
|
||||
|
||||
@@ -14,6 +17,8 @@ export class CacheEngine {
|
||||
} else if (cacheConf?.LOCAL?.ENABLED) {
|
||||
this.engine = new LocalCache(configService, module);
|
||||
}
|
||||
|
||||
logger.info(`RedisCache initialized for ${module}`);
|
||||
}
|
||||
|
||||
public getEngine() {
|
||||
@@ -1,7 +1,7 @@
|
||||
import NodeCache from 'node-cache';
|
||||
|
||||
import { CacheConf, CacheConfLocal, ConfigService } from '../../../../config/env.config';
|
||||
import { ICache } from '../../../abstract/abstract.cache';
|
||||
import { ICache } from '../api/abstract/abstract.cache';
|
||||
import { CacheConf, CacheConfLocal, ConfigService } from '../config/env.config';
|
||||
|
||||
export class LocalCache implements ICache {
|
||||
private conf: CacheConfLocal;
|
||||
@@ -45,4 +45,17 @@ export class LocalCache implements ICache {
|
||||
buildKey(key: string) {
|
||||
return `${this.module}:${key}`;
|
||||
}
|
||||
|
||||
async hGet() {
|
||||
console.log('hGet not implemented');
|
||||
}
|
||||
|
||||
async hSet() {
|
||||
console.log('hSet not implemented');
|
||||
}
|
||||
|
||||
async hDelete() {
|
||||
console.log('hDelete not implemented');
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { createClient, RedisClientType } from 'redis';
|
||||
|
||||
import { CacheConf, CacheConfRedis, configService } from '../../../../config/env.config';
|
||||
import { Logger } from '../../../../config/logger.config';
|
||||
import { CacheConf, CacheConfRedis, configService } from '../config/env.config';
|
||||
import { Logger } from '../config/logger.config';
|
||||
|
||||
class Redis {
|
||||
private logger = new Logger(Redis.name);
|
||||
@@ -1,8 +1,9 @@
|
||||
import { BufferJSON } from 'baileys';
|
||||
import { RedisClientType } from 'redis';
|
||||
|
||||
import { CacheConf, CacheConfRedis, ConfigService } from '../../../../config/env.config';
|
||||
import { Logger } from '../../../../config/logger.config';
|
||||
import { ICache } from '../../../abstract/abstract.cache';
|
||||
import { ICache } from '../api/abstract/abstract.cache';
|
||||
import { CacheConf, CacheConfRedis, ConfigService } from '../config/env.config';
|
||||
import { Logger } from '../config/logger.config';
|
||||
import { redisClient } from './rediscache.client';
|
||||
|
||||
export class RedisCache implements ICache {
|
||||
@@ -14,7 +15,6 @@ export class RedisCache implements ICache {
|
||||
this.conf = this.configService.get<CacheConf>('CACHE')?.REDIS;
|
||||
this.client = redisClient.getConnection();
|
||||
}
|
||||
|
||||
async get(key: string): Promise<any> {
|
||||
try {
|
||||
return JSON.parse(await this.client.get(this.buildKey(key)));
|
||||
@@ -23,6 +23,20 @@ export class RedisCache implements ICache {
|
||||
}
|
||||
}
|
||||
|
||||
async hGet(key: string, field: string) {
|
||||
try {
|
||||
const data = await this.client.hGet(this.buildKey(key), field);
|
||||
|
||||
if (data) {
|
||||
return JSON.parse(data, BufferJSON.reviver);
|
||||
}
|
||||
|
||||
return null;
|
||||
} catch (error) {
|
||||
this.logger.error(error);
|
||||
}
|
||||
}
|
||||
|
||||
async set(key: string, value: any, ttl?: number) {
|
||||
try {
|
||||
await this.client.setEx(this.buildKey(key), ttl || this.conf?.TTL, JSON.stringify(value));
|
||||
@@ -31,6 +45,16 @@ export class RedisCache implements ICache {
|
||||
}
|
||||
}
|
||||
|
||||
async hSet(key: string, field: string, value: any) {
|
||||
try {
|
||||
const json = JSON.stringify(value, BufferJSON.replacer);
|
||||
|
||||
await this.client.hSet(this.buildKey(key), field, json);
|
||||
} catch (error) {
|
||||
this.logger.error(error);
|
||||
}
|
||||
}
|
||||
|
||||
async has(key: string) {
|
||||
try {
|
||||
return (await this.client.exists(this.buildKey(key))) > 0;
|
||||
@@ -47,6 +71,14 @@ export class RedisCache implements ICache {
|
||||
}
|
||||
}
|
||||
|
||||
async hDelete(key: string, field: string) {
|
||||
try {
|
||||
return await this.client.hDel(this.buildKey(key), field);
|
||||
} catch (error) {
|
||||
this.logger.error(error);
|
||||
}
|
||||
}
|
||||
|
||||
async deleteAll(appendCriteria?: string) {
|
||||
try {
|
||||
const keys = await this.keys(appendCriteria);
|
||||
@@ -63,12 +63,6 @@ export type Database = {
|
||||
SAVE_DATA: SaveData;
|
||||
};
|
||||
|
||||
export type Redis = {
|
||||
ENABLED: boolean;
|
||||
URI: string;
|
||||
PREFIX_KEY: string;
|
||||
};
|
||||
|
||||
export type Rabbitmq = {
|
||||
ENABLED: boolean;
|
||||
MODE: string; // global, single, isolated
|
||||
@@ -153,6 +147,7 @@ export type CacheConfRedis = {
|
||||
URI: string;
|
||||
PREFIX_KEY: string;
|
||||
TTL: number;
|
||||
SAVE_INSTANCES: boolean;
|
||||
};
|
||||
export type CacheConfLocal = {
|
||||
ENABLED: boolean;
|
||||
@@ -186,7 +181,6 @@ export interface Env {
|
||||
STORE: StoreConf;
|
||||
CLEAN_STORE: CleanStoreConf;
|
||||
DATABASE: Database;
|
||||
REDIS: Redis;
|
||||
RABBITMQ: Rabbitmq;
|
||||
SQS: Sqs;
|
||||
WEBSOCKET: Websocket;
|
||||
@@ -280,11 +274,6 @@ export class ConfigService {
|
||||
LABELS: process.env?.DATABASE_SAVE_DATA_LABELS === 'true',
|
||||
},
|
||||
},
|
||||
REDIS: {
|
||||
ENABLED: process.env?.REDIS_ENABLED === 'true',
|
||||
URI: process.env.REDIS_URI || '',
|
||||
PREFIX_KEY: process.env.REDIS_PREFIX_KEY || 'evolution',
|
||||
},
|
||||
RABBITMQ: {
|
||||
ENABLED: process.env?.RABBITMQ_ENABLED === 'true',
|
||||
MODE: process.env?.RABBITMQ_MODE || 'isolated',
|
||||
@@ -398,6 +387,7 @@ export class ConfigService {
|
||||
URI: process.env?.CACHE_REDIS_URI || '',
|
||||
PREFIX_KEY: process.env?.CACHE_REDIS_PREFIX_KEY || 'evolution-cache',
|
||||
TTL: Number.parseInt(process.env?.CACHE_REDIS_TTL) || 604800,
|
||||
SAVE_INSTANCES: process.env?.CACHE_REDIS_SAVE_INSTANCES === 'true',
|
||||
},
|
||||
LOCAL: {
|
||||
ENABLED: process.env?.CACHE_LOCAL_ENABLED === 'true',
|
||||
|
||||
@@ -60,10 +60,16 @@ export class Logger {
|
||||
private readonly configService = configService;
|
||||
constructor(private context = 'Logger') {}
|
||||
|
||||
private instance = null;
|
||||
|
||||
public setContext(value: string) {
|
||||
this.context = value;
|
||||
}
|
||||
|
||||
public setInstance(value: string) {
|
||||
this.instance = value;
|
||||
}
|
||||
|
||||
private console(value: any, type: Type) {
|
||||
const types: Type[] = [];
|
||||
|
||||
@@ -76,6 +82,8 @@ export class Logger {
|
||||
/*Command.UNDERSCORE +*/ Command.BRIGHT + Level[type],
|
||||
'[Evolution API]',
|
||||
Command.BRIGHT + Color[type],
|
||||
this.instance ? `[${this.instance}]` : '',
|
||||
Command.BRIGHT + Color[type],
|
||||
`v${packageJson.version}`,
|
||||
Command.BRIGHT + Color[type],
|
||||
process.pid.toString(),
|
||||
@@ -99,6 +107,7 @@ export class Logger {
|
||||
} else {
|
||||
console.log(
|
||||
'[Evolution API]',
|
||||
this.instance ? `[${this.instance}]` : '',
|
||||
process.pid.toString(),
|
||||
'-',
|
||||
`${formatDateLog(Date.now())} `,
|
||||
|
||||
@@ -77,11 +77,6 @@ DATABASE:
|
||||
CONTACTS: false
|
||||
CHATS: false
|
||||
|
||||
REDIS:
|
||||
ENABLED: false
|
||||
URI: "redis://localhost:6379"
|
||||
PREFIX_KEY: "evolution"
|
||||
|
||||
RABBITMQ:
|
||||
ENABLED: false
|
||||
MODE: "global"
|
||||
@@ -181,8 +176,9 @@ CACHE:
|
||||
REDIS:
|
||||
ENABLED: false
|
||||
URI: "redis://localhost:6379"
|
||||
PREFIX_KEY: "evolution-cache"
|
||||
PREFIX_KEY: "evolution"
|
||||
TTL: 604800
|
||||
SAVE_INSTANCES: false
|
||||
LOCAL:
|
||||
ENABLED: false
|
||||
TTL: 86400
|
||||
|
||||
@@ -25,7 +25,7 @@ info:
|
||||
</font>
|
||||
|
||||
[](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.2
|
||||
version: 1.7.4
|
||||
contact:
|
||||
name: DavidsonGomes
|
||||
email: contato@agenciadgcode.com
|
||||
|
||||
@@ -1,123 +0,0 @@
|
||||
import { createClient, RedisClientType } from '@redis/client';
|
||||
import { BufferJSON } from '@whiskeysockets/baileys';
|
||||
|
||||
import { Redis } from '../config/env.config';
|
||||
import { Logger } from '../config/logger.config';
|
||||
|
||||
export class RedisCache {
|
||||
private readonly logger = new Logger(RedisCache.name);
|
||||
private client: RedisClientType;
|
||||
private statusConnection = false;
|
||||
private instanceName: string;
|
||||
private redisEnv: Redis;
|
||||
|
||||
constructor() {
|
||||
this.logger.verbose('RedisCache instance created');
|
||||
process.on('beforeExit', () => {
|
||||
this.logger.verbose('RedisCache instance destroyed');
|
||||
this.disconnect();
|
||||
});
|
||||
}
|
||||
|
||||
public set reference(reference: string) {
|
||||
this.logger.verbose('set reference: ' + reference);
|
||||
this.instanceName = reference;
|
||||
}
|
||||
|
||||
public async connect(redisEnv: Redis) {
|
||||
this.logger.verbose('Connecting to Redis...');
|
||||
this.client = createClient({ url: redisEnv.URI });
|
||||
this.client.on('error', (err) => this.logger.error('Redis Client Error ' + err));
|
||||
|
||||
await this.client.connect();
|
||||
this.statusConnection = true;
|
||||
this.redisEnv = redisEnv;
|
||||
this.logger.verbose(`Connected to ${redisEnv.URI}`);
|
||||
}
|
||||
|
||||
public async disconnect() {
|
||||
if (this.statusConnection) {
|
||||
await this.client.disconnect();
|
||||
this.statusConnection = false;
|
||||
this.logger.verbose('Redis client disconnected');
|
||||
}
|
||||
}
|
||||
|
||||
public async getInstanceKeys(): Promise<string[]> {
|
||||
const keys: string[] = [];
|
||||
try {
|
||||
this.logger.verbose('Fetching instance keys');
|
||||
for await (const key of this.client.scanIterator({ MATCH: `${this.redisEnv.PREFIX_KEY}:*` })) {
|
||||
keys.push(key);
|
||||
}
|
||||
return keys;
|
||||
} catch (error) {
|
||||
this.logger.error('Error fetching instance keys ' + error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
public async keyExists(key?: string) {
|
||||
try {
|
||||
const keys = await this.getInstanceKeys();
|
||||
const targetKey = key || this.instanceName;
|
||||
this.logger.verbose('keyExists: ' + targetKey);
|
||||
return keys.includes(targetKey);
|
||||
} catch (error) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public async setData(field: string, data: any) {
|
||||
try {
|
||||
this.logger.verbose('setData: ' + field);
|
||||
const json = JSON.stringify(data, BufferJSON.replacer);
|
||||
await this.client.hSet(this.redisEnv.PREFIX_KEY + ':' + this.instanceName, field, json);
|
||||
return true;
|
||||
} catch (error) {
|
||||
this.logger.error(error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public async getData(field: string): Promise<any | null> {
|
||||
try {
|
||||
this.logger.verbose('getData: ' + field);
|
||||
const data = await this.client.hGet(this.redisEnv.PREFIX_KEY + ':' + this.instanceName, field);
|
||||
|
||||
if (data) {
|
||||
this.logger.verbose('getData: ' + field + ' success');
|
||||
return JSON.parse(data, BufferJSON.reviver);
|
||||
}
|
||||
|
||||
this.logger.verbose('getData: ' + field + ' not found');
|
||||
return null;
|
||||
} catch (error) {
|
||||
this.logger.error(error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public async removeData(field: string): Promise<boolean> {
|
||||
try {
|
||||
this.logger.verbose('removeData: ' + field);
|
||||
await this.client.hDel(this.redisEnv.PREFIX_KEY + ':' + this.instanceName, field);
|
||||
return true;
|
||||
} catch (error) {
|
||||
this.logger.error(error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public async delAll(hash?: string): Promise<boolean> {
|
||||
try {
|
||||
const targetHash = hash || this.redisEnv.PREFIX_KEY + ':' + this.instanceName;
|
||||
this.logger.verbose('instance delAll: ' + targetHash);
|
||||
const result = await this.client.del(targetHash);
|
||||
return !!result;
|
||||
} catch (error) {
|
||||
this.logger.error(error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import path from 'path';
|
||||
|
||||
import { ConfigService, Language } from '../config/env.config';
|
||||
|
||||
const languages = ['en', 'pt-BR'];
|
||||
const languages = ['en', 'pt-BR', 'es'];
|
||||
const translationsPath = path.join(__dirname, 'translations');
|
||||
const configService: ConfigService = new ConfigService();
|
||||
|
||||
|
||||
@@ -22,5 +22,6 @@
|
||||
"cw.contactMessage.contact": "Contact",
|
||||
"cw.contactMessage.name": "Name",
|
||||
"cw.contactMessage.number": "Number",
|
||||
"cw.message.notsent": "🚨 The message could not be sent. Please check your connection. {{error}}",
|
||||
"cw.message.edited": "Edited Message"
|
||||
}
|
||||
27
src/utils/translations/es.json
Normal file
27
src/utils/translations/es.json
Normal file
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"qrgeneratedsuccesfully": "Código QR generado exitosamente!",
|
||||
"scanqr": "Escanea este código QR en los próximos 40 segundos.",
|
||||
"qrlimitreached": "🚨 Se alcanzó el límite de generación de QRCode. Para generar un nuevo QRCode, envíe el mensaje 'init' nuevamente.",
|
||||
"numbernotinwhatsapp": "⚠️ El mensaje no fue enviado porque el contacto no es un número de Whatsapp válido..",
|
||||
"cw.inbox.connected": "🚀 ¡Conexión establecida exitosamente!",
|
||||
"cw.inbox.disconnect": "🚨 Instancia *{{inboxName}}* desconectado de Whatsapp.",
|
||||
"cw.inbox.alreadyConnected": "🚨 La instancia {{inboxName}} está conectada.",
|
||||
"cw.inbox.clearCache": "✅ Caché de la instancia {{inboxName}} borrada.",
|
||||
"cw.inbox.notFound": "⚠️ Instancia {{inboxName}} no encontrada.",
|
||||
"cw.inbox.status": "⚠️ Estado de la instancia {{inboxName}}: *{{state}}*.",
|
||||
"cw.import.startImport": "💬 Empezando a importar mensajes. Espere por favor...",
|
||||
"cw.import.importingMessages": "💬 Importando mensajes. mas un momento...",
|
||||
"cw.import.messagesImported": "💬 {{totalMessagesImported}} mensajes importados. Actualiza la página para ver los nuevos mensajes..",
|
||||
"cw.import.messagesException": "⚠️ Algo salió mal al importar mensajes..",
|
||||
"cw.locationMessage.location": "Ubicación",
|
||||
"cw.locationMessage.latitude": "Latitude",
|
||||
"cw.locationMessage.longitude": "Longitude",
|
||||
"cw.locationMessage.locationName": "Nombre",
|
||||
"cw.locationMessage.locationAddress": "Direccion",
|
||||
"cw.locationMessage.locationUrl": "URL",
|
||||
"cw.contactMessage.contact": "Contacto",
|
||||
"cw.contactMessage.name": "Nombre",
|
||||
"cw.contactMessage.number": "Numero",
|
||||
"cw.message.notsent": "🚨 El mensaje no se pudo enviar. Comprueba tu conexión. {{error}}",
|
||||
"cw.message.edited": "Mensaje editado"
|
||||
}
|
||||
@@ -22,5 +22,6 @@
|
||||
"cw.contactMessage.contact": "Contato",
|
||||
"cw.contactMessage.name": "Nome",
|
||||
"cw.contactMessage.number": "Número",
|
||||
"cw.message.notsent": "🚨 Não foi possível enviar a mensagem. Verifique sua conexão. {{error}}",
|
||||
"cw.message.edited": "Mensagem editada"
|
||||
}
|
||||
@@ -1,11 +1,4 @@
|
||||
import {
|
||||
AuthenticationCreds,
|
||||
AuthenticationState,
|
||||
BufferJSON,
|
||||
initAuthCreds,
|
||||
proto,
|
||||
SignalDataTypeMap,
|
||||
} from '@whiskeysockets/baileys';
|
||||
import { AuthenticationCreds, AuthenticationState, BufferJSON, initAuthCreds, proto, SignalDataTypeMap } from 'baileys';
|
||||
|
||||
import { configService, Database } from '../config/env.config';
|
||||
import { Logger } from '../config/logger.config';
|
||||
|
||||
@@ -1,15 +1,12 @@
|
||||
import {
|
||||
AuthenticationCreds,
|
||||
AuthenticationState,
|
||||
initAuthCreds,
|
||||
proto,
|
||||
SignalDataTypeMap,
|
||||
} from '@whiskeysockets/baileys';
|
||||
import { AuthenticationCreds, AuthenticationState, initAuthCreds, proto, SignalDataTypeMap } from 'baileys';
|
||||
|
||||
import { CacheService } from '../api/services/cache.service';
|
||||
import { Logger } from '../config/logger.config';
|
||||
import { RedisCache } from '../libs/redis.client';
|
||||
|
||||
export async function useMultiFileAuthStateRedisDb(cache: RedisCache): Promise<{
|
||||
export async function useMultiFileAuthStateRedisDb(
|
||||
instanceName: string,
|
||||
cache: CacheService,
|
||||
): Promise<{
|
||||
state: AuthenticationState;
|
||||
saveCreds: () => Promise<void>;
|
||||
}> {
|
||||
@@ -17,7 +14,7 @@ export async function useMultiFileAuthStateRedisDb(cache: RedisCache): Promise<{
|
||||
|
||||
const writeData = async (data: any, key: string): Promise<any> => {
|
||||
try {
|
||||
return await cache.setData(key, data);
|
||||
return await cache.hSet(instanceName, key, data);
|
||||
} catch (error) {
|
||||
return logger.error({ localError: 'writeData', error });
|
||||
}
|
||||
@@ -25,7 +22,7 @@ export async function useMultiFileAuthStateRedisDb(cache: RedisCache): Promise<{
|
||||
|
||||
const readData = async (key: string): Promise<any> => {
|
||||
try {
|
||||
return await cache.getData(key);
|
||||
return await cache.hGet(instanceName, key);
|
||||
} catch (error) {
|
||||
logger.error({ localError: 'readData', error });
|
||||
return;
|
||||
@@ -34,7 +31,7 @@ export async function useMultiFileAuthStateRedisDb(cache: RedisCache): Promise<{
|
||||
|
||||
const removeData = async (key: string) => {
|
||||
try {
|
||||
return await cache.removeData(key);
|
||||
return await cache.hDelete(instanceName, key);
|
||||
} catch (error) {
|
||||
logger.error({ readData: 'removeData', error });
|
||||
}
|
||||
|
||||
@@ -1,110 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="pt-br">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<link rel="shortcut icon" href="https://evolution-api.com/files/evolution-api-favicon.png" type="image/x-icon">
|
||||
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css"
|
||||
integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous">
|
||||
<title>Instance Manager</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div class="container mt-4">
|
||||
<!-- Botão para abrir o modal de adicionar nova instância -->
|
||||
<button class="btn btn-primary mb-3" data-toggle="modal" data-target="#actionModal" data-action="add">Nova
|
||||
Instância</button>
|
||||
|
||||
<!-- Tabela de instâncias -->
|
||||
<table class="table table-bordered">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Nome da Instância</th>
|
||||
<th>Status</th>
|
||||
<th>API Key</th>
|
||||
<th>Ações</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<!-- Iterando sobre as instâncias e preenchendo a tabela -->
|
||||
{{#each instances}}
|
||||
<tr>
|
||||
<td>{{this.instance.instanceName}}</td>
|
||||
<td>{{this.instance.status}}</td>
|
||||
<td>{{this.instance.apikey}}</td>
|
||||
<td>
|
||||
<!-- Dropdown de ações para cada instância -->
|
||||
<div class="dropdown">
|
||||
<button class="btn btn-secondary dropdown-toggle" type="button" id="actionDropdown"
|
||||
data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
|
||||
Ações
|
||||
</button>
|
||||
<div class="dropdown-menu" aria-labelledby="actionDropdown">
|
||||
<a class="dropdown-item" href="#" data-toggle="modal" data-target="#actionModal"
|
||||
data-action="connect">Connect</a>
|
||||
<a class="dropdown-item" href="#" data-toggle="modal" data-target="#actionModal"
|
||||
data-action="restart">Restart</a>
|
||||
<!-- Adicione mais itens de ação aqui -->
|
||||
<!-- ... -->
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
{{/each}}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<!-- Modal de ações -->
|
||||
<div class="modal fade" id="actionModal" tabindex="-1" role="dialog" aria-labelledby="actionModalLabel"
|
||||
aria-hidden="true">
|
||||
<div class="modal-dialog" role="document">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title" id="actionModalLabel">Ação</h5>
|
||||
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
|
||||
<span aria-hidden="true">×</span>
|
||||
</button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>
|
||||
<button type="button" class="btn btn-primary">Salvar</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js"
|
||||
integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
|
||||
crossorigin="anonymous"></script>
|
||||
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"
|
||||
integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN"
|
||||
crossorigin="anonymous"></script>
|
||||
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.min.js"
|
||||
integrity="sha384-+sLIOodYLS7CIrQpBjl+C7nPvqq+FbNUBDunl/OZv93DB7Ln/533i8e/mZXLi/P+"
|
||||
crossorigin="anonymous"></script>
|
||||
|
||||
<script>
|
||||
$(document).ready(function(){
|
||||
$('#actionModal').on('show.bs.modal', function(event) {
|
||||
var button = $(event.relatedTarget);
|
||||
var action = button.data('action');
|
||||
|
||||
console.log(action);
|
||||
|
||||
if (action === 'connect') {
|
||||
|
||||
} else if (action === 'restart') {
|
||||
|
||||
}
|
||||
});
|
||||
})
|
||||
</script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
Reference in New Issue
Block a user