fix: Solved problem when disconnecting from the instance the instance was deleted

This commit is contained in:
Davidson Gomes 2023-07-29 11:09:56 -03:00
parent f89c2b1f63
commit fe2b9774d8
7 changed files with 29 additions and 96 deletions

View File

@ -1,3 +1,13 @@
# 1.5.0 (homolog)
### Fixed
* Solved problem when disconnecting from the instance the instance was deleted
### Integrations
- Chatwoot: v2.18.0 - v3.0.0
# 1.4.8 (2023-07-27 10:27) # 1.4.8 (2023-07-27 10:27)
### Fixed ### Fixed

View File

@ -1,6 +1,6 @@
{ {
"name": "evolution-api", "name": "evolution-api",
"version": "1.4.8", "version": "1.5.0",
"description": "Rest api for communication with WhatsApp", "description": "Rest api for communication with WhatsApp",
"main": "./dist/src/main.js", "main": "./dist/src/main.js",
"scripts": { "scripts": {

View File

@ -90,10 +90,4 @@ export class ChatwootController {
return chatwootService.receiveWebhook(instance, data); return chatwootService.receiveWebhook(instance, data);
} }
public async newInstance(data: any) {
const chatwootService = new ChatwootService(waMonitor, this.configService);
return chatwootService.newInstance(data);
}
} }

View File

@ -187,7 +187,7 @@ export class InstanceController {
this.chatwootService.initInstanceChatwoot( this.chatwootService.initInstanceChatwoot(
instance, instance,
instance.instanceName, instance.instanceName.split('-cwId-')[0],
`${urlServer}/chatwoot/webhook/${instance.instanceName}`, `${urlServer}/chatwoot/webhook/${instance.instanceName}`,
qrcode, qrcode,
number, number,
@ -234,6 +234,10 @@ export class InstanceController {
this.logger.verbose('state: ' + state); this.logger.verbose('state: ' + state);
if (!state) {
throw new BadRequestException('The "' + instanceName + '" instance does not exist');
}
if (state == 'open') { if (state == 'open') {
return await this.connectionState({ instanceName }); return await this.connectionState({ instanceName });
} }

View File

@ -5,7 +5,7 @@ import { createReadStream, readFileSync, unlinkSync, writeFileSync } from 'fs';
import mimeTypes from 'mime-types'; import mimeTypes from 'mime-types';
import path from 'path'; import path from 'path';
import { ConfigService, HttpServer } from '../../config/env.config'; import { ConfigService } from '../../config/env.config';
import { Logger } from '../../config/logger.config'; import { Logger } from '../../config/logger.config';
import { ROOT_DIR } from '../../config/path.config'; import { ROOT_DIR } from '../../config/path.config';
import { ChatwootDto } from '../dto/chatwoot.dto'; import { ChatwootDto } from '../dto/chatwoot.dto';
@ -578,7 +578,7 @@ export class ChatwootService {
} }
this.logger.verbose('find inbox by name'); this.logger.verbose('find inbox by name');
const findByName = inbox.payload.find((inbox) => inbox.name === instance.instanceName); const findByName = inbox.payload.find((inbox) => inbox.name === instance.instanceName.split('-cwId-')[0]);
if (!findByName) { if (!findByName) {
this.logger.warn('inbox not found'); this.logger.warn('inbox not found');
@ -996,39 +996,6 @@ export class ChatwootService {
await waInstance?.client?.logout('Log out instance: ' + instance.instanceName); await waInstance?.client?.logout('Log out instance: ' + instance.instanceName);
await waInstance?.client?.ws?.close(); await waInstance?.client?.ws?.close();
} }
if (command.includes('new_instance')) {
const urlServer = this.configService.get<HttpServer>('SERVER').URL;
const apiKey = this.configService.get('AUTHENTICATION').API_KEY.KEY;
const data = {
instanceName: command.split(':')[1],
qrcode: true,
chatwoot_account_id: this.provider.account_id,
chatwoot_token: this.provider.token,
chatwoot_url: this.provider.url,
chatwoot_sign_msg: this.provider.sign_msg,
chatwoot_reopen_conversation: this.provider.reopen_conversation,
chatwoot_conversation_pending: this.provider.conversation_pending,
};
if (command.split(':')[2]) {
data['number'] = command.split(':')[2];
}
const config = {
method: 'post',
maxBodyLength: Infinity,
url: `${urlServer}/instance/create`,
headers: {
'Content-Type': 'application/json',
apikey: apiKey,
},
data: data,
};
await axios.request(config);
}
} }
if (body.message_type === 'outgoing' && body?.conversation?.messages?.length && chatId !== '123456') { if (body.message_type === 'outgoing' && body?.conversation?.messages?.length && chatId !== '123456') {
@ -1342,7 +1309,7 @@ export class ChatwootService {
if (!body.key.fromMe) { if (!body.key.fromMe) {
this.logger.verbose('message is not from me'); this.logger.verbose('message is not from me');
content = `**${participantName}**\n\n${bodyMessage}`; content = `**${participantName}:**\n\n${bodyMessage}`;
} else { } else {
this.logger.verbose('message is from me'); this.logger.verbose('message is from me');
content = `${bodyMessage}`; content = `${bodyMessage}`;
@ -1515,50 +1482,4 @@ export class ChatwootService {
this.logger.error(error); this.logger.error(error);
} }
} }
public async newInstance(data: any) {
try {
const instanceName = data.instanceName;
const qrcode = true;
const number = data.number;
const accountId = data.accountId;
const chatwootToken = data.token;
const chatwootUrl = data.url;
const signMsg = true;
const urlServer = this.configService.get<HttpServer>('SERVER').URL;
const apiKey = this.configService.get('AUTHENTICATION').API_KEY.KEY;
const requestData = {
instanceName,
qrcode,
chatwoot_account_id: accountId,
chatwoot_token: chatwootToken,
chatwoot_url: chatwootUrl,
chatwoot_sign_msg: signMsg,
};
if (number) {
requestData['number'] = number;
}
// eslint-disable-next-line
const config = {
method: 'post',
maxBodyLength: Infinity,
url: `${urlServer}/instance/create`,
headers: {
'Content-Type': 'application/json',
apikey: apiKey,
},
data: requestData,
};
// await axios.request(config);
return true;
} catch (error) {
this.logger.error(error);
return null;
}
}
} }

View File

@ -335,11 +335,14 @@ export class WAMonitoringService {
this.logger.verbose('checking instances without connection'); this.logger.verbose('checking instances without connection');
this.eventEmitter.on('no.connection', async (instanceName) => { this.eventEmitter.on('no.connection', async (instanceName) => {
try { try {
this.logger.verbose('instance: ' + instanceName + ' - removing from memory'); this.logger.verbose('logging out instance: ' + instanceName);
this.waInstances[instanceName] = undefined; await this.waInstances[instanceName]?.client?.logout('Log out instance: ' + instanceName);
this.logger.verbose('request cleaning up instance: ' + instanceName); this.logger.verbose('close connection instance: ' + instanceName);
this.cleaningUp(instanceName); this.waInstances[instanceName]?.client?.ws?.close();
this.waInstances[instanceName].instance.qrcode = { count: 0 };
this.waInstances[instanceName].stateConnection.state = 'close';
} catch (error) { } catch (error) {
this.logger.error({ this.logger.error({
localError: 'noConnection', localError: 'noConnection',

View File

@ -135,12 +135,12 @@ export class WAStartupService {
} }
private readonly logger = new Logger(WAStartupService.name); private readonly logger = new Logger(WAStartupService.name);
private readonly instance: wa.Instance = {}; public readonly instance: wa.Instance = {};
public client: WASocket; public client: WASocket;
private readonly localWebhook: wa.LocalWebHook = {}; private readonly localWebhook: wa.LocalWebHook = {};
private readonly localChatwoot: wa.LocalChatwoot = {}; private readonly localChatwoot: wa.LocalChatwoot = {};
private readonly localSettings: wa.LocalSettings = {}; private readonly localSettings: wa.LocalSettings = {};
private stateConnection: wa.StateConnection = { state: 'close' }; public stateConnection: wa.StateConnection = { state: 'close' };
public readonly storePath = join(ROOT_DIR, 'store'); public readonly storePath = join(ROOT_DIR, 'store');
private readonly msgRetryCounterCache: CacheStore = new NodeCache(); private readonly msgRetryCounterCache: CacheStore = new NodeCache();
private readonly userDevicesCache: CacheStore = new NodeCache(); private readonly userDevicesCache: CacheStore = new NodeCache();
@ -558,6 +558,7 @@ export class WAStartupService {
this.logger.verbose('Connection update'); this.logger.verbose('Connection update');
if (qr) { if (qr) {
this.logger.verbose('QR code found'); this.logger.verbose('QR code found');
console.log('this.instance.qrcode', this.instance.qrcode);
if (this.instance.qrcode.count === this.configService.get<QrCode>('QRCODE').LIMIT) { if (this.instance.qrcode.count === this.configService.get<QrCode>('QRCODE').LIMIT) {
this.logger.verbose('QR code limit reached'); this.logger.verbose('QR code limit reached');