Skip to content

Commit 8608b7c

Browse files
Merge pull request #404 from judsonjuniorr/instance-deletion
Temp instance deletion
2 parents 32026d1 + 704701e commit 8608b7c

File tree

8 files changed

+54
-39
lines changed

8 files changed

+54
-39
lines changed

src/utils/i18n.ts

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,6 @@ import path from 'path';
44

55
import { ConfigService, Language } from '../config/env.config';
66

7-
// export class i18n {
8-
// constructor(private readonly configService: ConfigService) {
97
const languages = ['en', 'pt-BR'];
108
const translationsPath = path.join(__dirname, 'translations');
119
const configService: ConfigService = new ConfigService();
@@ -31,6 +29,4 @@ i18next.init({
3129
escapeValue: false,
3230
},
3331
});
34-
// }
35-
// }
3632
export default i18next;

src/whatsapp/abstract/abstract.router.ts

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@ const logger = new Logger('Validate');
2121
export abstract class RouterBroker {
2222
constructor() {}
2323
public routerPath(path: string, param = true) {
24-
// const route = param ? '/:instanceName/' + path : '/' + path;
2524
let route = '/' + path;
2625
param ? (route += '/:instanceName') : null;
2726

@@ -56,10 +55,6 @@ export abstract class RouterBroker {
5655
message = stack.replace('instance.', '');
5756
}
5857
return message;
59-
// return {
60-
// property: property.replace('instance.', ''),
61-
// message,
62-
// };
6358
});
6459
logger.error(message);
6560
throw new BadRequestException(message);

src/whatsapp/controllers/settings.controller.ts

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,4 @@
1-
// import { isURL } from 'class-validator';
2-
31
import { Logger } from '../../config/logger.config';
4-
// import { BadRequestException } from '../../exceptions';
52
import { InstanceDto } from '../dto/instance.dto';
63
import { SettingsDto } from '../dto/settings.dto';
74
import { SettingsService } from '../services/settings.service';

src/whatsapp/repository/auth.repository.ts

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { readFileSync } from 'fs';
1+
import { opendirSync, readFileSync } from 'fs';
22
import { join } from 'path';
33

44
import { Auth, ConfigService } from '../../config/env.config';
@@ -64,6 +64,37 @@ export class AuthRepository extends Repository {
6464
}
6565
}
6666

