mirror of
https://github.com/EvolutionAPI/evolution-api.git
synced 2026-01-11 14:22:19 -06:00
fix: baileys and chatwoot
This commit is contained in:
@@ -82,7 +82,7 @@ import { createId as cuid } from '@paralleldrive/cuid2';
|
||||
import { Instance, Message } from '@prisma/client';
|
||||
import { createJid } from '@utils/createJid';
|
||||
import { fetchLatestWaWebVersion } from '@utils/fetchLatestWaWebVersion';
|
||||
import {makeProxyAgent, makeProxyAgentUndici} from '@utils/makeProxyAgent';
|
||||
import { makeProxyAgent, makeProxyAgentUndici } from '@utils/makeProxyAgent';
|
||||
import { getOnWhatsappCache, saveOnWhatsappCache } from '@utils/onWhatsappCache';
|
||||
import { status } from '@utils/renderStatus';
|
||||
import { sendTelemetry } from '@utils/sendTelemetry';
|
||||
@@ -569,15 +569,6 @@ export class BaileysStartupService extends ChannelStartupService {
|
||||
const version = baileysVersion.version;
|
||||
const log = `Baileys version: ${version.join('.')}`;
|
||||
|
||||
// if (session.VERSION) {
|
||||
// version = session.VERSION.split('.');
|
||||
// log = `Baileys version env: ${version}`;
|
||||
// } else {
|
||||
// const baileysVersion = await fetchLatestWaWebVersion({});
|
||||
// version = baileysVersion.version;
|
||||
// log = `Baileys version: ${version}`;
|
||||
// }
|
||||
|
||||
this.logger.info(log);
|
||||
|
||||
this.logger.info(`Group Ignore: ${this.localSettings.groupsIgnore}`);
|
||||
@@ -1130,16 +1121,6 @@ export class BaileysStartupService extends ChannelStartupService {
|
||||
}
|
||||
}
|
||||
|
||||
const messageKey = `${this.instance.id}_${received.key.id}`;
|
||||
const cached = await this.baileysCache.get(messageKey);
|
||||
|
||||
if (cached && !editedMessage && !requestId) {
|
||||
this.logger.info(`Message duplicated ignored: ${received.key.id}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
await this.baileysCache.set(messageKey, true, this.MESSAGE_CACHE_TTL_SECONDS);
|
||||
|
||||
if (
|
||||
(type !== 'notify' && type !== 'append') ||
|
||||
editedMessage ||
|
||||
@@ -1442,7 +1423,7 @@ export class BaileysStartupService extends ChannelStartupService {
|
||||
const cached = await this.baileysCache.get(updateKey);
|
||||
|
||||
if (cached) {
|
||||
this.logger.info(`Message duplicated ignored [avoid deadlock]: ${updateKey}`);
|
||||
this.logger.info(`Update Message duplicated ignored [avoid deadlock]: ${updateKey}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,10 +1,6 @@
|
||||
import { InstanceDto } from '@api/dto/instance.dto';
|
||||
import { ChatwootDto } from '@api/integrations/chatbot/chatwoot/dto/chatwoot.dto';
|
||||
import { ChatwootService } from '@api/integrations/chatbot/chatwoot/services/chatwoot.service';
|
||||
import { PrismaRepository } from '@api/repository/repository.service';
|
||||
import { waMonitor } from '@api/server.module';
|
||||
import { CacheService } from '@api/services/cache.service';
|
||||
import { CacheEngine } from '@cache/cacheengine';
|
||||
import { Chatwoot, ConfigService, HttpServer } from '@config/env.config';
|
||||
import { BadRequestException } from '@exceptions';
|
||||
import { isURL } from 'class-validator';
|
||||
@@ -13,7 +9,6 @@ export class ChatwootController {
|
||||
constructor(
|
||||
private readonly chatwootService: ChatwootService,
|
||||
private readonly configService: ConfigService,
|
||||
private readonly prismaRepository: PrismaRepository,
|
||||
) {}
|
||||
|
||||
public async createChatwoot(instance: InstanceDto, data: ChatwootDto) {
|
||||
@@ -84,9 +79,6 @@ export class ChatwootController {
|
||||
public async receiveWebhook(instance: InstanceDto, data: any) {
|
||||
if (!this.configService.get<Chatwoot>('CHATWOOT').ENABLED) throw new BadRequestException('Chatwoot is disabled');
|
||||
|
||||
const chatwootCache = new CacheService(new CacheEngine(this.configService, ChatwootService.name).getEngine());
|
||||
const chatwootService = new ChatwootService(waMonitor, this.configService, this.prismaRepository, chatwootCache);
|
||||
|
||||
return chatwootService.receiveWebhook(instance, data);
|
||||
return this.chatwootService.receiveWebhook(instance, data);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,6 +27,7 @@ import { WAMessageContent, WAMessageKey } from 'baileys';
|
||||
import dayjs from 'dayjs';
|
||||
import FormData from 'form-data';
|
||||
import { Jimp, JimpMime } from 'jimp';
|
||||
import { parsePhoneNumberFromString } from 'libphonenumber-js';
|
||||
import Long from 'long';
|
||||
import mimeTypes from 'mime-types';
|
||||
import path from 'path';
|
||||
@@ -589,7 +590,7 @@ export class ChatwootService {
|
||||
`Identifier needs update: (contact.identifier: ${contact.identifier}, phoneNumber: ${phoneNumber}, body.key.remoteJidAlt: ${remoteJid}`,
|
||||
);
|
||||
const updateContact = await this.updateContact(instance, contact.id, {
|
||||
identifier: remoteJid,
|
||||
identifier: phoneNumber,
|
||||
phone_number: `+${phoneNumber.split('@')[0]}`,
|
||||
});
|
||||
|
||||
@@ -611,13 +612,15 @@ export class ChatwootService {
|
||||
if (await this.cache.has(cacheKey)) {
|
||||
const conversationId = (await this.cache.get(cacheKey)) as number;
|
||||
this.logger.verbose(`Found conversation to: ${phoneNumber}, conversation ID: ${conversationId}`);
|
||||
let conversationExists: conversation | boolean;
|
||||
let conversationExists: any;
|
||||
try {
|
||||
conversationExists = await client.conversations.get({
|
||||
accountId: this.provider.accountId,
|
||||
conversationId: conversationId,
|
||||
});
|
||||
this.logger.verbose(`Conversation exists: ${JSON.stringify(conversationExists)}`);
|
||||
this.logger.verbose(
|
||||
`Conversation exists: ID: ${conversationExists.id} - Name: ${conversationExists.meta.sender.name} - Identifier: ${conversationExists.meta.sender.identifier}`,
|
||||
);
|
||||
} catch (error) {
|
||||
this.logger.error(`Error getting conversation: ${error}`);
|
||||
conversationExists = false;
|
||||
@@ -669,7 +672,7 @@ export class ChatwootService {
|
||||
if (isGroup) {
|
||||
this.logger.verbose(`Processing group conversation`);
|
||||
const group = await this.waMonitor.waInstances[instance.instanceName].client.groupMetadata(chatId);
|
||||
this.logger.verbose(`Group metadata: ${JSON.stringify(group)}`);
|
||||
this.logger.verbose(`Group metadata: JID:${group.JID} - Subject:${group?.subject || group?.Name}`);
|
||||
|
||||
const participantJid = isLid && !body.key.fromMe ? body.key.participantAlt : body.key.participant;
|
||||
nameContact = `${group.subject} (GROUP)`;
|
||||
@@ -680,9 +683,11 @@ export class ChatwootService {
|
||||
this.logger.verbose(`Participant profile picture URL: ${JSON.stringify(picture_url)}`);
|
||||
|
||||
const findParticipant = await this.findContact(instance, participantJid.split('@')[0]);
|
||||
this.logger.verbose(`Found participant: ${JSON.stringify(findParticipant)}`);
|
||||
|
||||
if (findParticipant) {
|
||||
this.logger.verbose(
|
||||
`Found participant: ID:${findParticipant.id} - Name: ${findParticipant.name} - identifier: ${findParticipant.identifier}`,
|
||||
);
|
||||
if (!findParticipant.name || findParticipant.name === chatId) {
|
||||
await this.updateContact(instance, findParticipant.id, {
|
||||
name: body.pushName,
|
||||
@@ -692,7 +697,7 @@ export class ChatwootService {
|
||||
} else {
|
||||
await this.createContact(
|
||||
instance,
|
||||
participantJid.split('@')[0],
|
||||
participantJid.split('@')[0].split(':')[0],
|
||||
filterInbox.id,
|
||||
false,
|
||||
body.pushName,
|
||||
@@ -709,20 +714,13 @@ export class ChatwootService {
|
||||
let contact = await this.findContact(instance, chatId);
|
||||
|
||||
if (contact) {
|
||||
this.logger.verbose(`Found contact: ${JSON.stringify(contact)}`);
|
||||
this.logger.verbose(`Found contact: ID:${contact.id} - Name:${contact.name}`);
|
||||
if (!body.key.fromMe) {
|
||||
const waProfilePictureFile =
|
||||
picture_url?.profilePictureUrl?.split('#')[0].split('?')[0].split('/').pop() || '';
|
||||
const chatwootProfilePictureFile = contact?.thumbnail?.split('#')[0].split('?')[0].split('/').pop() || '';
|
||||
const pictureNeedsUpdate = waProfilePictureFile !== chatwootProfilePictureFile;
|
||||
const nameNeedsUpdate =
|
||||
!contact.name ||
|
||||
contact.name === chatId ||
|
||||
(`+${chatId}`.startsWith('+55')
|
||||
? this.getNumbers(`+${chatId}`).some(
|
||||
(v) => contact.name === v || contact.name === v.substring(3) || contact.name === v.substring(1),
|
||||
)
|
||||
: false);
|
||||
const nameNeedsUpdate = !contact.name || contact.name === chatId;
|
||||
this.logger.verbose(`Picture needs update: ${pictureNeedsUpdate}`);
|
||||
this.logger.verbose(`Name needs update: ${nameNeedsUpdate}`);
|
||||
if (pictureNeedsUpdate || nameNeedsUpdate) {
|
||||
@@ -741,7 +739,7 @@ export class ChatwootService {
|
||||
isGroup,
|
||||
nameContact,
|
||||
picture_url.profilePictureUrl || null,
|
||||
remoteJid,
|
||||
phoneNumber,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -757,7 +755,6 @@ export class ChatwootService {
|
||||
accountId: this.provider.accountId,
|
||||
id: contactId,
|
||||
})) as any;
|
||||
this.logger.verbose(`Contact conversations: ${JSON.stringify(contactConversations)}`);
|
||||
|
||||
if (!contactConversations || !contactConversations.payload) {
|
||||
this.logger.error(`No conversations found or payload is undefined`);
|
||||
@@ -769,7 +766,9 @@ export class ChatwootService {
|
||||
);
|
||||
if (inboxConversation) {
|
||||
if (this.provider.reopenConversation) {
|
||||
this.logger.verbose(`Found conversation in reopenConversation mode: ${JSON.stringify(inboxConversation)}`);
|
||||
this.logger.verbose(
|
||||
`Found conversation in reopenConversation mode: ID: ${inboxConversation.id} - Name: ${inboxConversation.meta.sender.name} - Identifier: ${inboxConversation.meta.sender.identifier}`,
|
||||
);
|
||||
if (inboxConversation && this.provider.conversationPending && inboxConversation.status !== 'open') {
|
||||
await client.conversations.toggleStatus({
|
||||
accountId: this.provider.accountId,
|
||||
@@ -789,7 +788,7 @@ export class ChatwootService {
|
||||
|
||||
if (inboxConversation) {
|
||||
this.logger.verbose(`Returning existing conversation ID: ${inboxConversation.id}`);
|
||||
this.cache.set(cacheKey, inboxConversation.id, 8 * 3600);
|
||||
this.cache.set(cacheKey, inboxConversation.id, 1800);
|
||||
return inboxConversation.id;
|
||||
}
|
||||
}
|
||||
@@ -803,14 +802,6 @@ export class ChatwootService {
|
||||
data['status'] = 'pending';
|
||||
}
|
||||
|
||||
/*
|
||||
Triple check after lock
|
||||
Utilizei uma nova verificação para evitar que outra thread execute entre o terminio do while e o set lock
|
||||
*/
|
||||
if (await this.cache.has(cacheKey)) {
|
||||
return (await this.cache.get(cacheKey)) as number;
|
||||
}
|
||||
|
||||
const conversation = await client.conversations.create({
|
||||
accountId: this.provider.accountId,
|
||||
data,
|
||||
@@ -822,7 +813,7 @@ export class ChatwootService {
|
||||
}
|
||||
|
||||
this.logger.verbose(`New conversation created of ${remoteJid} with ID: ${conversation.id}`);
|
||||
this.cache.set(cacheKey, conversation.id, 8 * 3600);
|
||||
this.cache.set(cacheKey, conversation.id, 1800);
|
||||
return conversation.id;
|
||||
} finally {
|
||||
await this.cache.delete(lockKey);
|
||||
@@ -1392,10 +1383,7 @@ export class ChatwootService {
|
||||
}
|
||||
|
||||
if (body.message_type === 'outgoing' && body?.conversation?.messages?.length && chatId !== '123456') {
|
||||
if (
|
||||
body?.conversation?.messages[0]?.source_id?.substring(0, 5) === 'WAID:' &&
|
||||
body?.conversation?.messages[0]?.id === body?.id
|
||||
) {
|
||||
if (body?.conversation?.messages[0]?.source_id?.substring(0, 5) === 'WAID:') {
|
||||
return { message: 'bot' };
|
||||
}
|
||||
|
||||
@@ -2032,17 +2020,9 @@ export class ChatwootService {
|
||||
const participantName = body.pushName;
|
||||
const rawPhoneNumber =
|
||||
body.key.addressingMode === 'lid' && !body.key.fromMe
|
||||
? body.key.participantAlt.split('@')[0]
|
||||
: body.key.participant.split('@')[0];
|
||||
const phoneMatch = rawPhoneNumber.match(/^(\d{2})(\d{2})(\d{4})(\d{4})$/);
|
||||
|
||||
let formattedPhoneNumber: string;
|
||||
|
||||
if (phoneMatch) {
|
||||
formattedPhoneNumber = `+${phoneMatch[1]} (${phoneMatch[2]}) ${phoneMatch[3]}-${phoneMatch[4]}`;
|
||||
} else {
|
||||
formattedPhoneNumber = `+${rawPhoneNumber}`;
|
||||
}
|
||||
? body.key.participantAlt.split('@')[0].split(':')[0]
|
||||
: body.key.participant.split('@')[0].split(':')[0];
|
||||
const formattedPhoneNumber = parsePhoneNumberFromString(`+${rawPhoneNumber}`).formatInternational();
|
||||
|
||||
let content: string;
|
||||
|
||||
@@ -2178,17 +2158,9 @@ export class ChatwootService {
|
||||
const participantName = body.pushName;
|
||||
const rawPhoneNumber =
|
||||
body.key.addressingMode === 'lid' && !body.key.fromMe
|
||||
? body.key.participantAlt.split('@')[0]
|
||||
: body.key.participant.split('@')[0];
|
||||
const phoneMatch = rawPhoneNumber.match(/^(\d{2})(\d{2})(\d{4})(\d{4})$/);
|
||||
|
||||
let formattedPhoneNumber: string;
|
||||
|
||||
if (phoneMatch) {
|
||||
formattedPhoneNumber = `+${phoneMatch[1]} (${phoneMatch[2]}) ${phoneMatch[3]}-${phoneMatch[4]}`;
|
||||
} else {
|
||||
formattedPhoneNumber = `+${rawPhoneNumber}`;
|
||||
}
|
||||
? body.key.participantAlt.split('@')[0].split(':')[0]
|
||||
: body.key.participant.split('@')[0].split(':')[0];
|
||||
const formattedPhoneNumber = parsePhoneNumberFromString(`+${rawPhoneNumber}`).formatInternational();
|
||||
|
||||
let content: string;
|
||||
|
||||
@@ -2270,8 +2242,21 @@ export class ChatwootService {
|
||||
}
|
||||
|
||||
if (event === 'messages.edit' || event === 'send.message.update') {
|
||||
const editedMessageContent =
|
||||
body?.editedMessage?.conversation || body?.editedMessage?.extendedTextMessage?.text;
|
||||
const editedMessageContentRaw =
|
||||
body?.editedMessage?.conversation ??
|
||||
body?.editedMessage?.extendedTextMessage?.text ??
|
||||
body?.editedMessage?.imageMessage?.caption ??
|
||||
body?.editedMessage?.videoMessage?.caption ??
|
||||
body?.editedMessage?.documentMessage?.caption ??
|
||||
(typeof body?.text === 'string' ? body.text : undefined);
|
||||
|
||||
const editedMessageContent = (editedMessageContentRaw ?? '').trim();
|
||||
|
||||
if (!editedMessageContent) {
|
||||
this.logger.info('[CW.EDIT] Conteúdo vazio — ignorando (DELETE tratará se for revoke).');
|
||||
return;
|
||||
}
|
||||
|
||||
const message = await this.getMessageByKeyId(instance, body?.key?.id);
|
||||
|
||||
if (!message) {
|
||||
|
||||
Reference in New Issue
Block a user