fix: fix problems in create instance and delete instance files

This commit is contained in:
Davidson Gomes 2023-06-28 13:42:35 -03:00
parent e0bd06489f
commit 1017010e15
17 changed files with 84 additions and 18 deletions

View File

@ -8,6 +8,9 @@
### Fixed
* Adjust dockerfile variables
* Fixed baileys version in package.json
* Fixed problem that did not validate if the token passed in create instance already existed
* Fixed problem that does not delete instance files in server mode
# 1.1.0 (2023-06-21 11:17)

View File

@ -41,7 +41,7 @@
"homepage": "https://github.com/DavidsonGomes/evolution-api#readme",
"dependencies": {
"@adiwajshing/keyed-db": "^0.2.4",
"@evolution/base": "github:WhiskeySockets/Baileys",
"@whiskeysockets/baileys": "^6.3.0",
"@ffmpeg-installer/ffmpeg": "^1.1.0",
"@hapi/boom": "^10.0.1",
"axios": "^1.3.5",

View File

@ -1,6 +1,6 @@
import { createClient, RedisClientType } from '@redis/client';
import { Logger } from '../config/logger.config';
import { BufferJSON } from '@evolution/base';
import { BufferJSON } from '@whiskeysockets/baileys';
import { Redis } from '../config/env.config';
export class RedisCache {

View File

@ -5,7 +5,7 @@ import {
initAuthCreds,
proto,
SignalDataTypeMap,
} from '@evolution/base';
} from '@whiskeysockets/baileys';
import { configService, Database } from '../config/env.config';
import { Logger } from '../config/logger.config';
import { dbserver } from '../db/db.connect';

View File

@ -4,7 +4,7 @@ import {
initAuthCreds,
proto,
SignalDataTypeMap,
} from '@evolution/base';
} from '@whiskeysockets/baileys';
import { RedisCache } from '../db/redis.client';
import { Logger } from '../config/logger.config';
import { Redis } from '../config/env.config';

View File

@ -1,4 +1,4 @@
import { proto } from '@evolution/base';
import { proto } from '@whiskeysockets/baileys';
import {
ArchiveChatDto,
DeleteMessage,

View File

@ -1,4 +1,4 @@
import { delay } from '@evolution/base';
import { delay } from '@whiskeysockets/baileys';
import EventEmitter2 from 'eventemitter2';
import { Auth, ConfigService } from '../../config/env.config';
import { BadRequestException, InternalServerErrorException } from '../../exceptions';
@ -41,6 +41,8 @@ export class InstanceController {
]);
}
await this.authService.checkDuplicateToken(token);
const instance = new WAStartupService(
this.configService,
this.eventEmitter,
@ -84,6 +86,8 @@ export class InstanceController {
events: getEvents,
};
} else {
await this.authService.checkDuplicateToken(token);
const instance = new WAStartupService(
this.configService,
this.eventEmitter,
@ -159,6 +163,26 @@ export class InstanceController {
}
}
public async restartInstance({ instanceName }: InstanceDto) {
try {
delete this.waMonitor.waInstances[instanceName];
console.log(this.waMonitor.waInstances[instanceName]);
const instance = new WAStartupService(
this.configService,
this.eventEmitter,
this.repository,
);
instance.instanceName = instanceName;
await instance.connectToWhatsapp();
this.waMonitor.waInstances[instance.instanceName] = instance;
return { error: false, message: 'Instance restarted' };
} catch (error) {
this.logger.error(error);
}
}
public async connectionState({ instanceName }: InstanceDto) {
return this.waMonitor.waInstances[instanceName]?.connectionStatus;
}
@ -195,8 +219,15 @@ export class InstanceController {
]);
}
try {
delete this.waMonitor.waInstances[instanceName];
return { error: false, message: 'Instance deleted' };
if (stateConn.state === 'connecting') {
await this.logout({ instanceName });
delete this.waMonitor.waInstances[instanceName];
return { error: false, message: 'Instance deleted' };
} else {
delete this.waMonitor.waInstances[instanceName];
this.eventEmitter.emit('remove.instance', instanceName, 'inner');
return { error: false, message: 'Instance deleted' };
}
} catch (error) {
throw new BadRequestException(error.toString());
}

View File

