Skip to content

Commit

Permalink
Merge pull request #140 from vilsonei/main
Browse files Browse the repository at this point in the history
Correções sobre as conexões das instâncias com o WhatsApp
  • Loading branch information
jrCleber authored Jul 4, 2024
2 parents f9425bf + 180a281 commit 738dedc
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 26 deletions.
6 changes: 3 additions & 3 deletions src/config/env.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -191,9 +191,9 @@ export class ConfigService {
LEVEL: process.env?.LOG_LEVEL.split('|') as LogLevel[],
COLOR: process.env?.LOG_COLOR === 'true',
},
INSTANCE_EXPIRATION_TIME: isBooleanString(process.env?.DEL_INSTANCE)
? process.env.DEL_INSTANCE === 'true'
: Number.parseInt(process.env?.DEL_INSTANCE || '5'),
INSTANCE_EXPIRATION_TIME: process.env?.INSTANCE_EXPIRATION_TIME === 'false'
? false
: Number.parseInt(process.env?.INSTANCE_EXPIRATION_TIME || '5'),
GLOBAL_WEBHOOK: {
URL: process.env?.WEBHOOK_GLOBAL_URL,
ENABLED: process.env?.WEBHOOK_GLOBAL_ENABLED === 'true',
Expand Down
5 changes: 1 addition & 4 deletions src/whatsapp/controllers/instance.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,10 +125,7 @@ export class InstanceController {
this.providerFiles,
);
await instance.setInstanceName(instanceName);
this.waMonitor.waInstances.set(instance.instanceName, instance);
this.waMonitor.delInstanceTime(instance.instanceName);

this.waMonitor.waInstances.set(instanceName, instance);
this.waMonitor.addInstance(instanceName, instance);
}

const state = instance?.connectionStatus?.state;
Expand Down
67 changes: 48 additions & 19 deletions src/whatsapp/services/monitor.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,27 +75,41 @@ export class WAMonitoringService {
this.configService.get<ProviderSession>('PROVIDER'),
);

private readonly instanceDelTimeout = {};

public addInstance(instanceName: string, instance: WAStartupService) {
const currentInstance = this.waInstances.get(instanceName);
if (currentInstance) {
this.clearListeners(instanceName);
}
this.waInstances.set(instanceName, instance);
this.delInstanceTime(instanceName);
}

public delInstanceTime(instance: string) {
const time = this.configService.get<InstanceExpirationTime>(
'INSTANCE_EXPIRATION_TIME',
);
if (typeof time === 'number' && time > 0) {
setTimeout(
if (this.instanceDelTimeout[instance]) {
clearTimeout(this.instanceDelTimeout[instance]);
}

this.instanceDelTimeout[instance] = setTimeout(
() => {
const ref = this.waInstances.get(instance);
if (ref?.connectionStatus?.state !== 'open') {
this.waInstances.delete(instance);
}
delete this.instanceDelTimeout[instance];
},
1000 * 60 * time,
);
}
}

private async cleaningUp({ name }: Instance) {
this.waInstances.get(name)?.client?.ev.removeAllListeners('connection.update');
this.waInstances.get(name)?.client?.ev.flush();
this.waInstances.delete(name);
this.clearListeners(name);
if (this.providerSession?.ENABLED) {
await this.providerFiles.removeSession(name);
} else {
Expand All @@ -110,6 +124,16 @@ export class WAMonitoringService {
});
}

private clearListeners(instanceName: string) {
try {
this.waInstances.get(instanceName)?.client?.ev.removeAllListeners('connection.update');
this.waInstances.get(instanceName)?.client?.ev.flush();
this.waInstances.delete(instanceName);
} catch {
this.logger.error(`Error clearing ${instanceName} instance listeners`);
}
}

public async loadInstance() {
const set = async (name: string) => {
const instance = await this.repository.instance.findUnique({
Expand All @@ -125,8 +149,8 @@ export class WAMonitoringService {
this.providerFiles,
);
await init.setInstanceName(name);
this.addInstance(init.instanceName, init);
await init.connectToWhatsapp();
this.waInstances.set(name, init);
};

try {
Expand Down Expand Up @@ -185,21 +209,26 @@ export class WAMonitoringService {

private noConnection() {
this.eventEmitter.on('no.connection', async (instance: Instance) => {
const del = this.configService.get<InstanceExpirationTime>(
'INSTANCE_EXPIRATION_TIME',
);
if (del) {
try {
this.cleaningUp(instance);
} catch (error) {
this.logger.error({
localError: 'noConnection',
warn: 'Error deleting instance from memory.',
error,
});
} finally {
this.logger.warn(`Instance "${instance.name}" - NOT CONNECTION`);
const waInstance = this.waInstances.get(instance.name);
if (waInstance?.connectionStatus?.state !== 'open') {
const del = this.configService.get<InstanceExpirationTime>(
'INSTANCE_EXPIRATION_TIME',
);
if (del) {
try {
this.cleaningUp(instance);
} catch (error) {
this.logger.error({
localError: 'noConnection',
warn: 'Error deleting instance from memory.',
error,
});
} finally {
this.logger.warn(`Instance "${instance.name}" - NOT CONNECTION`);
}
}
} else {
this.logger.info(`Instance ${waInstance.instanceName} already connected!`);
}
});
}
Expand Down

0 comments on commit 738dedc

Please sign in to comment.