mirror of
https://github.com/EvolutionAPI/evolution-api.git
synced 2025-12-18 19:32:21 -06:00
Merge branch 'develop' into main
This commit is contained in:
@@ -110,7 +110,7 @@ import makeWASocket, {
|
||||
isJidBroadcast,
|
||||
isJidGroup,
|
||||
isJidNewsletter,
|
||||
isJidUser,
|
||||
isPnUser,
|
||||
makeCacheableSignalKeyStore,
|
||||
MessageUpsertType,
|
||||
MessageUserReceiptUpdate,
|
||||
@@ -151,6 +151,19 @@ import { v4 } from 'uuid';
|
||||
import { BaileysMessageProcessor } from './baileysMessage.processor';
|
||||
import { useVoiceCallsBaileys } from './voiceCalls/useVoiceCallsBaileys';
|
||||
|
||||
export interface ExtendedMessageKey extends WAMessageKey {
|
||||
senderPn?: string;
|
||||
previousRemoteJid?: string | null;
|
||||
}
|
||||
|
||||
export interface ExtendedIMessageKey extends proto.IMessageKey {
|
||||
senderPn?: string;
|
||||
remoteJidAlt?: string;
|
||||
participantAlt?: string;
|
||||
server_id?: string;
|
||||
isViewOnce?: boolean;
|
||||
}
|
||||
|
||||
const groupMetadataCache = new CacheService(new CacheEngine(configService, 'groups').getEngine());
|
||||
|
||||
// Adicione a função getVideoDuration no início do arquivo
|
||||
@@ -484,9 +497,13 @@ export class BaileysStartupService extends ChannelStartupService {
|
||||
|
||||
private async getMessage(key: proto.IMessageKey, full = false) {
|
||||
try {
|
||||
const webMessageInfo = (await this.prismaRepository.message.findMany({
|
||||
where: { instanceId: this.instanceId, key: { path: ['id'], equals: key.id } },
|
||||
})) as unknown as proto.IWebMessageInfo[];
|
||||
// Use raw SQL to avoid JSON path issues
|
||||
const webMessageInfo = (await this.prismaRepository.$queryRaw`
|
||||
SELECT * FROM "Message"
|
||||
WHERE "instanceId" = ${this.instanceId}
|
||||
AND "key"->>'id' = ${key.id}
|
||||
`) as proto.IWebMessageInfo[];
|
||||
|
||||
if (full) {
|
||||
return webMessageInfo[0];
|
||||
}
|
||||
@@ -982,8 +999,8 @@ export class BaileysStartupService extends ChannelStartupService {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (m.key.remoteJid?.includes('@lid') && m.key.senderPn) {
|
||||
m.key.remoteJid = m.key.senderPn;
|
||||
if (m.key.remoteJid?.includes('@lid') && (m.key as ExtendedIMessageKey).senderPn) {
|
||||
m.key.remoteJid = (m.key as ExtendedIMessageKey).senderPn;
|
||||
}
|
||||
|
||||
if (Long.isLong(m?.messageTimestamp)) {
|
||||
@@ -1048,9 +1065,9 @@ export class BaileysStartupService extends ChannelStartupService {
|
||||
) => {
|
||||
try {
|
||||
for (const received of messages) {
|
||||
if (received.key.remoteJid?.includes('@lid') && received.key.senderPn) {
|
||||
(received.key as { previousRemoteJid?: string | null }).previousRemoteJid = received.key.remoteJid;
|
||||
received.key.remoteJid = received.key.senderPn;
|
||||
if (received.key.remoteJid?.includes('@lid') && (received.key as ExtendedMessageKey).senderPn) {
|
||||
(received.key as ExtendedMessageKey).previousRemoteJid = received.key.remoteJid;
|
||||
received.key.remoteJid = (received.key as ExtendedMessageKey).senderPn;
|
||||
}
|
||||
if (
|
||||
received?.messageStubParameters?.some?.((param) =>
|
||||
@@ -1407,8 +1424,8 @@ export class BaileysStartupService extends ChannelStartupService {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (key.remoteJid?.includes('@lid') && key.senderPn) {
|
||||
key.remoteJid = key.senderPn;
|
||||
if (key.remoteJid?.includes('@lid') && key.remoteJidAlt) {
|
||||
key.remoteJid = key.remoteJidAlt;
|
||||
}
|
||||
|
||||
const updateKey = `${this.instance.id}_${key.id}_${update.status}`;
|
||||
@@ -1459,9 +1476,14 @@ export class BaileysStartupService extends ChannelStartupService {
|
||||
let findMessage: any;
|
||||
const configDatabaseData = this.configService.get<Database>('DATABASE').SAVE_DATA;
|
||||
if (configDatabaseData.HISTORIC || configDatabaseData.NEW_MESSAGE) {
|
||||
findMessage = await this.prismaRepository.message.findFirst({
|
||||
where: { instanceId: this.instanceId, key: { path: ['id'], equals: key.id } },
|
||||
});
|
||||
// Use raw SQL to avoid JSON path issues
|
||||
const messages = (await this.prismaRepository.$queryRaw`
|
||||
SELECT * FROM "Message"
|
||||
WHERE "instanceId" = ${this.instanceId}
|
||||
AND "key"->>'id' = ${key.id}
|
||||
LIMIT 1
|
||||
`) as any[];
|
||||
findMessage = messages[0] || null;
|
||||
|
||||
if (findMessage) message.messageId = findMessage.id;
|
||||
}
|
||||
@@ -1910,7 +1932,7 @@ export class BaileysStartupService extends ChannelStartupService {
|
||||
quoted,
|
||||
});
|
||||
const id = await this.client.relayMessage(sender, message, { messageId });
|
||||
m.key = { id: id, remoteJid: sender, participant: isJidUser(sender) ? sender : undefined, fromMe: true };
|
||||
m.key = { id: id, remoteJid: sender, participant: isPnUser(sender) ? sender : undefined, fromMe: true };
|
||||
for (const [key, value] of Object.entries(m)) {
|
||||
if (!value || (isArray(value) && value.length) === 0) {
|
||||
delete m[key];
|
||||
@@ -3367,7 +3389,7 @@ export class BaileysStartupService extends ChannelStartupService {
|
||||
try {
|
||||
const keys: proto.IMessageKey[] = [];
|
||||
data.readMessages.forEach((read) => {
|
||||
if (isJidGroup(read.remoteJid) || isJidUser(read.remoteJid)) {
|
||||
if (isJidGroup(read.remoteJid) || isPnUser(read.remoteJid)) {
|
||||
keys.push({ remoteJid: read.remoteJid, fromMe: read.fromMe, id: read.id });
|
||||
}
|
||||
});
|
||||
@@ -4299,22 +4321,50 @@ export class BaileysStartupService extends ChannelStartupService {
|
||||
throw new Error('Method not available in the Baileys service');
|
||||
}
|
||||
|
||||
private convertLongToNumber(obj: any): any {
|
||||
if (obj === null || obj === undefined) {
|
||||
return obj;
|
||||
}
|
||||
|
||||
if (Long.isLong(obj)) {
|
||||
return obj.toNumber();
|
||||
}
|
||||
|
||||
if (Array.isArray(obj)) {
|
||||
return obj.map((item) => this.convertLongToNumber(item));
|
||||
}
|
||||
|
||||
if (typeof obj === 'object') {
|
||||
const converted: any = {};
|
||||
for (const key in obj) {
|
||||
if (Object.prototype.hasOwnProperty.call(obj, key)) {
|
||||
converted[key] = this.convertLongToNumber(obj[key]);
|
||||
}
|
||||
}
|
||||
return converted;
|
||||
}
|
||||
|
||||
return obj;
|
||||
}
|
||||
|
||||
private prepareMessage(message: proto.IWebMessageInfo): any {
|
||||
const contentType = getContentType(message.message);
|
||||
const contentMsg = message?.message[contentType] as any;
|
||||
|
||||
const messageRaw = {
|
||||
key: message.key,
|
||||
key: message.key, // Save key exactly as it comes from Baileys
|
||||
pushName:
|
||||
message.pushName ||
|
||||
(message.key.fromMe
|
||||
? 'Você'
|
||||
: message?.participant || (message.key?.participant ? message.key.participant.split('@')[0] : null)),
|
||||
status: status[message.status],
|
||||
message: { ...message.message },
|
||||
contextInfo: contentMsg?.contextInfo,
|
||||
message: this.convertLongToNumber({ ...message.message }),
|
||||
contextInfo: this.convertLongToNumber(contentMsg?.contextInfo),
|
||||
messageType: contentType || 'unknown',
|
||||
messageTimestamp: message.messageTimestamp as number,
|
||||
messageTimestamp: Long.isLong(message.messageTimestamp)
|
||||
? message.messageTimestamp.toNumber()
|
||||
: (message.messageTimestamp as number),
|
||||
instanceId: this.instanceId,
|
||||
source: getDevice(message.key.id),
|
||||
};
|
||||
@@ -4357,7 +4407,22 @@ export class BaileysStartupService extends ChannelStartupService {
|
||||
const prepare = (message: any) => this.prepareMessage(message);
|
||||
this.chatwootService.syncLostMessages({ instanceName: this.instance.name }, chatwootConfig, prepare);
|
||||
|
||||
// Generate ID for this cron task and store in cache
|
||||
const cronId = cuid();
|
||||
const cronKey = `chatwoot:syncLostMessages`;
|
||||
await this.chatwootService.getCache()?.hSet(cronKey, this.instance.name, cronId);
|
||||
|
||||
const task = cron.schedule('0,30 * * * *', async () => {
|
||||
// Check ID before executing (only if cache is available)
|
||||
const cache = this.chatwootService.getCache();
|
||||
if (cache) {
|
||||
const storedId = await cache.hGet(cronKey, this.instance.name);
|
||||
if (storedId && storedId !== cronId) {
|
||||
this.logger.info(`Stopping syncChatwootLostMessages cron - ID mismatch: ${cronId} vs ${storedId}`);
|
||||
task.stop();
|
||||
return;
|
||||
}
|
||||
}
|
||||
this.chatwootService.syncLostMessages({ instanceName: this.instance.name }, chatwootConfig, prepare);
|
||||
});
|
||||
task.start();
|
||||
@@ -4367,24 +4432,23 @@ export class BaileysStartupService extends ChannelStartupService {
|
||||
private async updateMessagesReadedByTimestamp(remoteJid: string, timestamp?: number): Promise<number> {
|
||||
if (timestamp === undefined || timestamp === null) return 0;
|
||||
|
||||
const result = await this.prismaRepository.message.updateMany({
|
||||
where: {
|
||||
AND: [
|
||||
{ key: { path: ['remoteJid'], equals: remoteJid } },
|
||||
{ key: { path: ['fromMe'], equals: false } },
|
||||
{ messageTimestamp: { lte: timestamp } },
|
||||
{ OR: [{ status: null }, { status: status[3] }] },
|
||||
],
|
||||
},
|
||||
data: { status: status[4] },
|
||||
});
|
||||
// Use raw SQL to avoid JSON path issues
|
||||
const result = await this.prismaRepository.$executeRaw`
|
||||
UPDATE "Message"
|
||||
SET "status" = ${status[4]}
|
||||
WHERE "instanceId" = ${this.instanceId}
|
||||
AND "key"->>'remoteJid' = ${remoteJid}
|
||||
AND ("key"->>'fromMe')::boolean = false
|
||||
AND "messageTimestamp" <= ${timestamp}
|
||||
AND ("status" IS NULL OR "status" = ${status[3]})
|
||||
`;
|
||||
|
||||
if (result) {
|
||||
if (result.count > 0) {
|
||||
if (result > 0) {
|
||||
this.updateChatUnreadMessages(remoteJid);
|
||||
}
|
||||
|
||||
return result.count;
|
||||
return result;
|
||||
}
|
||||
|
||||
return 0;
|
||||
@@ -4393,15 +4457,14 @@ export class BaileysStartupService extends ChannelStartupService {
|
||||
private async updateChatUnreadMessages(remoteJid: string): Promise<number> {
|
||||
const [chat, unreadMessages] = await Promise.all([
|
||||
this.prismaRepository.chat.findFirst({ where: { remoteJid } }),
|
||||
this.prismaRepository.message.count({
|
||||
where: {
|
||||
AND: [
|
||||
{ key: { path: ['remoteJid'], equals: remoteJid } },
|
||||
{ key: { path: ['fromMe'], equals: false } },
|
||||
{ status: { equals: status[3] } },
|
||||
],
|
||||
},
|
||||
}),
|
||||
// Use raw SQL to avoid JSON path issues
|
||||
this.prismaRepository.$queryRaw`
|
||||
SELECT COUNT(*)::int as count FROM "Message"
|
||||
WHERE "instanceId" = ${this.instanceId}
|
||||
AND "key"->>'remoteJid' = ${remoteJid}
|
||||
AND ("key"->>'fromMe')::boolean = false
|
||||
AND "status" = ${status[3]}
|
||||
`.then((result: any[]) => result[0]?.count || 0),
|
||||
]);
|
||||
|
||||
if (chat && chat.unreadMessages !== unreadMessages) {
|
||||
|
||||
@@ -2,6 +2,7 @@ import { IgnoreJidDto } from '@api/dto/chatbot.dto';
|
||||
import { InstanceDto } from '@api/dto/instance.dto';
|
||||
import { PrismaRepository } from '@api/repository/repository.service';
|
||||
import { WAMonitoringService } from '@api/services/monitor.service';
|
||||
import { Events } from '@api/types/wa.types';
|
||||
import { Logger } from '@config/logger.config';
|
||||
import { BadRequestException } from '@exceptions';
|
||||
import { TriggerOperator, TriggerType } from '@prisma/client';
|
||||
@@ -446,6 +447,16 @@ export abstract class BaseChatbotController<BotType = any, BotData extends BaseC
|
||||
|
||||
const remoteJid = data.remoteJid;
|
||||
const status = data.status;
|
||||
const session = await this.getSession(remoteJid, instance);
|
||||
|
||||
if (this.integrationName === 'Typebot') {
|
||||
const typebotData = {
|
||||
remoteJid: remoteJid,
|
||||
status: status,
|
||||
session,
|
||||
};
|
||||
this.waMonitor.waInstances[instance.instanceName].sendDataWebhook(Events.TYPEBOT_CHANGE_STATUS, typebotData);
|
||||
}
|
||||
|
||||
if (status === 'delete') {
|
||||
await this.sessionRepository.deleteMany({
|
||||
@@ -867,6 +878,16 @@ export abstract class BaseChatbotController<BotType = any, BotData extends BaseC
|
||||
status: 'paused',
|
||||
},
|
||||
});
|
||||
|
||||
if (this.integrationName === 'Typebot') {
|
||||
const typebotData = {
|
||||
remoteJid: remoteJid,
|
||||
status: 'paused',
|
||||
session,
|
||||
};
|
||||
this.waMonitor.waInstances[instance.instanceName].sendDataWebhook(Events.TYPEBOT_CHANGE_STATUS, typebotData);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -880,12 +901,6 @@ export abstract class BaseChatbotController<BotType = any, BotData extends BaseC
|
||||
return;
|
||||
}
|
||||
|
||||
// Skip if session exists and status is paused
|
||||
if (session && session.status === 'paused') {
|
||||
this.logger.warn(`Session for ${remoteJid} is paused, skipping message processing`);
|
||||
return;
|
||||
}
|
||||
|
||||
// Merged settings
|
||||
const mergedSettings = {
|
||||
...settings,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { InstanceDto } from '@api/dto/instance.dto';
|
||||
import { Options, Quoted, SendAudioDto, SendMediaDto, SendTextDto } from '@api/dto/sendMessage.dto';
|
||||
import { ExtendedMessageKey } from '@api/integrations/channel/whatsapp/whatsapp.baileys.service';
|
||||
import { ChatwootDto } from '@api/integrations/chatbot/chatwoot/dto/chatwoot.dto';
|
||||
import { postgresClient } from '@api/integrations/chatbot/chatwoot/libs/postgres.client';
|
||||
import { chatwootImport } from '@api/integrations/chatbot/chatwoot/utils/chatwoot-import-helper';
|
||||
@@ -567,13 +568,6 @@ export class ChatwootService {
|
||||
}
|
||||
|
||||
public async createConversation(instance: InstanceDto, body: any) {
|
||||
if (!body?.key) {
|
||||
this.logger.warn(
|
||||
`body.key is null or undefined in createConversation. Full body object: ${JSON.stringify(body)}`,
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
const isLid = body.key.previousRemoteJid?.includes('@lid') && body.key.senderPn;
|
||||
const remoteJid = body.key.remoteJid;
|
||||
const cacheKey = `${instance.instanceName}:createConversation-${remoteJid}`;
|
||||
@@ -1291,12 +1285,7 @@ export class ChatwootService {
|
||||
});
|
||||
|
||||
if (message) {
|
||||
const key = message.key as {
|
||||
id: string;
|
||||
remoteJid: string;
|
||||
fromMe: boolean;
|
||||
participant: string;
|
||||
};
|
||||
const key = message.key as ExtendedMessageKey;
|
||||
|
||||
await waInstance?.client.sendMessage(key.remoteJid, { delete: key });
|
||||
|
||||
@@ -1494,12 +1483,7 @@ export class ChatwootService {
|
||||
},
|
||||
});
|
||||
if (lastMessage && !lastMessage.chatwootIsRead) {
|
||||
const key = lastMessage.key as {
|
||||
id: string;
|
||||
fromMe: boolean;
|
||||
remoteJid: string;
|
||||
participant?: string;
|
||||
};
|
||||
const key = lastMessage.key as ExtendedMessageKey;
|
||||
|
||||
waInstance?.markMessageAsRead({
|
||||
readMessages: [
|
||||
@@ -1557,33 +1541,24 @@ export class ChatwootService {
|
||||
chatwootMessageIds: ChatwootMessage,
|
||||
instance: InstanceDto,
|
||||
) {
|
||||
const key = message.key as {
|
||||
id: string;
|
||||
fromMe: boolean;
|
||||
remoteJid: string;
|
||||
participant?: string;
|
||||
};
|
||||
const key = message.key as ExtendedMessageKey;
|
||||
|
||||
if (!chatwootMessageIds.messageId || !key?.id) {
|
||||
return;
|
||||
}
|
||||
|
||||
await this.prismaRepository.message.updateMany({
|
||||
where: {
|
||||
key: {
|
||||
path: ['id'],
|
||||
equals: key.id,
|
||||
},
|
||||
instanceId: instance.instanceId,
|
||||
},
|
||||
data: {
|
||||
chatwootMessageId: chatwootMessageIds.messageId,
|
||||
chatwootConversationId: chatwootMessageIds.conversationId,
|
||||
chatwootInboxId: chatwootMessageIds.inboxId,
|
||||
chatwootContactInboxSourceId: chatwootMessageIds.contactInboxSourceId,
|
||||
chatwootIsRead: chatwootMessageIds.isRead,
|
||||
},
|
||||
});
|
||||
// Use raw SQL to avoid JSON path issues
|
||||
await this.prismaRepository.$executeRaw`
|
||||
UPDATE "Message"
|
||||
SET
|
||||
"chatwootMessageId" = ${chatwootMessageIds.messageId},
|
||||
"chatwootConversationId" = ${chatwootMessageIds.conversationId},
|
||||
"chatwootInboxId" = ${chatwootMessageIds.inboxId},
|
||||
"chatwootContactInboxSourceId" = ${chatwootMessageIds.contactInboxSourceId},
|
||||
"chatwootIsRead" = ${chatwootMessageIds.isRead || false}
|
||||
WHERE "instanceId" = ${instance.instanceId}
|
||||
AND "key"->>'id' = ${key.id}
|
||||
`;
|
||||
|
||||
if (this.isImportHistoryAvailable()) {
|
||||
chatwootImport.updateMessageSourceID(chatwootMessageIds.messageId, key.id);
|
||||
@@ -1591,17 +1566,15 @@ export class ChatwootService {
|
||||
}
|
||||
|
||||
private async getMessageByKeyId(instance: InstanceDto, keyId: string): Promise<MessageModel> {
|
||||
const messages = await this.prismaRepository.message.findFirst({
|
||||
where: {
|
||||
key: {
|
||||
path: ['id'],
|
||||
equals: keyId,
|
||||
},
|
||||
instanceId: instance.instanceId,
|
||||
},
|
||||
});
|
||||
// Use raw SQL query to avoid JSON path issues with Prisma
|
||||
const messages = await this.prismaRepository.$queryRaw`
|
||||
SELECT * FROM "Message"
|
||||
WHERE "instanceId" = ${instance.instanceId}
|
||||
AND "key"->>'id' = ${keyId}
|
||||
LIMIT 1
|
||||
`;
|
||||
|
||||
return messages || null;
|
||||
return (messages as MessageModel[])[0] || null;
|
||||
}
|
||||
|
||||
private async getReplyToIds(
|
||||
@@ -1636,12 +1609,7 @@ export class ChatwootService {
|
||||
},
|
||||
});
|
||||
|
||||
const key = message?.key as {
|
||||
id: string;
|
||||
fromMe: boolean;
|
||||
remoteJid: string;
|
||||
participant?: string;
|
||||
};
|
||||
const key = message?.key as ExtendedMessageKey;
|
||||
|
||||
if (message && key?.id) {
|
||||
return {
|
||||
@@ -1900,12 +1868,6 @@ export class ChatwootService {
|
||||
|
||||
public async eventWhatsapp(event: string, instance: InstanceDto, body: any) {
|
||||
try {
|
||||
// Ignore events that are not messages (like EPHEMERAL_SYNC_RESPONSE)
|
||||
if (body?.type && body.type !== 'message' && body.type !== 'conversation') {
|
||||
this.logger.verbose(`Ignoring non-message event type: ${body.type}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const waInstance = this.waMonitor.waInstances[instance.instanceName];
|
||||
|
||||
if (!waInstance) {
|
||||
@@ -1951,11 +1913,6 @@ export class ChatwootService {
|
||||
}
|
||||
|
||||
if (event === 'messages.upsert' || event === 'send.message') {
|
||||
if (!body?.key) {
|
||||
this.logger.warn(`body.key is null or undefined. Full body object: ${JSON.stringify(body)}`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (body.key.remoteJid === 'status@broadcast') {
|
||||
return;
|
||||
}
|
||||
@@ -2278,29 +2235,17 @@ export class ChatwootService {
|
||||
}
|
||||
|
||||
if (event === 'messages.edit' || event === 'send.message.update') {
|
||||
// Ignore events that are not messages (like EPHEMERAL_SYNC_RESPONSE)
|
||||
if (body?.type && body.type !== 'message') {
|
||||
this.logger.verbose(`Ignoring non-message event type: ${body.type}`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!body?.key?.id) {
|
||||
this.logger.warn(
|
||||
`body.key.id is null or undefined in messages.edit. Full body object: ${JSON.stringify(body)}`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const editedText = `${
|
||||
body?.editedMessage?.conversation || body?.editedMessage?.extendedTextMessage?.text
|
||||
}\n\n_\`${i18next.t('cw.message.edited')}.\`_`;
|
||||
const message = await this.getMessageByKeyId(instance, body.key.id);
|
||||
const key = message.key as {
|
||||
id: string;
|
||||
fromMe: boolean;
|
||||
remoteJid: string;
|
||||
participant?: string;
|
||||
};
|
||||
const message = await this.getMessageByKeyId(instance, body?.key?.id);
|
||||
|
||||
if (!message) {
|
||||
this.logger.warn('Message not found for edit event');
|
||||
return;
|
||||
}
|
||||
|
||||
const key = message.key as ExtendedMessageKey;
|
||||
|
||||
const messageType = key?.fromMe ? 'outgoing' : 'incoming';
|
||||
|
||||
@@ -2578,7 +2523,7 @@ export class ChatwootService {
|
||||
const savedMessages = await this.prismaRepository.message.findMany({
|
||||
where: {
|
||||
Instance: { name: instance.instanceName },
|
||||
messageTimestamp: { gte: dayjs().subtract(6, 'hours').unix() },
|
||||
messageTimestamp: { gte: Number(dayjs().subtract(6, 'hours').unix()) },
|
||||
AND: ids.map((id) => ({ key: { path: ['id'], not: id } })),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -106,15 +106,37 @@ export class EvolutionBotService extends BaseChatbotService<EvolutionBot, Evolut
|
||||
};
|
||||
}
|
||||
|
||||
// Sanitize payload for logging (remove sensitive data)
|
||||
const sanitizedPayload = {
|
||||
...payload,
|
||||
inputs: {
|
||||
...payload.inputs,
|
||||
apiKey: payload.inputs.apiKey ? '[REDACTED]' : undefined,
|
||||
},
|
||||
};
|
||||
|
||||
this.logger.debug(`[EvolutionBot] Sending request to endpoint: ${endpoint}`);
|
||||
this.logger.debug(`[EvolutionBot] Request payload: ${JSON.stringify(sanitizedPayload, null, 2)}`);
|
||||
|
||||
const response = await axios.post(endpoint, payload, {
|
||||
headers,
|
||||
});
|
||||
|
||||
this.logger.debug(`[EvolutionBot] Response received - Status: ${response.status}`);
|
||||
|
||||
if (instance.integration === Integration.WHATSAPP_BAILEYS) {
|
||||
await instance.client.sendPresenceUpdate('paused', remoteJid);
|
||||
}
|
||||
|
||||
let message = response?.data?.message;
|
||||
const rawLinkPreview = response?.data?.linkPreview;
|
||||
|
||||
// Validate linkPreview is boolean and default to true for backward compatibility
|
||||
const linkPreview = typeof rawLinkPreview === 'boolean' ? rawLinkPreview : true;
|
||||
|
||||
this.logger.debug(
|
||||
`[EvolutionBot] Processing response - Message length: ${message?.length || 0}, LinkPreview: ${linkPreview}`,
|
||||
);
|
||||
|
||||
if (message && typeof message === 'string' && message.startsWith("'") && message.endsWith("'")) {
|
||||
const innerContent = message.slice(1, -1);
|
||||
@@ -124,8 +146,19 @@ export class EvolutionBotService extends BaseChatbotService<EvolutionBot, Evolut
|
||||
}
|
||||
|
||||
if (message) {
|
||||
// Use the base class method to send the message to WhatsApp
|
||||
await this.sendMessageWhatsApp(instance, remoteJid, message, settings);
|
||||
// Send message directly with validated linkPreview option
|
||||
await instance.textMessage(
|
||||
{
|
||||
number: remoteJid.split('@')[0],
|
||||
delay: settings?.delayMessage || 1000,
|
||||
text: message,
|
||||
linkPreview, // Always boolean, defaults to true
|
||||
},
|
||||
false,
|
||||
);
|
||||
this.logger.debug(`[EvolutionBot] Message sent successfully with linkPreview: ${linkPreview}`);
|
||||
} else {
|
||||
this.logger.warn(`[EvolutionBot] No message content received from bot response`);
|
||||
}
|
||||
|
||||
// Send telemetry
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { PrismaRepository } from '@api/repository/repository.service';
|
||||
import { WAMonitoringService } from '@api/services/monitor.service';
|
||||
import { Events } from '@api/types/wa.types';
|
||||
import { Auth, ConfigService, HttpServer, Typebot } from '@config/env.config';
|
||||
import { Instance, IntegrationSession, Message, Typebot as TypebotModel } from '@prisma/client';
|
||||
import { getConversationMessage } from '@utils/getConversationMessage';
|
||||
@@ -151,6 +152,14 @@ export class TypebotService extends BaseChatbotService<TypebotModel, any> {
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const typebotData = {
|
||||
remoteJid: data.remoteJid,
|
||||
status: 'opened',
|
||||
session,
|
||||
};
|
||||
this.waMonitor.waInstances[instance.name].sendDataWebhook(Events.TYPEBOT_CHANGE_STATUS, typebotData);
|
||||
|
||||
return { ...request.data, session };
|
||||
} catch (error) {
|
||||
this.logger.error(error);
|
||||
@@ -399,12 +408,14 @@ export class TypebotService extends BaseChatbotService<TypebotModel, any> {
|
||||
},
|
||||
});
|
||||
} else {
|
||||
let statusChange = 'closed';
|
||||
if (!settings?.keepOpen) {
|
||||
await prismaRepository.integrationSession.deleteMany({
|
||||
where: {
|
||||
id: session.id,
|
||||
},
|
||||
});
|
||||
statusChange = 'delete';
|
||||
} else {
|
||||
await prismaRepository.integrationSession.update({
|
||||
where: {
|
||||
@@ -415,6 +426,13 @@ export class TypebotService extends BaseChatbotService<TypebotModel, any> {
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const typebotData = {
|
||||
remoteJid: session.remoteJid,
|
||||
status: statusChange,
|
||||
session,
|
||||
};
|
||||
instance.sendDataWebhook(Events.TYPEBOT_CHANGE_STATUS, typebotData);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -639,6 +657,7 @@ export class TypebotService extends BaseChatbotService<TypebotModel, any> {
|
||||
}
|
||||
|
||||
if (keywordFinish && content.toLowerCase() === keywordFinish.toLowerCase()) {
|
||||
let statusChange = 'closed';
|
||||
if (keepOpen) {
|
||||
await this.prismaRepository.integrationSession.update({
|
||||
where: {
|
||||
@@ -649,6 +668,7 @@ export class TypebotService extends BaseChatbotService<TypebotModel, any> {
|
||||
},
|
||||
});
|
||||
} else {
|
||||
statusChange = 'delete';
|
||||
await this.prismaRepository.integrationSession.deleteMany({
|
||||
where: {
|
||||
botId: findTypebot.id,
|
||||
@@ -656,6 +676,14 @@ export class TypebotService extends BaseChatbotService<TypebotModel, any> {
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const typebotData = {
|
||||
remoteJid: remoteJid,
|
||||
status: statusChange,
|
||||
session,
|
||||
};
|
||||
waInstance.sendDataWebhook(Events.TYPEBOT_CHANGE_STATUS, typebotData);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -788,6 +816,7 @@ export class TypebotService extends BaseChatbotService<TypebotModel, any> {
|
||||
}
|
||||
|
||||
if (keywordFinish && content.toLowerCase() === keywordFinish.toLowerCase()) {
|
||||
let statusChange = 'closed';
|
||||
if (keepOpen) {
|
||||
await this.prismaRepository.integrationSession.update({
|
||||
where: {
|
||||
@@ -798,6 +827,7 @@ export class TypebotService extends BaseChatbotService<TypebotModel, any> {
|
||||
},
|
||||
});
|
||||
} else {
|
||||
statusChange = 'delete';
|
||||
await this.prismaRepository.integrationSession.deleteMany({
|
||||
where: {
|
||||
botId: findTypebot.id,
|
||||
@@ -806,6 +836,13 @@ export class TypebotService extends BaseChatbotService<TypebotModel, any> {
|
||||
});
|
||||
}
|
||||
|
||||
const typebotData = {
|
||||
remoteJid: remoteJid,
|
||||
status: statusChange,
|
||||
session,
|
||||
};
|
||||
waInstance.sendDataWebhook(Events.TYPEBOT_CHANGE_STATUS, typebotData);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -881,6 +918,7 @@ export class TypebotService extends BaseChatbotService<TypebotModel, any> {
|
||||
}
|
||||
|
||||
if (keywordFinish && content.toLowerCase() === keywordFinish.toLowerCase()) {
|
||||
let statusChange = 'closed';
|
||||
if (keepOpen) {
|
||||
await this.prismaRepository.integrationSession.update({
|
||||
where: {
|
||||
@@ -891,6 +929,7 @@ export class TypebotService extends BaseChatbotService<TypebotModel, any> {
|
||||
},
|
||||
});
|
||||
} else {
|
||||
statusChange = 'delete';
|
||||
await this.prismaRepository.integrationSession.deleteMany({
|
||||
where: {
|
||||
botId: findTypebot.id,
|
||||
@@ -898,6 +937,15 @@ export class TypebotService extends BaseChatbotService<TypebotModel, any> {
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const typebotData = {
|
||||
remoteJid: remoteJid,
|
||||
status: statusChange,
|
||||
session,
|
||||
};
|
||||
|
||||
waInstance.sendDataWebhook(Events.TYPEBOT_CHANGE_STATUS, typebotData);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -31,11 +31,12 @@ export class WebsocketController extends EventController implements EventControl
|
||||
const params = new URLSearchParams(url.search);
|
||||
|
||||
const { remoteAddress } = req.socket;
|
||||
const isLocalhost =
|
||||
remoteAddress === '127.0.0.1' || remoteAddress === '::1' || remoteAddress === '::ffff:127.0.0.1';
|
||||
const isAllowedHost = (process.env.WEBSOCKET_ALLOWED_HOSTS || '127.0.0.1,::1,::ffff:127.0.0.1')
|
||||
.split(',')
|
||||
.map((h) => h.trim())
|
||||
.includes(remoteAddress);
|
||||
|
||||
// Permite conexões internas do Socket.IO (EIO=4 é o Engine.IO v4)
|
||||
if (params.has('EIO') && isLocalhost) {
|
||||
if (params.has('EIO') && isAllowedHost) {
|
||||
return callback(null, true);
|
||||
}
|
||||
|
||||
|
||||
@@ -29,6 +29,8 @@ export class WAMonitoringService {
|
||||
|
||||
Object.assign(this.db, configService.get<Database>('DATABASE'));
|
||||
Object.assign(this.redis, configService.get<CacheConf>('CACHE'));
|
||||
|
||||
(this as any).providerSession = Object.freeze(configService.get<ProviderSession>('PROVIDER'));
|
||||
}
|
||||
|
||||
private readonly db: Partial<Database> = {};
|
||||
@@ -37,7 +39,7 @@ export class WAMonitoringService {
|
||||
private readonly logger = new Logger('WAMonitoringService');
|
||||
public readonly waInstances: Record<string, any> = {};
|
||||
|
||||
private readonly providerSession = Object.freeze(this.configService.get<ProviderSession>('PROVIDER'));
|
||||
private readonly providerSession: ProviderSession;
|
||||
|
||||
public delInstanceTime(instance: string) {
|
||||
const time = this.configService.get<DelInstance>('DEL_INSTANCE');
|
||||
|
||||
Reference in New Issue
Block a user