67+
public async list(): Promise<AuthRaw[]> {
68+
try {
69+
if (this.dbSettings.ENABLED) {
70+
this.logger.verbose('listing auth in db');
71+
return await this.authModel.find();
72+
}
73+
74+
this.logger.verbose('listing auth in store');
75+
76+
const auths: AuthRaw[] = [];
77+
const openDir = opendirSync(join(AUTH_DIR, this.auth.TYPE), {
78+
encoding: 'utf-8',
79+
});
80+
for await (const dirent of openDir) {
81+
if (dirent.isFile()) {
82+
auths.push(
83+
JSON.parse(
84+
readFileSync(join(AUTH_DIR, this.auth.TYPE, dirent.name), {
85+
encoding: 'utf-8',
86+
}),
87+
),
88+
);
89+
}
90+
}
91+
92+
return auths;
93+
} catch (error) {
94+
return [];
95+
}
96+
}
97+
6798
public async findInstanceNameById(instanceId: string): Promise<string | null> {
6899
try {
69100
this.logger.verbose('finding auth by instanceId');

src/whatsapp/routers/chatwoot.router.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ import { chatwootSchema, instanceNameSchema } from '../../validate/validate.sche
55
import { RouterBroker } from '../abstract/abstract.router';
66
import { ChatwootDto } from '../dto/chatwoot.dto';
77
import { InstanceDto } from '../dto/instance.dto';
8-
// import { ChatwootService } from '../services/chatwoot.service';
98
import { chatwootController } from '../whatsapp.module';
109
import { HttpStatus } from './index.router';
1110

src/whatsapp/routers/settings.router.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ import { instanceNameSchema, settingsSchema } from '../../validate/validate.sche
55
import { RouterBroker } from '../abstract/abstract.router';
66
import { InstanceDto } from '../dto/instance.dto';
77
import { SettingsDto } from '../dto/settings.dto';
8-
// import { SettingsService } from '../services/settings.service';
98
import { settingsController } from '../whatsapp.module';
109
import { HttpStatus } from './index.router';
1110

src/whatsapp/services/chatwoot.service.ts

Lines changed: 0 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -51,11 +51,6 @@ export class ChatwootService {
5151
this.cache.set(cacheKey, provider);
5252

5353
return provider;
54-
// try {
55-
// } catch (error) {
56-
// this.logger.error('provider not found');
57-
// return null;
58-
// }
5954
}
6055

6156
private async clientCw(instance: InstanceDto) {
@@ -389,10 +384,6 @@ export class ChatwootService {
389384
q: query,
390385
});
391386
} else {
392-
// contact = await client.contacts.filter({
393-
// accountId: this.provider.account_id,
394-
// payload: this.getFilterPayload(query),
395-
// });
396387
// hotfix for: https://github.com/EvolutionAPI/evolution-api/pull/382. waiting fix: https://github.com/figurolatam/chatwoot-sdk/pull/7
397388
contact = await chatwootRequest(this.getClientCwConfig(), {
398389
method: 'POST',
@@ -1194,7 +1185,6 @@ export class ChatwootService {
11941185
if (state !== 'open') {
11951186
if (state === 'close') {
11961187
this.logger.verbose('request cleaning up instance: ' + instance.instanceName);
1197-
// await this.waMonitor.cleaningUp(instance.instanceName);
11981188
}
11991189
this.logger.verbose('connect to whatsapp');
12001190
const number = command.split(':')[1];

src/whatsapp/services/monitor.service.ts

Lines changed: 22 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2,22 +2,19 @@ import { execSync } from 'child_process';
22
import EventEmitter2 from 'eventemitter2';
33
import { opendirSync, readdirSync, rmSync } from 'fs';
44
import { Db } from 'mongodb';
5+
import { Collection } from 'mongoose';
56
import { join } from 'path';
67

78
import { Auth, ConfigService, Database, DelInstance, HttpServer, Redis } from '../../config/env.config';
89
import { Logger } from '../../config/logger.config';
910
import { INSTANCE_DIR, STORE_DIR } from '../../config/path.config';
1011
import { NotFoundException } from '../../exceptions';
11-
import { dbserver } from '../../libs/db.connect';
1212
import { RedisCache } from '../../libs/redis.client';
1313
import {
1414
AuthModel,
1515
ChamaaiModel,
16-
// ChatModel,
1716
ChatwootModel,
18-
// ContactModel,
19-
// MessageModel,
20-
// MessageUpModel,
17+
ContactModel,
2118
ProxyModel,
2219
RabbitmqModel,
2320
SettingsModel,
@@ -41,7 +38,6 @@ export class WAMonitoringService {
4138

4239
this.removeInstance();
4340
this.noConnection();
44-
// this.delInstanceFiles();
4541

4642
Object.assign(this.db, configService.get<Database>('DATABASE'));
4743
Object.assign(this.redis, configService.get<Redis>('REDIS'));
@@ -56,8 +52,6 @@ export class WAMonitoringService {
5652

5753
private dbInstance: Db;
5854

59-
private dbStore = dbserver;
60-
6155
private readonly logger = new Logger(WAMonitoringService.name);
6256
public readonly waInstances: Record<string, WAStartupService> = {};
6357

@@ -326,11 +320,6 @@ export class WAMonitoringService {
326320

327321
this.logger.verbose('cleaning store database instance: ' + instanceName);
328322

329-
// await ChatModel.deleteMany({ owner: instanceName });
330-
// await ContactModel.deleteMany({ owner: instanceName });
331-
// await MessageUpModel.deleteMany({ owner: instanceName });
332-
// await MessageModel.deleteMany({ owner: instanceName });
333-
334323
await AuthModel.deleteMany({ _id: instanceName });
335324
await WebhookModel.deleteMany({ _id: instanceName });
336325
await ChatwootModel.deleteMany({ _id: instanceName });
@@ -340,6 +329,7 @@ export class WAMonitoringService {
340329
await TypebotModel.deleteMany({ _id: instanceName });
341330
await WebsocketModel.deleteMany({ _id: instanceName });
342331
await SettingsModel.deleteMany({ _id: instanceName });
332+
await ContactModel.deleteMany({ owner: instanceName });
343333

344334
return;
345335
}
@@ -393,7 +383,7 @@ export class WAMonitoringService {
393383
this.logger.verbose('Database enabled');
394384
await this.repository.dbServer.connect();
395385
const collections: any[] = await this.dbInstance.collections();
396-
386+
await this.deleteTempInstances(collections);
397387
if (collections.length > 0) {
398388
this.logger.verbose('Reading collections and setting instances');
399389
await Promise.all(collections.map((coll) => this.setInstance(coll.namespace.replace(/^[\w-]+\./, ''))));
@@ -482,4 +472,22 @@ export class WAMonitoringService {
482472
}
483473
});
484474
}
475+
476+
private async deleteTempInstances(collections: Collection<Document>[]) {
477+
this.logger.verbose('Cleaning up temp instances');
478+
const auths = await this.repository.auth.list();
479+
if (auths.length === 0) {
480+
this.logger.verbose('No temp instances found');
481+
return;
482+
}
483+
let tempInstances = 0;
484+
auths.forEach((auth) => {
485+
if (collections.find((coll) => coll.namespace.replace(/^[\w-]+\./, '') === auth._id)) {
486+
return;
487+
}
488+
tempInstances++;
489+
this.eventEmitter.emit('remove.instance', auth._id, 'inner');
490+
});
491+
this.logger.verbose('Temp instances removed: ' + tempInstances);
492+
}
485493
}

0 commit comments

Comments
 (0)