Skip to content

Commit 9354af3

Browse files
committed
Adjust to repository from session worker
1 parent f48f331 commit 9354af3

File tree

5 files changed

+53
-24
lines changed

5 files changed

+53
-24
lines changed

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@
4949
"amqplib": "^0.10.3",
5050
"@aws-sdk/client-sqs": "^3.569.0",
5151
"axios": "^1.6.5",
52-
"@whiskeysockets/baileys": "^6.7.2",
52+
"@whiskeysockets/baileys": "6.6.0",
5353
"class-validator": "^0.14.1",
5454
"compression": "^1.7.4",
5555
"cors": "^2.8.5",

src/api/provider/sessions.ts

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ type ResponseProvider = Promise<[ResponseSuccess?, Error?]>;
99

1010
export class ProviderFiles {
1111
constructor(private readonly configService: ConfigService) {
12-
this.baseUrl = `http://${this.config.HOST}:${this.config.PORT}/session`;
12+
this.baseUrl = `http://${this.config.HOST}:${this.config.PORT}/session/${this.config.PREFIX}`;
1313
}
1414

1515
private readonly logger = new Logger(ProviderFiles.name);
@@ -18,8 +18,6 @@ export class ProviderFiles {
1818

1919
private readonly config = Object.freeze(this.configService.get<ProviderSession>('PROVIDER'));
2020

21-
private readonly prefix = Object.freeze(this.configService.get<ProviderSession>('PROVIDER').PREFIX);
22-
2321
get isEnabled() {
2422
return !!this.config?.ENABLED;
2523
}
@@ -30,7 +28,7 @@ export class ProviderFiles {
3028
baseURL: this.baseUrl,
3129
});
3230
try {
33-
const response = await client.options(`/${this.prefix}/ping`);
31+
const response = await client.options('/ping');
3432
if (!response?.data?.pong) {
3533
throw new Error('Offline file provider.');
3634
}
@@ -48,7 +46,7 @@ export class ProviderFiles {
4846

4947
public async create(instance: string): ResponseProvider {
5048
try {
51-
const response = await axios.post(`${this.baseUrl}/${this.prefix}`, {
49+
const response = await axios.post(`${this.baseUrl}`, {
5250
instance,
5351
});
5452
return [{ status: response.status, data: response?.data }];
@@ -65,7 +63,7 @@ export class ProviderFiles {
6563

6664
public async write(instance: string, key: string, data: any): ResponseProvider {
6765
try {
68-
const response = await axios.post(`${this.baseUrl}/${this.prefix}/${instance}/${key}`, data);
66+
const response = await axios.post(`${this.baseUrl}/${instance}/${key}`, data);
6967
return [{ status: response.status, data: response?.data }];
7068
} catch (error) {
7169
return [
@@ -80,7 +78,7 @@ export class ProviderFiles {
8078

8179
public async read(instance: string, key: string): ResponseProvider {
8280
try {
83-
const response = await axios.get(`${this.baseUrl}/${this.prefix}/${instance}/${key}`);
81+
const response = await axios.get(`${this.baseUrl}/${instance}/${key}`);
8482
return [{ status: response.status, data: response?.data }];
8583
} catch (error) {
8684
return [
@@ -95,7 +93,7 @@ export class ProviderFiles {
9593

9694
public async delete(instance: string, key: string): ResponseProvider {
9795
try {
98-
const response = await axios.delete(`${this.baseUrl}/${this.prefix}/${instance}/${key}`);
96+
const response = await axios.delete(`${this.baseUrl}/${instance}/${key}`);
9997
return [{ status: response.status, data: response?.data }];
10098
} catch (error) {
10199
return [
@@ -110,7 +108,7 @@ export class ProviderFiles {
110108

111109
public async allInstances(): ResponseProvider {
112110
try {
113-
const response = await axios.get(`${this.baseUrl}/${this.prefix}/list-instances`);
111+
const response = await axios.get(`${this.baseUrl}/list-instances`);
114112
return [{ status: response.status, data: response?.data as string[] }];
115113
} catch (error) {
116114
return [
@@ -125,7 +123,7 @@ export class ProviderFiles {
125123

126124
public async removeSession(instance: string): ResponseProvider {
127125
try {
128-
const response = await axios.delete(`${this.baseUrl}/${this.prefix}/${instance}`);
126+
const response = await axios.delete(`${this.baseUrl}/${instance}`);
129127
return [{ status: response.status, data: response?.data }];
130128
} catch (error) {
131129
return [

src/api/services/channels/whatsapp.baileys.service.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,7 @@ export class BaileysStartupService extends ChannelStartupService {
146146
this.instance.qrcode = { count: 0 };
147147
this.mobile = false;
148148
this.recoveringMessages();
149-
this.authStateProvider = new AuthStateProvider(this.configService, this.providerFiles);
149+
this.authStateProvider = new AuthStateProvider(this.providerFiles);
150150
}
151151

152152
private authStateProvider: AuthStateProvider;
@@ -1486,7 +1486,7 @@ export class BaileysStartupService extends ChannelStartupService {
14861486
});
14871487
const chat = chats.find((c) => c.id === data.association.chatId);
14881488
if (chat) {
1489-
let labels = [...chat.labels];
1489+
let labels = [...chat?.labels];
14901490
if (data.type === 'remove') {
14911491
labels = labels.filter((label) => label !== data.association.labelId);
14921492
} else if (data.type === 'add') {

src/api/services/monitor.service.ts

Lines changed: 36 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,15 @@ import { Db } from 'mongodb';
55
import { Collection } from 'mongoose';
66
import { join } from 'path';
77

8-
import { Auth, CacheConf, ConfigService, Database, DelInstance, HttpServer } from '../../config/env.config';
8+
import {
9+
Auth,
10+
CacheConf,
11+
ConfigService,
12+
Database,
13+
DelInstance,
14+
HttpServer,
15+
ProviderSession,
16+
} from '../../config/env.config';
917
import { Logger } from '../../config/logger.config';
1018
import { INSTANCE_DIR, STORE_DIR } from '../../config/path.config';
1119
import { NotFoundException } from '../../exceptions';
@@ -60,6 +68,8 @@ export class WAMonitoringService {
6068
private readonly logger = new Logger(WAMonitoringService.name);
6169
public readonly waInstances: Record<string, BaileysStartupService | BusinessStartupService> = {};
6270

71+
private readonly providerSession = Object.freeze(this.configService.get<ProviderSession>('PROVIDER'));
72+
6373
public delInstanceTime(instance: string) {
6474
const time = this.configService.get<DelInstance>('DEL_INSTANCE');
6575
if (typeof time === 'number' && time > 0) {
@@ -259,13 +269,21 @@ export class WAMonitoringService {
259269
}
260270

261271
this.logger.verbose('cleaning up instance in files: ' + instanceName);
262-
rmSync(join(INSTANCE_DIR, instanceName), { recursive: true, force: true });
272+
if (this.providerSession?.ENABLED) {
273+
await this.providerFiles.removeSession(instanceName);
274+
} else {
275+
rmSync(join(INSTANCE_DIR, instanceName), { recursive: true, force: true });
276+
}
263277
}
264278

265279
public async cleaningStoreFiles(instanceName: string) {
266280
if (!this.db.ENABLED) {
267281
this.logger.verbose('cleaning store files instance: ' + instanceName);
268-
rmSync(join(INSTANCE_DIR, instanceName), { recursive: true, force: true });
282+
if (this.providerSession?.ENABLED) {
283+
await this.providerFiles.removeSession(instanceName);
284+
} else {
285+
rmSync(join(INSTANCE_DIR, instanceName), { recursive: true, force: true });
286+
}
269287

270288
execSync(`rm -rf ${join(STORE_DIR, 'chats', instanceName)}`);
271289
execSync(`rm -rf ${join(STORE_DIR, 'contacts', instanceName)}`);
@@ -307,7 +325,9 @@ export class WAMonitoringService {
307325
this.logger.verbose('Loading instances');
308326

309327
try {
310-
if (this.redis.REDIS.ENABLED && this.redis.REDIS.SAVE_INSTANCES) {
328+
if (this.providerSession.ENABLED) {
329+
await this.loadInstancesFromProvider();
330+
} else if (this.redis.REDIS.ENABLED && this.redis.REDIS.SAVE_INSTANCES) {
311331
await this.loadInstancesFromRedis();
312332
} else if (this.db.ENABLED && this.db.SAVE_DATA.INSTANCE) {
313333
await this.loadInstancesFromDatabase();
@@ -405,6 +425,18 @@ export class WAMonitoringService {
405425
}
406426
}
407427

428+
private async loadInstancesFromProvider() {
429+
this.logger.verbose('Provider in files enabled');
430+
const [instances] = await this.providerFiles.allInstances();
431+
432+
if (!instances?.data) {
433+
this.logger.verbose('No instances found');
434+
return;
435+
}
436+
437+
await Promise.all(instances?.data?.map(async (instanceName: string) => this.setInstance(instanceName)));
438+
}
439+
408440
private async loadInstancesFromFiles() {
409441
this.logger.verbose('Store in files enabled');
410442
const dir = opendirSync(INSTANCE_DIR, { encoding: 'utf-8' });

src/utils/use-multi-file-auth-state-provider-files.ts

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
/**
22
* ┌──────────────────────────────────────────────────────────────────────────────┐
33
* │ @author jrCleber │
4-
* │ @filename use-multi-file-auth-state-redis-db.ts │
4+
* │ @filename use-multi-file-auth-state-provider-files.ts │
55
* │ Developed by: Cleber Wilson │
6-
* │ Creation date: Apr 09, 2023
6+
* │ Creation date: May 31, 2024
77
* │ Contact: contato@codechat.dev │
88
* ├──────────────────────────────────────────────────────────────────────────────┤
99
* │ @copyright © Cleber Wilson 2023. All rights reserved. │
@@ -45,13 +45,12 @@ import {
4545
import { isNotEmpty } from 'class-validator';
4646

4747
import { ProviderFiles } from '../api/provider/sessions';
48-
import { ConfigService } from '../config/env.config';
4948
import { Logger } from '../config/logger.config';
5049

5150
export type AuthState = { state: AuthenticationState; saveCreds: () => Promise<void> };
5251

5352
export class AuthStateProvider {
54-
constructor(private readonly configService: ConfigService, private readonly providerFiles: ProviderFiles) {}
53+
constructor(private readonly providerFiles: ProviderFiles) {}
5554

5655
private readonly logger = new Logger(AuthStateProvider.name);
5756

@@ -68,7 +67,7 @@ export class AuthStateProvider {
6867
data: json,
6968
});
7069
if (error) {
71-
this.logger.error([error?.message, error?.stack]);
70+
this.logger.error(['writeData', error?.message, error?.stack]);
7271
return;
7372
}
7473
return response;
@@ -77,7 +76,7 @@ export class AuthStateProvider {
7776
const readData = async (key: string): Promise<any> => {
7877
const [response, error] = await this.providerFiles.read(instance, key);
7978
if (error) {
80-
this.logger.error([error?.message, error?.stack]);
79+
this.logger.error(['readData', error?.message, error?.stack]);
8180
return;
8281
}
8382
if (isNotEmpty(response?.data)) {
@@ -88,7 +87,7 @@ export class AuthStateProvider {
8887
const removeData = async (key: string) => {
8988
const [response, error] = await this.providerFiles.delete(instance, key);
9089
if (error) {
91-
this.logger.error([error?.message, error?.stack]);
90+
this.logger.error(['removeData', error?.message, error?.stack]);
9291
return;
9392
}
9493

0 commit comments

Comments
 (0)