Skip to content

Commit

Permalink
configuração do cliente do worker - #130
Browse files Browse the repository at this point in the history
  • Loading branch information
jrCleber committed Jun 5, 2024
1 parent b214c68 commit 6e130ab
Show file tree
Hide file tree
Showing 2 changed files with 141 additions and 24 deletions.
107 changes: 107 additions & 0 deletions src/provider/sessions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import axios, { Axios } from 'axios';
import { ConfigService, ProviderSession } from '../config/env.config';
import { Logger } from '../config/logger.config';
import { execSync } from 'child_process';

type ResponseSuccess = { status: number; data?: any };
type ResponseProvider = Promise<[ResponseSuccess?, Error?]>;

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

private readonly logger = new Logger(this.configService, ProviderFiles.name);

private _client: Axios;

public get client() {
return this._client;
}

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

get isEnabled() {
return !!this.config?.ENABLED;
}

public async onModuleInit() {
if (this.config.ENABLED) {
this._client = axios.create({
baseURL: `http://${this.config.HOST}:${this.config.PORT}/session`,
});
try {
const response = await this._client.options('/ping');
if (!response?.data?.pong) {
throw new Error('Offline file provider.');
}
} catch (error) {
this.logger.error([
'Failed to connect to the file server',
error?.message,
error?.stack,
]);
const pid = process.pid;
execSync(`kill -9 ${pid}`);
}
}
}

public async onModuleDestroy() {
//
}

public async create(instance: string): ResponseProvider {
try {
const response = await this._client.post('', { instance });
return [{ status: response.status, data: response?.data }];
} catch (error) {
return [, error];
}
}

public async write(instance: string, key: string, data: any): ResponseProvider {
try {
const response = await this._client.post(`/${instance}/${key}`, data);
return [{ status: response.status, data: response?.data }];
} catch (error) {
return [, error];
}
}

public async read(instance: string, key: string): ResponseProvider {
try {
const response = await this._client.get(`/${instance}/${key}`);
return [{ status: response.status, data: response?.data }];
} catch (error) {
return [, error];
}
}

public async delete(instance: string, key: string): ResponseProvider {
try {
const response = await this._client.delete(`/${instance}/${key}`);
return [{ status: response.status, data: response?.data }];
} catch (error) {
return [, error];
}
}

public async allInstances(): ResponseProvider {
try {
const response = await this._client.get('/list-instances');
return [{ status: response.status, data: response?.data as string[] }];
} catch (error) {
return [, error];
}
}

public async removeSession(instance: string): ResponseProvider {
try {
const response = await this._client.delete(`/${instance}`);
return [{ status: response.status, data: response?.data }];
} catch (error) {
return [, error];
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -45,50 +45,60 @@ import {
SignalDataTypeMap,
} from '@whiskeysockets/baileys';
import { Logger } from '../config/logger.config';
import { ConfigService, Redis } from '../config/env.config';
import { RedisCache } from '../cache/redis';
import { ConfigService } from '../config/env.config';
import { ProviderFiles } from '../provider/sessions';
import { isNotEmpty } from 'class-validator';

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

private readonly logger = new Logger(this.configService, AuthStateRedis.name);
private readonly config = Object.freeze(this.configService.get<Redis>('REDIS'));
private readonly logger = new Logger(this.configService, AuthStateProvider.name);

public async authStateRedisDb(instance: string): Promise<AuthState> {
const defaultKey = `${this.config.PREFIX_KEY}:${instance}`;
public async authStateProvider(instance: string): Promise<AuthState> {
const [, error] = await this.providerFiles.create(instance);
if (error) {
this.logger.error([
'Failed to create folder on file server',
error?.message,
error?.stack,
]);
return;
}

const writeData = async (data: any, key: string): Promise<any> => {
try {
const json = JSON.stringify(data, BufferJSON.replacer);
return await this.redisCache.client.hSet(defaultKey, key, json);
} catch (error) {
this.logger.error({ localError: 'writeData', error });
const json = JSON.stringify(data, BufferJSON.replacer);
const [response, error] = await this.providerFiles.write(instance, key, {
data: json,
});
if (error) {
this.logger.error([error?.message, error?.stack]);
return;
}
return response;
};

const readData = async (key: string): Promise<any> => {
try {
const data = await this.redisCache.client.hGet(defaultKey, key);
if (data) {
return JSON.parse(data, BufferJSON.reviver);
}
} catch (error) {
this.logger.error({ readData: 'writeData', error });
const [response, error] = await this.providerFiles.read(instance, key);
if (error) {
this.logger.error([error?.message, error?.stack]);
return;
}
if (isNotEmpty(response?.data)) {
return JSON.parse(JSON.stringify(response.data), BufferJSON.reviver);
}
};

const removeData = async (key: string) => {
try {
return await this.redisCache.client.hDel(defaultKey, key);
} catch (error) {
this.logger.error({ readData: 'removeData', error });
const [response, error] = await this.providerFiles.delete(instance, key);
if (error) {
this.logger.error([error?.message, error?.stack]);
return;
}

return response;
};

const creds: AuthenticationCreds = (await readData('creds')) || initAuthCreds();
Expand Down

0 comments on commit 6e130ab

Please sign in to comment.