@ -2,7 +2,7 @@ import {
WAPrivacyOnlineValue,
WAPrivacyValue,
WAReadReceiptsValue,
} from '@evolution/base';
} from '@whiskeysockets/baileys';
export class OnWhatsAppDto {
constructor(

View File

@ -1,4 +1,4 @@
import { proto, WAPresence } from '@evolution/base';
import { proto, WAPresence } from '@whiskeysockets/baileys';
export class Quoted {
key: proto.IMessageKey;

View File

@ -4,6 +4,7 @@ import { IInsert, Repository } from '../abstract/abstract.repository';
import { IAuthModel, AuthRaw } from '../models';
import { readFileSync } from 'fs';
import { AUTH_DIR } from '../../config/path.config';
import { InstanceDto } from '../dto/instance.dto';
export class AuthRepository extends Repository {
constructor(

View File

@ -29,7 +29,7 @@ import { chatController } from '../whatsapp.module';
import { RouterBroker } from '../abstract/abstract.router';
import { HttpStatus } from './index.router';
import { MessageUpQuery } from '../repository/messageUp.repository';
import { proto } from '@evolution/base';
import { proto } from '@whiskeysockets/baileys';
import { InstanceDto } from '../dto/instance.dto';
export class ChatRouter extends RouterBroker {

View File

@ -23,6 +23,16 @@ export class InstanceRouter extends RouterBroker {
return res.status(HttpStatus.CREATED).json(response);
})
.put(this.routerPath('restart'), ...guards, async (req, res) => {
const response = await this.dataValidate<InstanceDto>({
request: req,
schema: instanceNameSchema,
ClassRef: InstanceDto,
execute: (instance) => instanceController.restartInstance(instance),
});
return res.status(HttpStatus.OK).json(response);
})
.get(this.routerPath('connect'), ...guards, async (req, res) => {
const response = await this.dataValidate<InstanceDto>({
request: req,

View File

@ -72,6 +72,18 @@ export class AuthService {
return { apikey };
}
public async checkDuplicateToken(token: string) {
const instances = await this.waMonitor.instanceInfo();
const instance = instances.find((instance) => instance.instance.apikey === token);
if (instance) {
throw new BadRequestException('Token already exists');
}
return true;
}
public async generateHash(instance: InstanceDto, token?: string) {
const options = this.configService.get<Auth>('AUTHENTICATION');
return (await this[options.TYPE](instance, token)) as

View File

@ -16,7 +16,6 @@ import { NotFoundException } from '../../exceptions';
import { Db } from 'mongodb';
import { RedisCache } from '../../db/redis.client';
import { initInstance } from '../whatsapp.module';
import { ValidationError } from 'class-validator';
export class WAMonitoringService {
constructor(
@ -50,9 +49,19 @@ export class WAMonitoringService {
public delInstanceTime(instance: string) {
const time = this.configService.get<DelInstance>('DEL_INSTANCE');
if (typeof time === 'number' && time > 0) {
setTimeout(() => {
setTimeout(async () => {
if (this.waInstances[instance]?.connectionStatus?.state !== 'open') {
delete this.waInstances[instance];
if (this.waInstances[instance]?.connectionStatus?.state === 'connecting') {
await this.waInstances[instance]?.client?.logout(
'Log out instance: ' + instance,
);
this.waInstances[instance]?.client?.ws?.close();
this.waInstances[instance]?.client?.end(undefined);
delete this.waInstances[instance];
} else {
delete this.waInstances[instance];
this.eventEmitter.emit('remove.instance', instance, 'inner');
}
}
}, 1000 * 60 * time);
}
@ -156,7 +165,7 @@ export class WAMonitoringService {
}, 3600 * 1000 * 2);
}
private async cleaningUp(instanceName: string) {
public async cleaningUp(instanceName: string) {
if (this.db.ENABLED && this.db.SAVE_DATA.INSTANCE) {
await this.repository.dbServer.connect();
const collections: any[] = await this.dbInstance.collections();

View File

@ -30,7 +30,7 @@ import makeWASocket, {
WAMessageUpdate,
WASocket,
getAggregateVotesInPollMessage,
} from '@evolution/base';
} from '@whiskeysockets/baileys';
import {
Auth,
CleanStoreConf,

View File

@ -1,5 +1,5 @@
/* eslint-disable @typescript-eslint/no-namespace */
import { AuthenticationState, WAConnectionState } from '@evolution/base';
import { AuthenticationState, WAConnectionState } from '@whiskeysockets/baileys';
export enum Events {
APPLICATION_STARTUP = 'application.startup',

View File

@ -27,7 +27,7 @@ import { WebhookRepository } from './repository/webhook.repository';
import { WebhookModel } from './models/webhook.model';
import { AuthRepository } from './repository/auth.repository';
import { WAStartupService } from './services/whatsapp.service';
import { delay } from '@evolution/base';
import { delay } from '@whiskeysockets/baileys';
import { Events } from './types/wa.types';
const logger = new Logger('WA MODULE');