Merge branch 'release/2.2.3'

This commit is contained in:
Davidson Gomes 2025-02-03 11:52:49 -03:00
commit 427c994993
7 changed files with 83 additions and 79 deletions

View File

@ -1,3 +1,10 @@
# 2.2.3 (2025-02-03 11:52)
### Fixed
* Fix cache in local file system
* Update Baileys Version
# 2.2.2 (2025-01-31 06:55) # 2.2.2 (2025-01-31 06:55)
### Features ### Features

View File

@ -3,7 +3,7 @@ FROM node:20-alpine AS builder
RUN apk update && \ RUN apk update && \
apk add git ffmpeg wget curl bash openssl apk add git ffmpeg wget curl bash openssl
LABEL version="2.2.2" description="Api to control whatsapp features through http requests." LABEL version="2.2.3" description="Api to control whatsapp features through http requests."
LABEL maintainer="Davidson Gomes" git="https://github.com/DavidsonGomes" LABEL maintainer="Davidson Gomes" git="https://github.com/DavidsonGomes"
LABEL contact="contato@atendai.com" LABEL contact="contato@atendai.com"

8
package-lock.json generated
View File

@ -1,12 +1,12 @@
{ {
"name": "evolution-api", "name": "evolution-api",
"version": "2.2.2", "version": "2.2.3",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "evolution-api", "name": "evolution-api",
"version": "2.2.2", "version": "2.2.3",
"license": "Apache-2.0", "license": "Apache-2.0",
"dependencies": { "dependencies": {
"@adiwajshing/keyed-db": "^0.2.4", "@adiwajshing/keyed-db": "^0.2.4",
@ -4752,8 +4752,8 @@
"integrity": "sha512-OnAYlL5b7LEkALw87fUVafQw5rVR9RjwGd4KUwNQ6DrrNmaVaUCgLipfVlzrPQ4tWOR9P0IXGNOx50jYCCdSJg==" "integrity": "sha512-OnAYlL5b7LEkALw87fUVafQw5rVR9RjwGd4KUwNQ6DrrNmaVaUCgLipfVlzrPQ4tWOR9P0IXGNOx50jYCCdSJg=="
}, },
"node_modules/baileys": { "node_modules/baileys": {
"version": "6.7.9", "version": "6.7.12",
"resolved": "git+ssh://git@github.com/EvolutionAPI/Baileys.git#2140e16a9214067bf4cd408e88c231c24636a9e9", "resolved": "git+ssh://git@github.com/EvolutionAPI/Baileys.git#2c69f65d4b6c4e779d6e3d2c0c32689a5425df95",
"dependencies": { "dependencies": {
"@adiwajshing/keyed-db": "^0.2.4", "@adiwajshing/keyed-db": "^0.2.4",
"@hapi/boom": "^9.1.3", "@hapi/boom": "^9.1.3",

View File

@ -1,6 +1,6 @@
{ {
"name": "evolution-api", "name": "evolution-api",
"version": "2.2.2", "version": "2.2.3",
"description": "Rest api for communication with WhatsApp", "description": "Rest api for communication with WhatsApp",
"main": "./dist/main.js", "main": "./dist/main.js",
"type": "commonjs", "type": "commonjs",

View File

@ -2163,6 +2163,7 @@ export class BaileysStartupService extends ChannelStartupService {
const cache = this.configService.get<CacheConf>('CACHE'); const cache = this.configService.get<CacheConf>('CACHE');
if (!cache.REDIS.ENABLED && !cache.LOCAL.ENABLED) group = await this.findGroup({ groupJid: sender }, 'inner'); if (!cache.REDIS.ENABLED && !cache.LOCAL.ENABLED) group = await this.findGroup({ groupJid: sender }, 'inner');
else group = await this.getGroupMetadataCache(sender); else group = await this.getGroupMetadataCache(sender);
// group = await this.findGroup({ groupJid: sender }, 'inner');
} catch (error) { } catch (error) {
throw new NotFoundException('Group not found'); throw new NotFoundException('Group not found');
} }
@ -3551,25 +3552,31 @@ export class BaileysStartupService extends ChannelStartupService {
const messageId = response.message?.protocolMessage?.key?.id; const messageId = response.message?.protocolMessage?.key?.id;
if (messageId) { if (messageId) {
const isLogicalDeleted = configService.get<Database>('DATABASE').DELETE_DATA.LOGICAL_MESSAGE_DELETE; const isLogicalDeleted = configService.get<Database>('DATABASE').DELETE_DATA.LOGICAL_MESSAGE_DELETE;
let message = await this.prismaRepository.message.findUnique({ let message = await this.prismaRepository.message.findFirst({
where: { id: messageId }, where: {
key: {
path: ['id'],
equals: messageId,
},
},
}); });
if (isLogicalDeleted) { if (isLogicalDeleted) {
if (!message) return response; if (!message) return response;
const existingKey = typeof message?.key === 'object' && message.key !== null ? message.key : {}; const existingKey = typeof message?.key === 'object' && message.key !== null ? message.key : {};
message = await this.prismaRepository.message.update({ message = await this.prismaRepository.message.update({
where: { id: messageId }, where: { id: message.id },
data: { data: {
key: { key: {
...existingKey, ...existingKey,
deleted: true, deleted: true,
}, },
status: 'DELETED',
}, },
}); });
} else { } else {
await this.prismaRepository.message.deleteMany({ await this.prismaRepository.message.deleteMany({
where: { where: {
id: messageId, id: message.id,
}, },
}); });
} }
@ -3578,7 +3585,7 @@ export class BaileysStartupService extends ChannelStartupService {
instanceId: message.instanceId, instanceId: message.instanceId,
key: message.key, key: message.key,
messageType: message.messageType, messageType: message.messageType,
status: message.status, status: 'DELETED',
source: message.source, source: message.source,
messageTimestamp: message.messageTimestamp, messageTimestamp: message.messageTimestamp,
pushName: message.pushName, pushName: message.pushName,

View File

@ -224,63 +224,43 @@ export class DifyService {
headers: { headers: {
Authorization: `Bearer ${dify.apiKey}`, Authorization: `Bearer ${dify.apiKey}`,
}, },
responseType: 'stream',
}); });
let conversationId; let conversationId;
let answer = ''; let answer = '';
const stream = response.data; const data = response.data.replaceAll('data: ', '');
const reader = new Readable().wrap(stream);
reader.on('data', (chunk) => { const events = data.split('\n').filter((line) => line.trim() !== '');
const data = chunk.toString().replace(/data:\s*/g, '');
if (data.trim() === '' || !data.startsWith('{')) { for (const eventString of events) {
return; if (eventString.trim().startsWith('{')) {
} const event = JSON.parse(eventString);
try { if (event?.event === 'agent_message') {
const events = data.split('\n').filter((line) => line.trim() !== ''); console.log('event:', event);
conversationId = conversationId ?? event?.conversation_id;
for (const eventString of events) { answer += event?.answer;
if (eventString.trim().startsWith('{')) {
const event = JSON.parse(eventString);
if (event?.event === 'agent_message') {
console.log('event:', event);
conversationId = conversationId ?? event?.conversation_id;
answer += event?.answer;
}
}
} }
} catch (error) {
console.error('Error parsing stream data:', error);
} }
}); }
reader.on('end', async () => { if (instance.integration === Integration.WHATSAPP_BAILEYS)
if (instance.integration === Integration.WHATSAPP_BAILEYS) await instance.client.sendPresenceUpdate('paused', remoteJid);
await instance.client.sendPresenceUpdate('paused', remoteJid);
const message = answer; const message = answer;
await this.sendMessageWhatsApp(instance, remoteJid, message, settings); await this.sendMessageWhatsApp(instance, remoteJid, message, settings);
await this.prismaRepository.integrationSession.update({ await this.prismaRepository.integrationSession.update({
where: { where: {
id: session.id, id: session.id,
}, },
data: { data: {
status: 'opened', status: 'opened',
awaitUser: true, awaitUser: true,
sessionId: conversationId, sessionId: conversationId,
}, },
});
});
reader.on('error', (error) => {
console.error('Error reading stream:', error);
}); });
return; return;

View File

@ -5,14 +5,14 @@ import { AuthenticationState, BufferJSON, initAuthCreds, WAProto as proto } from
import fs from 'fs/promises'; import fs from 'fs/promises';
import path from 'path'; import path from 'path';
// const fixFileName = (file: string): string | undefined => { const fixFileName = (file: string): string | undefined => {
// if (!file) { if (!file) {
// return undefined; return undefined;
// } }
// const replacedSlash = file.replace(/\//g, '__'); const replacedSlash = file.replace(/\//g, '__');
// const replacedColon = replacedSlash.replace(/:/g, '-'); const replacedColon = replacedSlash.replace(/:/g, '-');
// return replacedColon; return replacedColon;
// }; };
export async function keyExists(sessionId: string): Promise<any> { export async function keyExists(sessionId: string): Promise<any> {
try { try {
@ -63,14 +63,14 @@ async function deleteAuthKey(sessionId: string): Promise<any> {
} }
} }
// async function fileExists(file: string): Promise<any> { async function fileExists(file: string): Promise<any> {
// try { try {
// const stat = await fs.stat(file); const stat = await fs.stat(file);
// if (stat.isFile()) return true; if (stat.isFile()) return true;
// } catch (error) { } catch (error) {
// return; return;
// } }
// } }
export default async function useMultiFileAuthStatePrisma( export default async function useMultiFileAuthStatePrisma(
sessionId: string, sessionId: string,
@ -80,16 +80,19 @@ export default async function useMultiFileAuthStatePrisma(
saveCreds: () => Promise<void>; saveCreds: () => Promise<void>;
}> { }> {
const localFolder = path.join(INSTANCE_DIR, sessionId); const localFolder = path.join(INSTANCE_DIR, sessionId);
// const localFile = (key: string) => path.join(localFolder, fixFileName(key) + '.json'); const localFile = (key: string) => path.join(localFolder, fixFileName(key) + '.json');
await fs.mkdir(localFolder, { recursive: true }); await fs.mkdir(localFolder, { recursive: true });
async function writeData(data: any, key: string): Promise<any> { async function writeData(data: any, key: string): Promise<any> {
const dataString = JSON.stringify(data, BufferJSON.replacer); const dataString = JSON.stringify(data, BufferJSON.replacer);
if (key != 'creds') { if (key != 'creds') {
return await cache.hSet(sessionId, key, data); if (process.env.CACHE_REDIS_ENABLED === 'true') {
// await fs.writeFile(localFile(key), dataString); return await cache.hSet(sessionId, key, data);
// return; } else {
await fs.writeFile(localFile(key), dataString);
return;
}
} }
await saveKey(sessionId, dataString); await saveKey(sessionId, dataString);
return; return;
@ -100,9 +103,13 @@ export default async function useMultiFileAuthStatePrisma(
let rawData; let rawData;
if (key != 'creds') { if (key != 'creds') {
return await cache.hGet(sessionId, key); if (process.env.CACHE_REDIS_ENABLED === 'true') {
// if (!(await fileExists(localFile(key)))) return null; return await cache.hGet(sessionId, key);
// rawData = await fs.readFile(localFile(key), { encoding: 'utf-8' }); } else {
if (!(await fileExists(localFile(key)))) return null;
rawData = await fs.readFile(localFile(key), { encoding: 'utf-8' });
return JSON.parse(rawData, BufferJSON.reviver);
}
} else { } else {
rawData = await getAuthKey(sessionId); rawData = await getAuthKey(sessionId);
} }
@ -117,8 +124,11 @@ export default async function useMultiFileAuthStatePrisma(
async function removeData(key: string): Promise<any> { async function removeData(key: string): Promise<any> {
try { try {
if (key != 'creds') { if (key != 'creds') {
return await cache.hDelete(sessionId, key); if (process.env.CACHE_REDIS_ENABLED === 'true') {
// await fs.unlink(localFile(key)); return await cache.hDelete(sessionId, key);
} else {
await fs.unlink(localFile(key));
}
} else { } else {
await deleteAuthKey(sessionId); await deleteAuthKey(sessionId);
} }