Skip to content

Commit

Permalink
Adjust to repository from session worker
Browse files Browse the repository at this point in the history
  • Loading branch information
DavidsonGomes committed Jun 1, 2024
1 parent f48f331 commit 9354af3
Show file tree
Hide file tree
Showing 5 changed files with 53 additions and 24 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@
"amqplib": "^0.10.3",
"@aws-sdk/client-sqs": "^3.569.0",
"axios": "^1.6.5",
"@whiskeysockets/baileys": "^6.7.2",
"@whiskeysockets/baileys": "6.6.0",
"class-validator": "^0.14.1",
"compression": "^1.7.4",
"cors": "^2.8.5",
Expand Down
18 changes: 8 additions & 10 deletions src/api/provider/sessions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ type ResponseProvider = Promise<[ResponseSuccess?, Error?]>;

export class ProviderFiles {
constructor(private readonly configService: ConfigService) {
this.baseUrl = `http://${this.config.HOST}:${this.config.PORT}/session`;
this.baseUrl = `http://${this.config.HOST}:${this.config.PORT}/session/${this.config.PREFIX}`;
}

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

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

private readonly prefix = Object.freeze(this.configService.get<ProviderSession>('PROVIDER').PREFIX);

get isEnabled() {
return !!this.config?.ENABLED;
}
Expand All @@ -30,7 +28,7 @@ export class ProviderFiles {
baseURL: this.baseUrl,
});
try {
const response = await client.options(`/${this.prefix}/ping`);
const response = await client.options('/ping');
if (!response?.data?.pong) {
throw new Error('Offline file provider.');
}
Expand All @@ -48,7 +46,7 @@ export class ProviderFiles {

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

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

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

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

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

public async removeSession(instance: string): ResponseProvider {
try {
const response = await axios.delete(`${this.baseUrl}/${this.prefix}/${instance}`);
const response = await axios.delete(`${this.baseUrl}/${instance}`);
return [{ status: response.status, data: response?.data }];
} catch (error) {
return [
Expand Down
4 changes: 2 additions & 2 deletions src/api/services/channels/whatsapp.baileys.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ export class BaileysStartupService extends ChannelStartupService {
this.instance.qrcode = { count: 0 };
this.mobile = false;
this.recoveringMessages();
this.authStateProvider = new AuthStateProvider(this.configService, this.providerFiles);
this.authStateProvider = new AuthStateProvider(this.providerFiles);
}

private authStateProvider: AuthStateProvider;
Expand Down Expand Up @@ -1486,7 +1486,7 @@ export class BaileysStartupService extends ChannelStartupService {
});
const chat = chats.find((c) => c.id === data.association.chatId);
if (chat) {
let labels = [...chat.labels];
let labels = [...chat?.labels];
if (data.type === 'remove') {
labels = labels.filter((label) => label !== data.association.labelId);
} else if (data.type === 'add') {
Expand Down
40 changes: 36 additions & 4 deletions src/api/services/monitor.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,15 @@ import { Db } from 'mongodb';
import { Collection } from 'mongoose';
import { join } from 'path';

import { Auth, CacheConf, ConfigService, Database, DelInstance, HttpServer } from '../../config/env.config';
import {
Auth,
CacheConf,
ConfigService,
Database,
DelInstance,
HttpServer,
ProviderSession,
} from '../../config/env.config';
import { Logger } from '../../config/logger.config';
import { INSTANCE_DIR, STORE_DIR } from '../../config/path.config';
import { NotFoundException } from '../../exceptions';
Expand Down Expand Up @@ -60,6 +68,8 @@ export class WAMonitoringService {
private readonly logger = new Logger(WAMonitoringService.name);
public readonly waInstances: Record<string, BaileysStartupService | BusinessStartupService> = {};

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

public delInstanceTime(instance: string) {
const time = this.configService.get<DelInstance>('DEL_INSTANCE');
if (typeof time === 'number' && time > 0) {
Expand Down Expand Up @@ -259,13 +269,21 @@ export class WAMonitoringService {
}

this.logger.verbose('cleaning up instance in files: ' + instanceName);
rmSync(join(INSTANCE_DIR, instanceName), { recursive: true, force: true });
if (this.providerSession?.ENABLED) {
await this.providerFiles.removeSession(instanceName);
} else {
rmSync(join(INSTANCE_DIR, instanceName), { recursive: true, force: true });
}
}

public async cleaningStoreFiles(instanceName: string) {
if (!this.db.ENABLED) {
this.logger.verbose('cleaning store files instance: ' + instanceName);
rmSync(join(INSTANCE_DIR, instanceName), { recursive: true, force: true });
if (this.providerSession?.ENABLED) {
await this.providerFiles.removeSession(instanceName);
} else {
rmSync(join(INSTANCE_DIR, instanceName), { recursive: true, force: true });
}

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

try {
if (this.redis.REDIS.ENABLED && this.redis.REDIS.SAVE_INSTANCES) {
if (this.providerSession.ENABLED) {
await this.loadInstancesFromProvider();
} else if (this.redis.REDIS.ENABLED && this.redis.REDIS.SAVE_INSTANCES) {
await this.loadInstancesFromRedis();
} else if (this.db.ENABLED && this.db.SAVE_DATA.INSTANCE) {
await this.loadInstancesFromDatabase();
Expand Down Expand Up @@ -405,6 +425,18 @@ export class WAMonitoringService {
}
}

private async loadInstancesFromProvider() {
this.logger.verbose('Provider in files enabled');
const [instances] = await this.providerFiles.allInstances();

if (!instances?.data) {
this.logger.verbose('No instances found');
return;
}

await Promise.all(instances?.data?.map(async (instanceName: string) => this.setInstance(instanceName)));
}

private async loadInstancesFromFiles() {
this.logger.verbose('Store in files enabled');
const dir = opendirSync(INSTANCE_DIR, { encoding: 'utf-8' });
Expand Down
13 changes: 6 additions & 7 deletions src/utils/use-multi-file-auth-state-provider-files.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
/**
* ┌──────────────────────────────────────────────────────────────────────────────┐
* │ @author jrCleber │
* │ @filename use-multi-file-auth-state-redis-db.ts │
* │ @filename use-multi-file-auth-state-provider-files.ts │
* │ Developed by: Cleber Wilson │
* │ Creation date: Apr 09, 2023
* │ Creation date: May 31, 2024
* │ Contact: [email protected]
* ├──────────────────────────────────────────────────────────────────────────────┤
* │ @copyright © Cleber Wilson 2023. All rights reserved. │
Expand Down Expand Up @@ -45,13 +45,12 @@ import {
import { isNotEmpty } from 'class-validator';

import { ProviderFiles } from '../api/provider/sessions';
import { ConfigService } from '../config/env.config';
import { Logger } from '../config/logger.config';

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

export class AuthStateProvider {
constructor(private readonly configService: ConfigService, private readonly providerFiles: ProviderFiles) {}
constructor(private readonly providerFiles: ProviderFiles) {}

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

Expand All @@ -68,7 +67,7 @@ export class AuthStateProvider {
data: json,
});
if (error) {
this.logger.error([error?.message, error?.stack]);
this.logger.error(['writeData', error?.message, error?.stack]);
return;
}
return response;
Expand All @@ -77,7 +76,7 @@ export class AuthStateProvider {
const readData = async (key: string): Promise<any> => {
const [response, error] = await this.providerFiles.read(instance, key);
if (error) {
this.logger.error([error?.message, error?.stack]);
this.logger.error(['readData', error?.message, error?.stack]);
return;
}
if (isNotEmpty(response?.data)) {
Expand All @@ -88,7 +87,7 @@ export class AuthStateProvider {
const removeData = async (key: string) => {
const [response, error] = await this.providerFiles.delete(instance, key);
if (error) {
this.logger.error([error?.message, error?.stack]);
this.logger.error(['removeData', error?.message, error?.stack]);
return;
}

Expand Down

0 comments on commit 9354af3

Please sign in to comment.