Skip to content

Commit

Permalink
Merge branch 'release/2.2.3'
Browse files Browse the repository at this point in the history
  • Loading branch information
DavidsonGomes committed Feb 3, 2025
2 parents db9cdbf + da74611 commit 427c994
Show file tree
Hide file tree
Showing 7 changed files with 83 additions and 79 deletions.
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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)

### Features
Expand Down
2 changes: 1 addition & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ FROM node:20-alpine AS builder
RUN apk update && \
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 contact="[email protected]"

Expand Down
8 changes: 4 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "evolution-api",
"version": "2.2.2",
"version": "2.2.3",
"description": "Rest api for communication with WhatsApp",
"main": "./dist/main.js",
"type": "commonjs",
Expand Down
17 changes: 12 additions & 5 deletions src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2163,6 +2163,7 @@ export class BaileysStartupService extends ChannelStartupService {
const cache = this.configService.get<CacheConf>('CACHE');
if (!cache.REDIS.ENABLED && !cache.LOCAL.ENABLED) group = await this.findGroup({ groupJid: sender }, 'inner');
else group = await this.getGroupMetadataCache(sender);
// group = await this.findGroup({ groupJid: sender }, 'inner');
} catch (error) {
throw new NotFoundException('Group not found');
}
Expand Down Expand Up @@ -3551,25 +3552,31 @@ export class BaileysStartupService extends ChannelStartupService {
const messageId = response.message?.protocolMessage?.key?.id;
if (messageId) {
const isLogicalDeleted = configService.get<Database>('DATABASE').DELETE_DATA.LOGICAL_MESSAGE_DELETE;
let message = await this.prismaRepository.message.findUnique({
where: { id: messageId },
let message = await this.prismaRepository.message.findFirst({
where: {
key: {
path: ['id'],
equals: messageId,
},
},
});
if (isLogicalDeleted) {
if (!message) return response;
const existingKey = typeof message?.key === 'object' && message.key !== null ? message.key : {};
message = await this.prismaRepository.message.update({
where: { id: messageId },
where: { id: message.id },
data: {
key: {
...existingKey,
deleted: true,
},
status: 'DELETED',
},
});
} else {
await this.prismaRepository.message.deleteMany({
where: {
id: messageId,
id: message.id,
},
});
}
Expand All @@ -3578,7 +3585,7 @@ export class BaileysStartupService extends ChannelStartupService {
instanceId: message.instanceId,
key: message.key,
messageType: message.messageType,
status: message.status,
status: 'DELETED',
source: message.source,
messageTimestamp: message.messageTimestamp,
pushName: message.pushName,
Expand Down
66 changes: 23 additions & 43 deletions src/api/integrations/chatbot/dify/services/dify.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -224,63 +224,43 @@ export class DifyService {
headers: {
Authorization: `Bearer ${dify.apiKey}`,
},
responseType: 'stream',
});

let conversationId;
let answer = '';

const stream = response.data;
const reader = new Readable().wrap(stream);
const data = response.data.replaceAll('data: ', '');

reader.on('data', (chunk) => {
const data = chunk.toString().replace(/data:\s*/g, '');
const events = data.split('\n').filter((line) => line.trim() !== '');

if (data.trim() === '' || !data.startsWith('{')) {
return;
}

try {
const events = data.split('\n').filter((line) => line.trim() !== '');
for (const eventString of events) {
if (eventString.trim().startsWith('{')) {
const event = JSON.parse(eventString);

for (const eventString of events) {
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;
}
}
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)
await instance.client.sendPresenceUpdate('paused', remoteJid);
}

const message = answer;
if (instance.integration === Integration.WHATSAPP_BAILEYS)
await instance.client.sendPresenceUpdate('paused', remoteJid);

await this.sendMessageWhatsApp(instance, remoteJid, message, settings);
const message = answer;

await this.prismaRepository.integrationSession.update({
where: {
id: session.id,
},
data: {
status: 'opened',
awaitUser: true,
sessionId: conversationId,
},
});
});
await this.sendMessageWhatsApp(instance, remoteJid, message, settings);

reader.on('error', (error) => {
console.error('Error reading stream:', error);
await this.prismaRepository.integrationSession.update({
where: {
id: session.id,
},
data: {
status: 'opened',
awaitUser: true,
sessionId: conversationId,
},
});

return;
Expand Down
60 changes: 35 additions & 25 deletions src/utils/use-multi-file-auth-state-prisma.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,14 @@ import { AuthenticationState, BufferJSON, initAuthCreds, WAProto as proto } from
import fs from 'fs/promises';
import path from 'path';

// const fixFileName = (file: string): string | undefined => {
// if (!file) {
// return undefined;
// }
// const replacedSlash = file.replace(/\//g, '__');
// const replacedColon = replacedSlash.replace(/:/g, '-');
// return replacedColon;
// };
const fixFileName = (file: string): string | undefined => {
if (!file) {
return undefined;
}
const replacedSlash = file.replace(/\//g, '__');
const replacedColon = replacedSlash.replace(/:/g, '-');
return replacedColon;
};

export async function keyExists(sessionId: string): Promise<any> {
try {
Expand Down Expand Up @@ -63,14 +63,14 @@ async function deleteAuthKey(sessionId: string): Promise<any> {
}
}

// async function fileExists(file: string): Promise<any> {
// try {
// const stat = await fs.stat(file);
// if (stat.isFile()) return true;
// } catch (error) {
// return;
// }
// }
async function fileExists(file: string): Promise<any> {
try {
const stat = await fs.stat(file);
if (stat.isFile()) return true;
} catch (error) {
return;
}
}

export default async function useMultiFileAuthStatePrisma(
sessionId: string,
Expand All @@ -80,16 +80,19 @@ export default async function useMultiFileAuthStatePrisma(
saveCreds: () => Promise<void>;
}> {
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 });

async function writeData(data: any, key: string): Promise<any> {
const dataString = JSON.stringify(data, BufferJSON.replacer);

if (key != 'creds') {
return await cache.hSet(sessionId, key, data);
// await fs.writeFile(localFile(key), dataString);
// return;
if (process.env.CACHE_REDIS_ENABLED === 'true') {
return await cache.hSet(sessionId, key, data);
} else {
await fs.writeFile(localFile(key), dataString);
return;
}
}
await saveKey(sessionId, dataString);
return;
Expand All @@ -100,9 +103,13 @@ export default async function useMultiFileAuthStatePrisma(
let rawData;

if (key != 'creds') {
return await cache.hGet(sessionId, key);
// if (!(await fileExists(localFile(key)))) return null;
// rawData = await fs.readFile(localFile(key), { encoding: 'utf-8' });
if (process.env.CACHE_REDIS_ENABLED === 'true') {
return await cache.hGet(sessionId, key);
} else {
if (!(await fileExists(localFile(key)))) return null;
rawData = await fs.readFile(localFile(key), { encoding: 'utf-8' });
return JSON.parse(rawData, BufferJSON.reviver);
}
} else {
rawData = await getAuthKey(sessionId);
}
Expand All @@ -117,8 +124,11 @@ export default async function useMultiFileAuthStatePrisma(
async function removeData(key: string): Promise<any> {
try {
if (key != 'creds') {
return await cache.hDelete(sessionId, key);
// await fs.unlink(localFile(key));
if (process.env.CACHE_REDIS_ENABLED === 'true') {
return await cache.hDelete(sessionId, key);
} else {
await fs.unlink(localFile(key));
}
} else {
await deleteAuthKey(sessionId);
}
Expand Down

0 comments on commit 427c994

Please sign in to comment.