mirror of
https://github.com/EvolutionAPI/evolution-api.git
synced 2025-12-19 03:42:23 -06:00
feat: prisma
This commit is contained in:
@@ -1,75 +1,30 @@
|
||||
import axios from 'axios';
|
||||
import { isJWT } from 'class-validator';
|
||||
import { sign, verify } from 'jsonwebtoken';
|
||||
import { v4 } from 'uuid';
|
||||
|
||||
import { name as apiName } from '../../../package.json';
|
||||
import { Auth, ConfigService, Webhook } from '../../config/env.config';
|
||||
import { Logger } from '../../config/logger.config';
|
||||
import { BadRequestException } from '../../exceptions';
|
||||
import { InstanceDto } from '../dto/instance.dto';
|
||||
import { RepositoryBroker } from '../repository/repository.manager';
|
||||
import { MongodbRepository } from '../repository/mongodb/repository.manager';
|
||||
import { PrismaRepository } from '../repository/prisma/repository.service';
|
||||
import { WAMonitoringService } from './monitor.service';
|
||||
|
||||
export type JwtPayload = {
|
||||
instanceName: string;
|
||||
apiName: string;
|
||||
jwt?: string;
|
||||
apikey?: string;
|
||||
tokenId: string;
|
||||
};
|
||||
|
||||
export class OldToken {
|
||||
oldToken: string;
|
||||
}
|
||||
|
||||
export class AuthService {
|
||||
constructor(
|
||||
private readonly configService: ConfigService,
|
||||
private readonly waMonitor: WAMonitoringService,
|
||||
private readonly repository: RepositoryBroker,
|
||||
private readonly mongodbRepository: MongodbRepository,
|
||||
private readonly prismaRepository: PrismaRepository,
|
||||
) {}
|
||||
|
||||
private readonly logger = new Logger(AuthService.name);
|
||||
|
||||
private async jwt(instance: InstanceDto) {
|
||||
const jwtOpts = this.configService.get<Auth>('AUTHENTICATION').JWT;
|
||||
const token = sign(
|
||||
{
|
||||
instanceName: instance.instanceName,
|
||||
apiName,
|
||||
tokenId: v4(),
|
||||
},
|
||||
jwtOpts.SECRET,
|
||||
{ expiresIn: jwtOpts.EXPIRIN_IN, encoding: 'utf8', subject: 'g-t' },
|
||||
);
|
||||
|
||||
this.logger.verbose('JWT token created: ' + token);
|
||||
|
||||
const auth = await this.repository.auth.create(
|
||||
{ jwt: token, instanceId: instance.instanceId },
|
||||
instance.instanceName,
|
||||
);
|
||||
|
||||
this.logger.verbose('JWT token saved in database');
|
||||
|
||||
if (auth['error']) {
|
||||
this.logger.error({
|
||||
localError: AuthService.name + '.jwt',
|
||||
error: auth['error'],
|
||||
});
|
||||
throw new BadRequestException('Authentication error', auth['error']?.toString());
|
||||
}
|
||||
|
||||
return { jwt: token };
|
||||
}
|
||||
|
||||
private async apikey(instance: InstanceDto, token?: string) {
|
||||
const apikey = token ? token : v4().toUpperCase();
|
||||
|
||||
this.logger.verbose(token ? 'APIKEY defined: ' + apikey : 'APIKEY created: ' + apikey);
|
||||
|
||||
const auth = await this.repository.auth.create({ apikey, instanceId: instance.instanceId }, instance.instanceName);
|
||||
const auth = await this.mongodbRepository.auth.create(
|
||||
{ apikey, instanceId: instance.instanceId },
|
||||
instance.instanceName,
|
||||
);
|
||||
|
||||
this.logger.verbose('APIKEY saved in database');
|
||||
|
||||
@@ -101,80 +56,8 @@ export class AuthService {
|
||||
}
|
||||
|
||||
public async generateHash(instance: InstanceDto, token?: string) {
|
||||
const options = this.configService.get<Auth>('AUTHENTICATION');
|
||||
this.logger.verbose('generating hash apiKey to instance: ' + instance.instanceName);
|
||||
|
||||
this.logger.verbose('generating hash ' + options.TYPE + ' to instance: ' + instance.instanceName);
|
||||
|
||||
return (await this[options.TYPE](instance, token)) as { jwt: string } | { apikey: string };
|
||||
}
|
||||
|
||||
public async refreshToken({ oldToken }: OldToken) {
|
||||
this.logger.verbose('refreshing token');
|
||||
|
||||
if (!isJWT(oldToken)) {
|
||||
throw new BadRequestException('Invalid "oldToken"');
|
||||
}
|
||||
|
||||
try {
|
||||
const jwtOpts = this.configService.get<Auth>('AUTHENTICATION').JWT;
|
||||
|
||||
this.logger.verbose('checking oldToken');
|
||||
|
||||
const decode = verify(oldToken, jwtOpts.SECRET, {
|
||||
ignoreExpiration: true,
|
||||
}) as Pick<JwtPayload, 'apiName' | 'instanceName' | 'tokenId'>;
|
||||
|
||||
this.logger.verbose('checking token in database');
|
||||
|
||||
const tokenStore = await this.repository.auth.find(decode.instanceName);
|
||||
|
||||
const decodeTokenStore = verify(tokenStore.jwt, jwtOpts.SECRET, {
|
||||
ignoreExpiration: true,
|
||||
}) as Pick<JwtPayload, 'apiName' | 'instanceName' | 'tokenId'>;
|
||||
|
||||
this.logger.verbose('checking tokenId');
|
||||
|
||||
if (decode.tokenId !== decodeTokenStore.tokenId) {
|
||||
throw new BadRequestException('Invalid "oldToken"');
|
||||
}
|
||||
|
||||
this.logger.verbose('generating new token');
|
||||
|
||||
const token = {
|
||||
jwt: (await this.jwt({ instanceName: decode.instanceName })).jwt,
|
||||
instanceName: decode.instanceName,
|
||||
};
|
||||
|
||||
try {
|
||||
this.logger.verbose('checking webhook');
|
||||
const webhook = await this.repository.webhook.find(decode.instanceName);
|
||||
if (webhook?.enabled && this.configService.get<Webhook>('WEBHOOK').EVENTS.NEW_JWT_TOKEN) {
|
||||
this.logger.verbose('sending webhook');
|
||||
|
||||
const httpService = axios.create({ baseURL: webhook.url });
|
||||
await httpService.post(
|
||||
'',
|
||||
{
|
||||
event: 'new.jwt',
|
||||
instance: decode.instanceName,
|
||||
data: token,
|
||||
},
|
||||
{ params: { owner: this.waMonitor.waInstances[decode.instanceName].wuid } },
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
this.logger.error(error);
|
||||
}
|
||||
|
||||
this.logger.verbose('token refreshed');
|
||||
|
||||
return token;
|
||||
} catch (error) {
|
||||
this.logger.error({
|
||||
localError: AuthService.name + '.refreshToken',
|
||||
error,
|
||||
});
|
||||
throw new BadRequestException('Invalid "oldToken"');
|
||||
}
|
||||
return (await this.apikey(instance, token)) as { apikey: string };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,7 +21,6 @@ import {
|
||||
import { Logger } from '../../config/logger.config';
|
||||
import { ROOT_DIR } from '../../config/path.config';
|
||||
import { NotFoundException } from '../../exceptions';
|
||||
import { ChamaaiService } from '../integrations/chamaai/services/chamaai.service';
|
||||
import { ChatwootRaw } from '../integrations/chatwoot/models/chatwoot.model';
|
||||
import { ChatwootService } from '../integrations/chatwoot/services/chatwoot.service';
|
||||
import { getAMQP, removeQueues } from '../integrations/rabbitmq/libs/amqp.server';
|
||||
@@ -29,12 +28,13 @@ import { getSQS, removeQueues as removeQueuesSQS } from '../integrations/sqs/lib
|
||||
import { TypebotService } from '../integrations/typebot/services/typebot.service';
|
||||
import { getIO } from '../integrations/websocket/libs/socket.server';
|
||||
import { WebsocketRaw } from '../integrations/websocket/models/websocket.model';
|
||||
import { ChamaaiRaw, IntegrationRaw, ProxyRaw, RabbitmqRaw, SettingsRaw, SqsRaw, TypebotRaw } from '../models';
|
||||
import { IntegrationRaw, ProxyRaw, RabbitmqRaw, SettingsRaw, SqsRaw, TypebotRaw } from '../models';
|
||||
import { WebhookRaw } from '../models/webhook.model';
|
||||
import { ContactQuery } from '../repository/contact.repository';
|
||||
import { MessageQuery } from '../repository/message.repository';
|
||||
import { MessageUpQuery } from '../repository/messageUp.repository';
|
||||
import { RepositoryBroker } from '../repository/repository.manager';
|
||||
import { ContactQuery } from '../repository/mongodb/contact.repository';
|
||||
import { MessageQuery } from '../repository/mongodb/message.repository';
|
||||
import { MessageUpQuery } from '../repository/mongodb/messageUp.repository';
|
||||
import { MongodbRepository } from '../repository/mongodb/repository.manager';
|
||||
import { PrismaRepository } from '../repository/prisma/repository.service';
|
||||
import { waMonitor } from '../server.module';
|
||||
import { Events, wa } from '../types/wa.types';
|
||||
import { CacheService } from './cache.service';
|
||||
@@ -43,7 +43,8 @@ export class ChannelStartupService {
|
||||
constructor(
|
||||
public readonly configService: ConfigService,
|
||||
public readonly eventEmitter: EventEmitter2,
|
||||
public readonly repository: RepositoryBroker,
|
||||
public readonly mongodbRepository: MongodbRepository,
|
||||
public readonly prismaRepository: PrismaRepository,
|
||||
public readonly chatwootCache: CacheService,
|
||||
) {
|
||||
this.logger.verbose('ChannelStartupService initialized');
|
||||
@@ -60,17 +61,20 @@ export class ChannelStartupService {
|
||||
public readonly localSqs: wa.LocalSqs = {};
|
||||
public readonly localTypebot: wa.LocalTypebot = {};
|
||||
public readonly localProxy: wa.LocalProxy = {};
|
||||
public readonly localChamaai: wa.LocalChamaai = {};
|
||||
public readonly localIntegration: wa.LocalIntegration = {};
|
||||
public readonly localSettings: wa.LocalSettings = {};
|
||||
public readonly storePath = join(ROOT_DIR, 'store');
|
||||
|
||||
public chatwootService = new ChatwootService(waMonitor, this.configService, this.repository, this.chatwootCache);
|
||||
public chatwootService = new ChatwootService(
|
||||
waMonitor,
|
||||
this.configService,
|
||||
this.mongodbRepository,
|
||||
this.prismaRepository,
|
||||
this.chatwootCache,
|
||||
);
|
||||
|
||||
public typebotService = new TypebotService(waMonitor, this.configService, this.eventEmitter);
|
||||
|
||||
public chamaaiService = new ChamaaiService(waMonitor, this.configService);
|
||||
|
||||
public set instanceName(name: string) {
|
||||
this.logger.setInstance(name);
|
||||
|
||||
@@ -112,7 +116,7 @@ export class ChannelStartupService {
|
||||
|
||||
public async loadIntegration() {
|
||||
this.logger.verbose('Loading webhook');
|
||||
const data = await this.repository.integration.find(this.instanceName);
|
||||
const data = await this.mongodbRepository.integration.find(this.instanceName);
|
||||
this.localIntegration.integration = data?.integration;
|
||||
this.logger.verbose(`Integration: ${this.localIntegration.integration}`);
|
||||
|
||||
@@ -127,7 +131,7 @@ export class ChannelStartupService {
|
||||
|
||||
public async setIntegration(data: IntegrationRaw) {
|
||||
this.logger.verbose('Setting integration');
|
||||
await this.repository.integration.create(data, this.instanceName);
|
||||
await this.mongodbRepository.integration.create(data, this.instanceName);
|
||||
this.logger.verbose(`Integration: ${data.integration}`);
|
||||
this.logger.verbose(`Integration number: ${data.number}`);
|
||||
this.logger.verbose(`Integration token: ${data.token}`);
|
||||
@@ -139,10 +143,13 @@ export class ChannelStartupService {
|
||||
this.logger.verbose('Finding integration');
|
||||
let data: any;
|
||||
|
||||
data = await this.repository.integration.find(this.instanceName);
|
||||
data = await this.mongodbRepository.integration.find(this.instanceName);
|
||||
|
||||
if (!data) {
|
||||
this.repository.integration.create({ integration: 'WHATSAPP-BAILEYS', number: '', token: '' }, this.instanceName);
|
||||
this.mongodbRepository.integration.create(
|
||||
{ integration: 'WHATSAPP-BAILEYS', number: '', token: '' },
|
||||
this.instanceName,
|
||||
);
|
||||
data = { integration: 'WHATSAPP-BAILEYS', number: '', token: '' };
|
||||
}
|
||||
|
||||
@@ -159,7 +166,7 @@ export class ChannelStartupService {
|
||||
|
||||
public async loadSettings() {
|
||||
this.logger.verbose('Loading settings');
|
||||
const data = await this.repository.settings.find(this.instanceName);
|
||||
const data = await this.mongodbRepository.settings.find(this.instanceName);
|
||||
this.localSettings.reject_call = data?.reject_call;
|
||||
this.logger.verbose(`Settings reject_call: ${this.localSettings.reject_call}`);
|
||||
|
||||
@@ -186,7 +193,7 @@ export class ChannelStartupService {
|
||||
|
||||
public async setSettings(data: SettingsRaw) {
|
||||
this.logger.verbose('Setting settings');
|
||||
await this.repository.settings.create(data, this.instanceName);
|
||||
await this.mongodbRepository.settings.create(data, this.instanceName);
|
||||
this.logger.verbose(`Settings reject_call: ${data.reject_call}`);
|
||||
this.logger.verbose(`Settings msg_call: ${data.msg_call}`);
|
||||
this.logger.verbose(`Settings groups_ignore: ${data.groups_ignore}`);
|
||||
@@ -200,7 +207,7 @@ export class ChannelStartupService {
|
||||
|
||||
public async findSettings() {
|
||||
this.logger.verbose('Finding settings');
|
||||
const data = await this.repository.settings.find(this.instanceName);
|
||||
const data = await this.mongodbRepository.settings.find(this.instanceName);
|
||||
|
||||
if (!data) {
|
||||
this.logger.verbose('Settings not found');
|
||||
@@ -227,7 +234,7 @@ export class ChannelStartupService {
|
||||
|
||||
public async loadWebhook() {
|
||||
this.logger.verbose('Loading webhook');
|
||||
const data = await this.repository.webhook.find(this.instanceName);
|
||||
const data = await this.mongodbRepository.webhook.find(this.instanceName);
|
||||
this.localWebhook.url = data?.url;
|
||||
this.logger.verbose(`Webhook url: ${this.localWebhook.url}`);
|
||||
|
||||
@@ -248,7 +255,7 @@ export class ChannelStartupService {
|
||||
|
||||
public async setWebhook(data: WebhookRaw) {
|
||||
this.logger.verbose('Setting webhook');
|
||||
await this.repository.webhook.create(data, this.instanceName);
|
||||
await this.mongodbRepository.webhook.create(data, this.instanceName);
|
||||
this.logger.verbose(`Webhook url: ${data.url}`);
|
||||
this.logger.verbose(`Webhook events: ${data.events}`);
|
||||
Object.assign(this.localWebhook, data);
|
||||
@@ -257,7 +264,7 @@ export class ChannelStartupService {
|
||||
|
||||
public async findWebhook() {
|
||||
this.logger.verbose('Finding webhook');
|
||||
const data = await this.repository.webhook.find(this.instanceName);
|
||||
const data = await this.mongodbRepository.webhook.find(this.instanceName);
|
||||
|
||||
if (!data) {
|
||||
this.logger.verbose('Webhook not found');
|
||||
@@ -278,7 +285,7 @@ export class ChannelStartupService {
|
||||
|
||||
public async loadChatwoot() {
|
||||
this.logger.verbose('Loading chatwoot');
|
||||
const data = await this.repository.chatwoot.find(this.instanceName);
|
||||
const data = await this.mongodbRepository.chatwoot.find(this.instanceName);
|
||||
this.localChatwoot.enabled = data?.enabled;
|
||||
this.logger.verbose(`Chatwoot enabled: ${this.localChatwoot.enabled}`);
|
||||
|
||||
@@ -323,7 +330,7 @@ export class ChannelStartupService {
|
||||
|
||||
public async setChatwoot(data: ChatwootRaw) {
|
||||
this.logger.verbose('Setting chatwoot');
|
||||
await this.repository.chatwoot.create(data, this.instanceName);
|
||||
await this.mongodbRepository.chatwoot.create(data, this.instanceName);
|
||||
this.logger.verbose(`Chatwoot account id: ${data.account_id}`);
|
||||
this.logger.verbose(`Chatwoot token: ${data.token}`);
|
||||
this.logger.verbose(`Chatwoot url: ${data.url}`);
|
||||
@@ -346,7 +353,7 @@ export class ChannelStartupService {
|
||||
|
||||
public async findChatwoot() {
|
||||
this.logger.verbose('Finding chatwoot');
|
||||
const data = await this.repository.chatwoot.find(this.instanceName);
|
||||
const data = await this.mongodbRepository.chatwoot.find(this.instanceName);
|
||||
|
||||
if (!data) {
|
||||
this.logger.verbose('Chatwoot not found');
|
||||
@@ -393,7 +400,7 @@ export class ChannelStartupService {
|
||||
|
||||
public async loadWebsocket() {
|
||||
this.logger.verbose('Loading websocket');
|
||||
const data = await this.repository.websocket.find(this.instanceName);
|
||||
const data = await this.mongodbRepository.websocket.find(this.instanceName);
|
||||
|
||||
this.localWebsocket.enabled = data?.enabled;
|
||||
this.logger.verbose(`Websocket enabled: ${this.localWebsocket.enabled}`);
|
||||
@@ -406,7 +413,7 @@ export class ChannelStartupService {
|
||||
|
||||
public async setWebsocket(data: WebsocketRaw) {
|
||||
this.logger.verbose('Setting websocket');
|
||||
await this.repository.websocket.create(data, this.instanceName);
|
||||
await this.mongodbRepository.websocket.create(data, this.instanceName);
|
||||
this.logger.verbose(`Websocket events: ${data.events}`);
|
||||
Object.assign(this.localWebsocket, data);
|
||||
this.logger.verbose('Websocket set');
|
||||
@@ -414,7 +421,7 @@ export class ChannelStartupService {
|
||||
|
||||
public async findWebsocket() {
|
||||
this.logger.verbose('Finding websocket');
|
||||
const data = await this.repository.websocket.find(this.instanceName);
|
||||
const data = await this.mongodbRepository.websocket.find(this.instanceName);
|
||||
|
||||
if (!data) {
|
||||
this.logger.verbose('Websocket not found');
|
||||
@@ -430,7 +437,7 @@ export class ChannelStartupService {
|
||||
|
||||
public async loadRabbitmq() {
|
||||
this.logger.verbose('Loading rabbitmq');
|
||||
const data = await this.repository.rabbitmq.find(this.instanceName);
|
||||
const data = await this.mongodbRepository.rabbitmq.find(this.instanceName);
|
||||
|
||||
this.localRabbitmq.enabled = data?.enabled;
|
||||
this.logger.verbose(`Rabbitmq enabled: ${this.localRabbitmq.enabled}`);
|
||||
@@ -443,7 +450,7 @@ export class ChannelStartupService {
|
||||
|
||||
public async setRabbitmq(data: RabbitmqRaw) {
|
||||
this.logger.verbose('Setting rabbitmq');
|
||||
await this.repository.rabbitmq.create(data, this.instanceName);
|
||||
await this.mongodbRepository.rabbitmq.create(data, this.instanceName);
|
||||
this.logger.verbose(`Rabbitmq events: ${data.events}`);
|
||||
Object.assign(this.localRabbitmq, data);
|
||||
this.logger.verbose('Rabbitmq set');
|
||||
@@ -451,7 +458,7 @@ export class ChannelStartupService {
|
||||
|
||||
public async findRabbitmq() {
|
||||
this.logger.verbose('Finding rabbitmq');
|
||||
const data = await this.repository.rabbitmq.find(this.instanceName);
|
||||
const data = await this.mongodbRepository.rabbitmq.find(this.instanceName);
|
||||
|
||||
if (!data) {
|
||||
this.logger.verbose('Rabbitmq not found');
|
||||
@@ -475,7 +482,7 @@ export class ChannelStartupService {
|
||||
|
||||
public async loadSqs() {
|
||||
this.logger.verbose('Loading sqs');
|
||||
const data = await this.repository.sqs.find(this.instanceName);
|
||||
const data = await this.mongodbRepository.sqs.find(this.instanceName);
|
||||
|
||||
this.localSqs.enabled = data?.enabled;
|
||||
this.logger.verbose(`Sqs enabled: ${this.localSqs.enabled}`);
|
||||
@@ -488,7 +495,7 @@ export class ChannelStartupService {
|
||||
|
||||
public async setSqs(data: SqsRaw) {
|
||||
this.logger.verbose('Setting sqs');
|
||||
await this.repository.sqs.create(data, this.instanceName);
|
||||
await this.mongodbRepository.sqs.create(data, this.instanceName);
|
||||
this.logger.verbose(`Sqs events: ${data.events}`);
|
||||
Object.assign(this.localSqs, data);
|
||||
this.logger.verbose('Sqs set');
|
||||
@@ -496,7 +503,7 @@ export class ChannelStartupService {
|
||||
|
||||
public async findSqs() {
|
||||
this.logger.verbose('Finding sqs');
|
||||
const data = await this.repository.sqs.find(this.instanceName);
|
||||
const data = await this.mongodbRepository.sqs.find(this.instanceName);
|
||||
|
||||
if (!data) {
|
||||
this.logger.verbose('Sqs not found');
|
||||
@@ -520,7 +527,7 @@ export class ChannelStartupService {
|
||||
|
||||
public async loadTypebot() {
|
||||
this.logger.verbose('Loading typebot');
|
||||
const data = await this.repository.typebot.find(this.instanceName);
|
||||
const data = await this.mongodbRepository.typebot.find(this.instanceName);
|
||||
|
||||
this.localTypebot.enabled = data?.enabled;
|
||||
this.logger.verbose(`Typebot enabled: ${this.localTypebot.enabled}`);
|
||||
@@ -553,7 +560,7 @@ export class ChannelStartupService {
|
||||
|
||||
public async setTypebot(data: TypebotRaw) {
|
||||
this.logger.verbose('Setting typebot');
|
||||
await this.repository.typebot.create(data, this.instanceName);
|
||||
await this.mongodbRepository.typebot.create(data, this.instanceName);
|
||||
this.logger.verbose(`Typebot typebot: ${data.typebot}`);
|
||||
this.logger.verbose(`Typebot expire: ${data.expire}`);
|
||||
this.logger.verbose(`Typebot keyword_finish: ${data.keyword_finish}`);
|
||||
@@ -566,7 +573,7 @@ export class ChannelStartupService {
|
||||
|
||||
public async findTypebot() {
|
||||
this.logger.verbose('Finding typebot');
|
||||
const data = await this.repository.typebot.find(this.instanceName);
|
||||
const data = await this.mongodbRepository.typebot.find(this.instanceName);
|
||||
|
||||
if (!data) {
|
||||
this.logger.verbose('Typebot not found');
|
||||
@@ -588,7 +595,7 @@ export class ChannelStartupService {
|
||||
|
||||
public async loadProxy() {
|
||||
this.logger.verbose('Loading proxy');
|
||||
const data = await this.repository.proxy.find(this.instanceName);
|
||||
const data = await this.mongodbRepository.proxy.find(this.instanceName);
|
||||
|
||||
this.localProxy.enabled = data?.enabled;
|
||||
this.logger.verbose(`Proxy enabled: ${this.localProxy.enabled}`);
|
||||
@@ -601,7 +608,7 @@ export class ChannelStartupService {
|
||||
|
||||
public async setProxy(data: ProxyRaw) {
|
||||
this.logger.verbose('Setting proxy');
|
||||
await this.repository.proxy.create(data, this.instanceName);
|
||||
await this.mongodbRepository.proxy.create(data, this.instanceName);
|
||||
this.logger.verbose(`Proxy proxy: ${data.proxy}`);
|
||||
Object.assign(this.localProxy, data);
|
||||
this.logger.verbose('Proxy set');
|
||||
@@ -609,7 +616,7 @@ export class ChannelStartupService {
|
||||
|
||||
public async findProxy() {
|
||||
this.logger.verbose('Finding proxy');
|
||||
const data = await this.repository.proxy.find(this.instanceName);
|
||||
const data = await this.mongodbRepository.proxy.find(this.instanceName);
|
||||
|
||||
if (!data) {
|
||||
this.logger.verbose('Proxy not found');
|
||||
@@ -622,70 +629,6 @@ export class ChannelStartupService {
|
||||
};
|
||||
}
|
||||
|
||||
public async loadChamaai() {
|
||||
this.logger.verbose('Loading chamaai');
|
||||
const data = await this.repository.chamaai.find(this.instanceName);
|
||||
|
||||
this.localChamaai.enabled = data?.enabled;
|
||||
this.logger.verbose(`Chamaai enabled: ${this.localChamaai.enabled}`);
|
||||
|
||||
this.localChamaai.url = data?.url;
|
||||
this.logger.verbose(`Chamaai url: ${this.localChamaai.url}`);
|
||||
|
||||
this.localChamaai.token = data?.token;
|
||||
this.logger.verbose(`Chamaai token: ${this.localChamaai.token}`);
|
||||
|
||||
this.localChamaai.waNumber = data?.waNumber;
|
||||
this.logger.verbose(`Chamaai waNumber: ${this.localChamaai.waNumber}`);
|
||||
|
||||
this.localChamaai.answerByAudio = data?.answerByAudio;
|
||||
this.logger.verbose(`Chamaai answerByAudio: ${this.localChamaai.answerByAudio}`);
|
||||
|
||||
this.logger.verbose('Chamaai loaded');
|
||||
}
|
||||
|
||||
public async setChamaai(data: ChamaaiRaw) {
|
||||
this.logger.verbose('Setting chamaai');
|
||||
await this.repository.chamaai.create(data, this.instanceName);
|
||||
this.logger.verbose(`Chamaai url: ${data.url}`);
|
||||
this.logger.verbose(`Chamaai token: ${data.token}`);
|
||||
this.logger.verbose(`Chamaai waNumber: ${data.waNumber}`);
|
||||
this.logger.verbose(`Chamaai answerByAudio: ${data.answerByAudio}`);
|
||||
|
||||
Object.assign(this.localChamaai, data);
|
||||
this.logger.verbose('Chamaai set');
|
||||
}
|
||||
|
||||
public async findChamaai() {
|
||||
this.logger.verbose('Finding chamaai');
|
||||
const data = await this.repository.chamaai.find(this.instanceName);
|
||||
|
||||
if (!data) {
|
||||
this.logger.verbose('Chamaai not found');
|
||||
throw new NotFoundException('Chamaai not found');
|
||||
}
|
||||
|
||||
return {
|
||||
enabled: data.enabled,
|
||||
url: data.url,
|
||||
token: data.token,
|
||||
waNumber: data.waNumber,
|
||||
answerByAudio: data.answerByAudio,
|
||||
};
|
||||
}
|
||||
|
||||
private assertExchangeAsync = (channel, exchangeName, exchangeType, options) => {
|
||||
return new Promise((resolve, reject) => {
|
||||
channel.assertExchange(exchangeName, exchangeType, options, (error, ok) => {
|
||||
if (error) {
|
||||
reject(error);
|
||||
} else {
|
||||
resolve(ok);
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
public async sendDataWebhook<T = any>(event: Events, data: T, local = true) {
|
||||
const webhookGlobal = this.configService.get<Webhook>('WEBHOOK');
|
||||
const webhookLocal = this.localWebhook.events;
|
||||
@@ -703,7 +646,7 @@ export class ChannelStartupService {
|
||||
const now = localISOTime;
|
||||
|
||||
const expose = this.configService.get<Auth>('AUTHENTICATION').EXPOSE_IN_FETCH_INSTANCES;
|
||||
const tokenStore = await this.repository.auth.find(this.instanceName);
|
||||
const tokenStore = await this.mongodbRepository.auth.find(this.instanceName);
|
||||
const instanceApikey = tokenStore?.apikey || 'Apikey not found';
|
||||
|
||||
if (rabbitmqEnabled) {
|
||||
@@ -1238,7 +1181,7 @@ export class ChannelStartupService {
|
||||
},
|
||||
};
|
||||
}
|
||||
return await this.repository.contact.find(query);
|
||||
return await this.mongodbRepository.contact.find(query);
|
||||
}
|
||||
|
||||
public async fetchMessages(query: MessageQuery) {
|
||||
@@ -1256,7 +1199,7 @@ export class ChannelStartupService {
|
||||
limit: query?.limit,
|
||||
};
|
||||
}
|
||||
return await this.repository.message.find(query);
|
||||
return await this.mongodbRepository.message.find(query);
|
||||
}
|
||||
|
||||
public async fetchStatusMessage(query: MessageUpQuery) {
|
||||
@@ -1274,11 +1217,11 @@ export class ChannelStartupService {
|
||||
limit: query?.limit,
|
||||
};
|
||||
}
|
||||
return await this.repository.messageUpdate.find(query);
|
||||
return await this.mongodbRepository.messageUpdate.find(query);
|
||||
}
|
||||
|
||||
public async fetchChats() {
|
||||
this.logger.verbose('Fetching chats');
|
||||
return await this.repository.chat.find({ where: { owner: this.instance.name } });
|
||||
return await this.mongodbRepository.chat.find({ where: { owner: this.instance.name } });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -68,9 +68,10 @@ import {
|
||||
} from '../../../config/env.config';
|
||||
import { INSTANCE_DIR } from '../../../config/path.config';
|
||||
import { BadRequestException, InternalServerErrorException, NotFoundException } from '../../../exceptions';
|
||||
import { dbserver } from '../../../libs/db.connect';
|
||||
import { mongodbServer } from '../../../libs/mongodb.connect';
|
||||
import { makeProxyAgent } from '../../../utils/makeProxyAgent';
|
||||
import { useMultiFileAuthStateDb } from '../../../utils/use-multi-file-auth-state-db';
|
||||
import { useMultiFileAuthStateMongoDb } from '../../../utils/use-multi-file-auth-state-mongodb';
|
||||
import useMultiFileAuthStatePrisma from '../../../utils/use-multi-file-auth-state-prisma';
|
||||
import { AuthStateProvider } from '../../../utils/use-multi-file-auth-state-provider-files';
|
||||
import { useMultiFileAuthStateRedisDb } from '../../../utils/use-multi-file-auth-state-redis-db';
|
||||
import {
|
||||
@@ -126,7 +127,8 @@ import { ChatRaw } from '../../models/chat.model';
|
||||
import { ContactRaw } from '../../models/contact.model';
|
||||
import { MessageRaw, MessageUpdateRaw } from '../../models/message.model';
|
||||
import { ProviderFiles } from '../../provider/sessions';
|
||||
import { RepositoryBroker } from '../../repository/repository.manager';
|
||||
import { MongodbRepository } from '../../repository/mongodb/repository.manager';
|
||||
import { PrismaRepository } from '../../repository/prisma/repository.service';
|
||||
import { waMonitor } from '../../server.module';
|
||||
import { Events, MessageSubtype, TypeMediaMessage, wa } from '../../types/wa.types';
|
||||
import { CacheService } from './../cache.service';
|
||||
@@ -138,13 +140,14 @@ export class BaileysStartupService extends ChannelStartupService {
|
||||
constructor(
|
||||
public readonly configService: ConfigService,
|
||||
public readonly eventEmitter: EventEmitter2,
|
||||
public readonly repository: RepositoryBroker,
|
||||
public readonly mongoRepository: MongodbRepository,
|
||||
public readonly prismaRepository: PrismaRepository,
|
||||
public readonly cache: CacheService,
|
||||
public readonly chatwootCache: CacheService,
|
||||
public readonly baileysCache: CacheService,
|
||||
private readonly providerFiles: ProviderFiles,
|
||||
) {
|
||||
super(configService, eventEmitter, repository, chatwootCache);
|
||||
super(configService, eventEmitter, mongoRepository, prismaRepository, chatwootCache);
|
||||
this.logger.verbose('BaileysStartupService initialized');
|
||||
this.cleanStore();
|
||||
this.instance.qrcode = { count: 0 };
|
||||
@@ -224,7 +227,7 @@ export class BaileysStartupService extends ChannelStartupService {
|
||||
this.logger.verbose('Profile name not found, trying to get from database');
|
||||
if (this.configService.get<Database>('DATABASE').ENABLED) {
|
||||
this.logger.verbose('Database enabled, trying to get from database');
|
||||
const collection = dbserver
|
||||
const collection = mongodbServer
|
||||
.getClient()
|
||||
.db(this.configService.get<Database>('DATABASE').CONNECTION.DB_PREFIX_NAME + '-instances')
|
||||
.collection(this.instanceName);
|
||||
@@ -460,7 +463,7 @@ export class BaileysStartupService extends ChannelStartupService {
|
||||
private async getMessage(key: proto.IMessageKey, full = false) {
|
||||
this.logger.verbose('Getting message with key: ' + JSON.stringify(key));
|
||||
try {
|
||||
const webMessageInfo = (await this.repository.message.find({
|
||||
const webMessageInfo = (await this.mongodbRepository.message.find({
|
||||
where: { owner: this.instance.name, key: { id: key.id } },
|
||||
})) as unknown as proto.IWebMessageInfo[];
|
||||
if (full) {
|
||||
@@ -510,7 +513,8 @@ export class BaileysStartupService extends ChannelStartupService {
|
||||
|
||||
if (db.SAVE_DATA.INSTANCE && db.ENABLED) {
|
||||
this.logger.verbose('Database enabled');
|
||||
return await useMultiFileAuthStateDb(this.instance.name);
|
||||
if (db.PROVIDER === 'mongodb') return await useMultiFileAuthStateMongoDb(this.instance.name);
|
||||
else return await useMultiFileAuthStatePrisma(this.instance.name);
|
||||
}
|
||||
|
||||
this.logger.verbose('Store file enabled');
|
||||
@@ -528,7 +532,6 @@ export class BaileysStartupService extends ChannelStartupService {
|
||||
this.loadSqs();
|
||||
this.loadTypebot();
|
||||
this.loadProxy();
|
||||
this.loadChamaai();
|
||||
|
||||
this.instance.authState = await this.defineAuthState();
|
||||
|
||||
@@ -827,7 +830,7 @@ export class BaileysStartupService extends ChannelStartupService {
|
||||
this.logger.verbose('Event received: chats.upsert');
|
||||
|
||||
this.logger.verbose('Finding chats in database');
|
||||
const chatsRepository = await this.repository.chat.find({
|
||||
const chatsRepository = await this.mongodbRepository.chat.find({
|
||||
where: { owner: this.instance.name },
|
||||
});
|
||||
|
||||
@@ -845,7 +848,7 @@ export class BaileysStartupService extends ChannelStartupService {
|
||||
this.sendDataWebhook(Events.CHATS_UPSERT, chatsRaw);
|
||||
|
||||
this.logger.verbose('Inserting chats in database');
|
||||
this.repository.chat.insert(chatsRaw, this.instance.name, database.SAVE_DATA.CHATS);
|
||||
this.mongodbRepository.chat.insert(chatsRaw, this.instance.name, database.SAVE_DATA.CHATS);
|
||||
},
|
||||
|
||||
'chats.update': async (
|
||||
@@ -872,7 +875,7 @@ export class BaileysStartupService extends ChannelStartupService {
|
||||
this.logger.verbose('Deleting chats in database');
|
||||
chats.forEach(
|
||||
async (chat) =>
|
||||
await this.repository.chat.delete({
|
||||
await this.mongodbRepository.chat.delete({
|
||||
where: { owner: this.instance.name, id: chat },
|
||||
}),
|
||||
);
|
||||
@@ -890,7 +893,7 @@ export class BaileysStartupService extends ChannelStartupService {
|
||||
this.logger.verbose('Finding contacts in database');
|
||||
const contactsRepository = new Set(
|
||||
(
|
||||
await this.repository.contact.find({
|
||||
await this.mongodbRepository.contact.find({
|
||||
select: { id: 1, _id: 0 },
|
||||
where: { owner: this.instance.name },
|
||||
})
|
||||
@@ -917,7 +920,7 @@ export class BaileysStartupService extends ChannelStartupService {
|
||||
if (contactsRaw.length > 0) this.sendDataWebhook(Events.CONTACTS_UPSERT, contactsRaw);
|
||||
|
||||
this.logger.verbose('Inserting contacts in database');
|
||||
this.repository.contact.insert(contactsRaw, this.instance.name, database.SAVE_DATA.CONTACTS);
|
||||
this.mongodbRepository.contact.insert(contactsRaw, this.instance.name, database.SAVE_DATA.CONTACTS);
|
||||
|
||||
if (this.localChatwoot.enabled && this.localChatwoot.import_contacts && contactsRaw.length) {
|
||||
this.chatwootService.addHistoryContacts({ instanceName: this.instance.name }, contactsRaw);
|
||||
@@ -939,7 +942,7 @@ export class BaileysStartupService extends ChannelStartupService {
|
||||
if (contactsRaw.length > 0) this.sendDataWebhook(Events.CONTACTS_UPSERT, contactsRaw);
|
||||
|
||||
this.logger.verbose('Updating contacts in database');
|
||||
this.repository.contact.update(contactsRaw, this.instance.name, database.SAVE_DATA.CONTACTS);
|
||||
this.mongodbRepository.contact.update(contactsRaw, this.instance.name, database.SAVE_DATA.CONTACTS);
|
||||
} catch (error) {
|
||||
this.logger.error(error);
|
||||
}
|
||||
@@ -963,7 +966,7 @@ export class BaileysStartupService extends ChannelStartupService {
|
||||
this.sendDataWebhook(Events.CONTACTS_UPDATE, contactsRaw);
|
||||
|
||||
this.logger.verbose('Updating contacts in database');
|
||||
this.repository.contact.update(contactsRaw, this.instance.name, database.SAVE_DATA.CONTACTS);
|
||||
this.mongodbRepository.contact.update(contactsRaw, this.instance.name, database.SAVE_DATA.CONTACTS);
|
||||
},
|
||||
};
|
||||
|
||||
@@ -1004,7 +1007,7 @@ export class BaileysStartupService extends ChannelStartupService {
|
||||
const chatsRaw: ChatRaw[] = [];
|
||||
const chatsRepository = new Set(
|
||||
(
|
||||
await this.repository.chat.find({
|
||||
await this.mongodbRepository.chat.find({
|
||||
select: { id: 1, _id: 0 },
|
||||
where: { owner: this.instance.name },
|
||||
})
|
||||
@@ -1027,13 +1030,13 @@ export class BaileysStartupService extends ChannelStartupService {
|
||||
this.sendDataWebhook(Events.CHATS_SET, chatsRaw);
|
||||
|
||||
this.logger.verbose('Inserting chats in database');
|
||||
this.repository.chat.insert(chatsRaw, this.instance.name, database.SAVE_DATA.CHATS);
|
||||
this.mongodbRepository.chat.insert(chatsRaw, this.instance.name, database.SAVE_DATA.CHATS);
|
||||
|
||||
const messagesRaw: MessageRaw[] = [];
|
||||
const messagesRepository = new Set(
|
||||
chatwootImport.getRepositoryMessagesCache(instance) ??
|
||||
(
|
||||
await this.repository.message.find({
|
||||
await this.mongodbRepository.message.find({
|
||||
select: { key: { id: 1 }, _id: 0 },
|
||||
where: { owner: this.instance.name },
|
||||
})
|
||||
@@ -1086,7 +1089,7 @@ export class BaileysStartupService extends ChannelStartupService {
|
||||
this.sendDataWebhook(Events.MESSAGES_SET, [...messagesRaw]);
|
||||
|
||||
this.logger.verbose('Inserting messages in database');
|
||||
await this.repository.message.insert(messagesRaw, this.instance.name, database.SAVE_DATA.NEW_MESSAGE);
|
||||
await this.mongodbRepository.message.insert(messagesRaw, this.instance.name, database.SAVE_DATA.NEW_MESSAGE);
|
||||
|
||||
if (this.localChatwoot.enabled && this.localChatwoot.import_messages && messagesRaw.length > 0) {
|
||||
this.chatwootService.addHistoryMessages(
|
||||
@@ -1262,19 +1265,11 @@ export class BaileysStartupService extends ChannelStartupService {
|
||||
}
|
||||
}
|
||||
|
||||
if (this.localChamaai.enabled && messageRaw.key.fromMe === false && type === 'notify') {
|
||||
await this.chamaaiService.sendChamaai(
|
||||
{ instanceName: this.instance.name },
|
||||
messageRaw.key.remoteJid,
|
||||
messageRaw,
|
||||
);
|
||||
}
|
||||
|
||||
this.logger.verbose('Inserting message in database');
|
||||
await this.repository.message.insert([messageRaw], this.instance.name, database.SAVE_DATA.NEW_MESSAGE);
|
||||
await this.mongodbRepository.message.insert([messageRaw], this.instance.name, database.SAVE_DATA.NEW_MESSAGE);
|
||||
|
||||
this.logger.verbose('Verifying contact from message');
|
||||
const contact = await this.repository.contact.find({
|
||||
const contact = await this.mongodbRepository.contact.find({
|
||||
where: { owner: this.instance.name, id: received.key.remoteJid },
|
||||
});
|
||||
|
||||
@@ -1311,7 +1306,7 @@ export class BaileysStartupService extends ChannelStartupService {
|
||||
}
|
||||
|
||||
this.logger.verbose('Updating contact in database');
|
||||
await this.repository.contact.update([contactRaw], this.instance.name, database.SAVE_DATA.CONTACTS);
|
||||
await this.mongodbRepository.contact.update([contactRaw], this.instance.name, database.SAVE_DATA.CONTACTS);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1321,7 +1316,7 @@ export class BaileysStartupService extends ChannelStartupService {
|
||||
this.sendDataWebhook(Events.CONTACTS_UPSERT, contactRaw);
|
||||
|
||||
this.logger.verbose('Inserting contact in database');
|
||||
this.repository.contact.insert([contactRaw], this.instance.name, database.SAVE_DATA.CONTACTS);
|
||||
this.mongodbRepository.contact.insert([contactRaw], this.instance.name, database.SAVE_DATA.CONTACTS);
|
||||
}
|
||||
} catch (error) {
|
||||
this.logger.error(error);
|
||||
@@ -1388,7 +1383,7 @@ export class BaileysStartupService extends ChannelStartupService {
|
||||
this.logger.verbose(message);
|
||||
|
||||
this.logger.verbose('Inserting message in database');
|
||||
await this.repository.messageUpdate.insert(
|
||||
await this.mongodbRepository.messageUpdate.insert(
|
||||
[message],
|
||||
this.instance.name,
|
||||
database.SAVE_DATA.MESSAGE_UPDATE,
|
||||
@@ -1419,7 +1414,7 @@ export class BaileysStartupService extends ChannelStartupService {
|
||||
this.sendDataWebhook(Events.MESSAGES_UPDATE, message);
|
||||
|
||||
this.logger.verbose('Inserting message in database');
|
||||
this.repository.messageUpdate.insert([message], this.instance.name, database.SAVE_DATA.MESSAGE_UPDATE);
|
||||
this.mongodbRepository.messageUpdate.insert([message], this.instance.name, database.SAVE_DATA.MESSAGE_UPDATE);
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -1462,14 +1457,14 @@ export class BaileysStartupService extends ChannelStartupService {
|
||||
[Events.LABELS_EDIT]: async (label: Label, database: Database) => {
|
||||
this.logger.verbose('Event received: labels.edit');
|
||||
this.logger.verbose('Finding labels in database');
|
||||
const labelsRepository = await this.repository.labels.find({
|
||||
const labelsRepository = await this.mongodbRepository.labels.find({
|
||||
where: { owner: this.instance.name },
|
||||
});
|
||||
|
||||
const savedLabel = labelsRepository.find((l) => l.id === label.id);
|
||||
if (label.deleted && savedLabel) {
|
||||
this.logger.verbose('Sending data to webhook in event LABELS_EDIT');
|
||||
await this.repository.labels.delete({
|
||||
await this.mongodbRepository.labels.delete({
|
||||
where: { owner: this.instance.name, id: label.id },
|
||||
});
|
||||
this.sendDataWebhook(Events.LABELS_EDIT, { ...label, instance: this.instance.name });
|
||||
@@ -1479,7 +1474,7 @@ export class BaileysStartupService extends ChannelStartupService {
|
||||
const labelName = label.name.replace(/[^\x20-\x7E]/g, '');
|
||||
if (!savedLabel || savedLabel.color !== label.color || savedLabel.name !== labelName) {
|
||||
this.logger.verbose('Sending data to webhook in event LABELS_EDIT');
|
||||
await this.repository.labels.insert(
|
||||
await this.mongodbRepository.labels.insert(
|
||||
{
|
||||
color: label.color,
|
||||
name: labelName,
|
||||
@@ -1502,7 +1497,7 @@ export class BaileysStartupService extends ChannelStartupService {
|
||||
|
||||
// Atualiza labels nos chats
|
||||
if (database.ENABLED && database.SAVE_DATA.CHATS) {
|
||||
const chats = await this.repository.chat.find({
|
||||
const chats = await this.mongodbRepository.chat.find({
|
||||
where: {
|
||||
owner: this.instance.name,
|
||||
},
|
||||
@@ -1515,7 +1510,7 @@ export class BaileysStartupService extends ChannelStartupService {
|
||||
} else if (data.type === 'add') {
|
||||
labels = [...labels, data.association.labelId];
|
||||
}
|
||||
await this.repository.chat.update(
|
||||
await this.mongodbRepository.chat.update(
|
||||
[{ id: chat.id, owner: this.instance.name, labels }],
|
||||
this.instance.name,
|
||||
database.SAVE_DATA.CHATS,
|
||||
@@ -2041,7 +2036,7 @@ export class BaileysStartupService extends ChannelStartupService {
|
||||
}
|
||||
|
||||
this.logger.verbose('Inserting message in database');
|
||||
await this.repository.message.insert(
|
||||
await this.mongodbRepository.message.insert(
|
||||
[messageRaw],
|
||||
this.instance.name,
|
||||
this.configService.get<Database>('DATABASE').SAVE_DATA.NEW_MESSAGE,
|
||||
@@ -2160,7 +2155,7 @@ export class BaileysStartupService extends ChannelStartupService {
|
||||
this.logger.verbose('All contacts defined as true');
|
||||
|
||||
this.logger.verbose('Getting contacts from database');
|
||||
const contacts = await this.repository.contact.find({
|
||||
const contacts = await this.mongodbRepository.contact.find({
|
||||
where: { owner: this.instance.name },
|
||||
});
|
||||
|
||||
@@ -2686,7 +2681,7 @@ export class BaileysStartupService extends ChannelStartupService {
|
||||
onWhatsapp.push(...groups);
|
||||
|
||||
// USERS
|
||||
const contacts: ContactRaw[] = await this.repository.contact.findManyById({
|
||||
const contacts: ContactRaw[] = await this.mongodbRepository.contact.findManyById({
|
||||
owner: this.instance.name,
|
||||
ids: jids.users.map(({ jid }) => (jid.startsWith('+') ? jid.substring(1) : jid)),
|
||||
});
|
||||
@@ -3177,7 +3172,7 @@ export class BaileysStartupService extends ChannelStartupService {
|
||||
|
||||
public async fetchLabels(): Promise<LabelDto[]> {
|
||||
this.logger.verbose('Fetching labels');
|
||||
const labels = await this.repository.labels.find({
|
||||
const labels = await this.mongodbRepository.labels.find({
|
||||
where: {
|
||||
owner: this.instance.name,
|
||||
},
|
||||
@@ -3485,7 +3480,7 @@ export class BaileysStartupService extends ChannelStartupService {
|
||||
this.logger.verbose('Fetching participants for group: ' + id.groupJid);
|
||||
try {
|
||||
const participants = (await this.client.groupMetadata(id.groupJid)).participants;
|
||||
const contacts = await this.repository.contact.findManyById({
|
||||
const contacts = await this.mongodbRepository.contact.findManyById({
|
||||
owner: this.instance.name,
|
||||
ids: participants.map((p) => p.id),
|
||||
});
|
||||
|
||||
@@ -24,7 +24,8 @@ import {
|
||||
} from '../../dto/sendMessage.dto';
|
||||
import { ContactRaw, MessageRaw, MessageUpdateRaw, SettingsRaw } from '../../models';
|
||||
import { ProviderFiles } from '../../provider/sessions';
|
||||
import { RepositoryBroker } from '../../repository/repository.manager';
|
||||
import { MongodbRepository } from '../../repository/mongodb/repository.manager';
|
||||
import { PrismaRepository } from '../../repository/prisma/repository.service';
|
||||
import { Events, wa } from '../../types/wa.types';
|
||||
import { CacheService } from './../cache.service';
|
||||
import { ChannelStartupService } from './../channel.service';
|
||||
@@ -33,13 +34,14 @@ export class BusinessStartupService extends ChannelStartupService {
|
||||
constructor(
|
||||
public readonly configService: ConfigService,
|
||||
public readonly eventEmitter: EventEmitter2,
|
||||
public readonly repository: RepositoryBroker,
|
||||
public readonly mongodbRepository: MongodbRepository,
|
||||
public readonly prismaRepository: PrismaRepository,
|
||||
public readonly cache: CacheService,
|
||||
public readonly chatwootCache: CacheService,
|
||||
public readonly baileysCache: CacheService,
|
||||
private readonly providerFiles: ProviderFiles,
|
||||
) {
|
||||
super(configService, eventEmitter, repository, chatwootCache);
|
||||
super(configService, eventEmitter, mongodbRepository, prismaRepository, chatwootCache);
|
||||
this.logger.verbose('BusinessStartupService initialized');
|
||||
this.cleanStore();
|
||||
}
|
||||
@@ -146,7 +148,6 @@ export class BusinessStartupService extends ChannelStartupService {
|
||||
this.loadRabbitmq();
|
||||
this.loadSqs();
|
||||
this.loadTypebot();
|
||||
this.loadChamaai();
|
||||
|
||||
this.logger.verbose('Creating socket');
|
||||
|
||||
@@ -442,19 +443,11 @@ export class BusinessStartupService extends ChannelStartupService {
|
||||
}
|
||||
}
|
||||
|
||||
if (this.localChamaai.enabled && messageRaw.key.fromMe === false && received?.message.type === 'notify') {
|
||||
await this.chamaaiService.sendChamaai(
|
||||
{ instanceName: this.instance.name },
|
||||
messageRaw.key.remoteJid,
|
||||
messageRaw,
|
||||
);
|
||||
}
|
||||
|
||||
this.logger.verbose('Inserting message in database');
|
||||
await this.repository.message.insert([messageRaw], this.instance.name, database.SAVE_DATA.NEW_MESSAGE);
|
||||
await this.mongodbRepository.message.insert([messageRaw], this.instance.name, database.SAVE_DATA.NEW_MESSAGE);
|
||||
|
||||
this.logger.verbose('Verifying contact from message');
|
||||
const contact = await this.repository.contact.find({
|
||||
const contact = await this.mongodbRepository.contact.find({
|
||||
where: { owner: this.instance.name, id: key.remoteJid },
|
||||
});
|
||||
|
||||
@@ -491,7 +484,7 @@ export class BusinessStartupService extends ChannelStartupService {
|
||||
}
|
||||
|
||||
this.logger.verbose('Updating contact in database');
|
||||
await this.repository.contact.update([contactRaw], this.instance.name, database.SAVE_DATA.CONTACTS);
|
||||
await this.mongodbRepository.contact.update([contactRaw], this.instance.name, database.SAVE_DATA.CONTACTS);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -501,7 +494,7 @@ export class BusinessStartupService extends ChannelStartupService {
|
||||
this.sendDataWebhook(Events.CONTACTS_UPSERT, contactRaw);
|
||||
|
||||
this.logger.verbose('Inserting contact in database');
|
||||
this.repository.contact.insert([contactRaw], this.instance.name, database.SAVE_DATA.CONTACTS);
|
||||
this.mongodbRepository.contact.insert([contactRaw], this.instance.name, database.SAVE_DATA.CONTACTS);
|
||||
}
|
||||
this.logger.verbose('Event received: messages.update');
|
||||
if (received.statuses) {
|
||||
@@ -536,7 +529,7 @@ export class BusinessStartupService extends ChannelStartupService {
|
||||
this.logger.verbose(message);
|
||||
|
||||
this.logger.verbose('Inserting message in database');
|
||||
await this.repository.messageUpdate.insert(
|
||||
await this.mongodbRepository.messageUpdate.insert(
|
||||
[message],
|
||||
this.instance.name,
|
||||
database.SAVE_DATA.MESSAGE_UPDATE,
|
||||
@@ -566,7 +559,11 @@ export class BusinessStartupService extends ChannelStartupService {
|
||||
this.sendDataWebhook(Events.MESSAGES_UPDATE, message);
|
||||
|
||||
this.logger.verbose('Inserting message in database');
|
||||
this.repository.messageUpdate.insert([message], this.instance.name, database.SAVE_DATA.MESSAGE_UPDATE);
|
||||
this.mongodbRepository.messageUpdate.insert(
|
||||
[message],
|
||||
this.instance.name,
|
||||
database.SAVE_DATA.MESSAGE_UPDATE,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -871,7 +868,7 @@ export class BusinessStartupService extends ChannelStartupService {
|
||||
}
|
||||
|
||||
this.logger.verbose('Inserting message in database');
|
||||
await this.repository.message.insert(
|
||||
await this.mongodbRepository.message.insert(
|
||||
[messageRaw],
|
||||
this.instance.name,
|
||||
this.configService.get<Database>('DATABASE').SAVE_DATA.NEW_MESSAGE,
|
||||
|
||||
@@ -19,7 +19,6 @@ import { INSTANCE_DIR, STORE_DIR } from '../../config/path.config';
|
||||
import { NotFoundException } from '../../exceptions';
|
||||
import {
|
||||
AuthModel,
|
||||
ChamaaiModel,
|
||||
ChatwootModel,
|
||||
ContactModel,
|
||||
LabelModel,
|
||||
@@ -31,7 +30,8 @@ import {
|
||||
WebsocketModel,
|
||||
} from '../models';
|
||||
import { ProviderFiles } from '../provider/sessions';
|
||||
import { RepositoryBroker } from '../repository/repository.manager';
|
||||
import { MongodbRepository } from '../repository/mongodb/repository.manager';
|
||||
import { PrismaRepository } from '../repository/prisma/repository.service';
|
||||
import { Integration } from '../types/wa.types';
|
||||
import { CacheService } from './cache.service';
|
||||
import { BaileysStartupService } from './channels/whatsapp.baileys.service';
|
||||
@@ -41,7 +41,8 @@ export class WAMonitoringService {
|
||||
constructor(
|
||||
private readonly eventEmitter: EventEmitter2,
|
||||
private readonly configService: ConfigService,
|
||||
private readonly repository: RepositoryBroker,
|
||||
private readonly monogodbRepository: MongodbRepository,
|
||||
private readonly primaRepository: PrismaRepository,
|
||||
private readonly cache: CacheService,
|
||||
private readonly chatwootCache: CacheService,
|
||||
private readonly baileysCache: CacheService,
|
||||
@@ -56,7 +57,7 @@ export class WAMonitoringService {
|
||||
Object.assign(this.redis, configService.get<CacheConf>('CACHE'));
|
||||
|
||||
this.dbInstance = this.db.ENABLED
|
||||
? this.repository.dbServer?.db(this.db.CONNECTION.DB_PREFIX_NAME + '-instances')
|
||||
? this.monogodbRepository.mongodbServer?.db(this.db.CONNECTION.DB_PREFIX_NAME + '-instances')
|
||||
: undefined;
|
||||
}
|
||||
|
||||
@@ -135,7 +136,7 @@ export class WAMonitoringService {
|
||||
const instanceData = {
|
||||
instance: {
|
||||
instanceName: key,
|
||||
instanceId: (await this.repository.auth.find(key))?.instanceId,
|
||||
instanceId: (await this.monogodbRepository.auth.find(key))?.instanceId,
|
||||
owner: value.wuid,
|
||||
profileName: (await value.getProfileName()) || 'not loaded',
|
||||
profilePictureUrl: value.profilePictureUrl,
|
||||
@@ -147,7 +148,7 @@ export class WAMonitoringService {
|
||||
if (this.configService.get<Auth>('AUTHENTICATION').EXPOSE_IN_FETCH_INSTANCES) {
|
||||
instanceData.instance['serverUrl'] = this.configService.get<HttpServer>('SERVER').URL;
|
||||
|
||||
instanceData.instance['apikey'] = (await this.repository.auth.find(key))?.apikey;
|
||||
instanceData.instance['apikey'] = (await this.monogodbRepository.auth.find(key))?.apikey;
|
||||
|
||||
instanceData.instance['chatwoot'] = chatwoot;
|
||||
|
||||
@@ -161,7 +162,7 @@ export class WAMonitoringService {
|
||||
const instanceData = {
|
||||
instance: {
|
||||
instanceName: key,
|
||||
instanceId: (await this.repository.auth.find(key))?.instanceId,
|
||||
instanceId: (await this.monogodbRepository.auth.find(key))?.instanceId,
|
||||
status: value.connectionStatus.state,
|
||||
},
|
||||
};
|
||||
@@ -169,7 +170,7 @@ export class WAMonitoringService {
|
||||
if (this.configService.get<Auth>('AUTHENTICATION').EXPOSE_IN_FETCH_INSTANCES) {
|
||||
instanceData.instance['serverUrl'] = this.configService.get<HttpServer>('SERVER').URL;
|
||||
|
||||
instanceData.instance['apikey'] = (await this.repository.auth.find(key))?.apikey;
|
||||
instanceData.instance['apikey'] = (await this.monogodbRepository.auth.find(key))?.apikey;
|
||||
|
||||
instanceData.instance['chatwoot'] = chatwoot;
|
||||
|
||||
@@ -193,12 +194,12 @@ export class WAMonitoringService {
|
||||
this.logger.verbose('get instance info');
|
||||
let instanceName: string;
|
||||
if (instanceId) {
|
||||
instanceName = await this.repository.auth.findInstanceNameById(instanceId);
|
||||
instanceName = await this.monogodbRepository.auth.findInstanceNameById(instanceId);
|
||||
if (!instanceName) {
|
||||
throw new NotFoundException(`Instance "${instanceId}" not found`);
|
||||
}
|
||||
} else if (number) {
|
||||
instanceName = await this.repository.auth.findInstanceNameByNumber(number);
|
||||
instanceName = await this.monogodbRepository.auth.findInstanceNameByNumber(number);
|
||||
if (!instanceName) {
|
||||
throw new NotFoundException(`Instance "${number}" not found`);
|
||||
}
|
||||
@@ -254,7 +255,7 @@ export class WAMonitoringService {
|
||||
|
||||
if (this.db.ENABLED && this.db.SAVE_DATA.INSTANCE) {
|
||||
this.logger.verbose('cleaning up instance in database: ' + instanceName);
|
||||
await this.repository.dbServer.connect();
|
||||
await this.monogodbRepository.mongodbServer.connect();
|
||||
const collections: any[] = await this.dbInstance.collections();
|
||||
if (collections.length > 0) {
|
||||
await this.dbInstance.dropCollection(instanceName);
|
||||
@@ -291,7 +292,6 @@ export class WAMonitoringService {
|
||||
execSync(`rm -rf ${join(STORE_DIR, 'auth', 'apikey', instanceName + '.json')}`);
|
||||
execSync(`rm -rf ${join(STORE_DIR, 'webhook', instanceName + '.json')}`);
|
||||
execSync(`rm -rf ${join(STORE_DIR, 'chatwoot', instanceName + '*')}`);
|
||||
execSync(`rm -rf ${join(STORE_DIR, 'chamaai', instanceName + '*')}`);
|
||||
execSync(`rm -rf ${join(STORE_DIR, 'proxy', instanceName + '*')}`);
|
||||
execSync(`rm -rf ${join(STORE_DIR, 'rabbitmq', instanceName + '*')}`);
|
||||
execSync(`rm -rf ${join(STORE_DIR, 'typebot', instanceName + '*')}`);
|
||||
@@ -307,7 +307,6 @@ export class WAMonitoringService {
|
||||
await AuthModel.deleteMany({ _id: instanceName });
|
||||
await WebhookModel.deleteMany({ _id: instanceName });
|
||||
await ChatwootModel.deleteMany({ _id: instanceName });
|
||||
await ChamaaiModel.deleteMany({ _id: instanceName });
|
||||
await ProxyModel.deleteMany({ _id: instanceName });
|
||||
await RabbitmqModel.deleteMany({ _id: instanceName });
|
||||
await TypebotModel.deleteMany({ _id: instanceName });
|
||||
@@ -328,7 +327,8 @@ export class WAMonitoringService {
|
||||
} 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();
|
||||
if (this.db.PROVIDER === 'mongodb') await this.loadInstancesFromDatabaseMongoDB();
|
||||
else if (this.db.PROVIDER === 'postgresql') await this.loadInstancesFromDatabasePostgres();
|
||||
} else {
|
||||
await this.loadInstancesFromFiles();
|
||||
}
|
||||
@@ -343,7 +343,7 @@ export class WAMonitoringService {
|
||||
try {
|
||||
const msgParsed = JSON.parse(JSON.stringify(data));
|
||||
if (this.db.ENABLED && this.db.SAVE_DATA.INSTANCE) {
|
||||
await this.repository.dbServer.connect();
|
||||
await this.monogodbRepository.mongodbServer.connect();
|
||||
await this.dbInstance.collection(data.instanceName).replaceOne({ _id: 'integration' }, msgParsed, {
|
||||
upsert: true,
|
||||
});
|
||||
@@ -358,14 +358,15 @@ export class WAMonitoringService {
|
||||
}
|
||||
|
||||
private async setInstance(name: string) {
|
||||
const integration = await this.repository.integration.find(name);
|
||||
const integration = await this.monogodbRepository.integration.find(name);
|
||||
|
||||
let instance: BaileysStartupService | BusinessStartupService;
|
||||
if (integration && integration.integration === Integration.WHATSAPP_BUSINESS) {
|
||||
instance = new BusinessStartupService(
|
||||
this.configService,
|
||||
this.eventEmitter,
|
||||
this.repository,
|
||||
this.monogodbRepository,
|
||||
this.primaRepository,
|
||||
this.cache,
|
||||
this.chatwootCache,
|
||||
this.baileysCache,
|
||||
@@ -377,7 +378,8 @@ export class WAMonitoringService {
|
||||
instance = new BaileysStartupService(
|
||||
this.configService,
|
||||
this.eventEmitter,
|
||||
this.repository,
|
||||
this.monogodbRepository,
|
||||
this.primaRepository,
|
||||
this.cache,
|
||||
this.chatwootCache,
|
||||
this.baileysCache,
|
||||
@@ -410,9 +412,9 @@ export class WAMonitoringService {
|
||||
}
|
||||
}
|
||||
|
||||
private async loadInstancesFromDatabase() {
|
||||
private async loadInstancesFromDatabaseMongoDB() {
|
||||
this.logger.verbose('Database enabled');
|
||||
await this.repository.dbServer.connect();
|
||||
await this.monogodbRepository.mongodbServer.connect();
|
||||
const collections: any[] = await this.dbInstance.collections();
|
||||
await this.deleteTempInstances(collections);
|
||||
if (collections.length > 0) {
|
||||
@@ -423,6 +425,20 @@ export class WAMonitoringService {
|
||||
}
|
||||
}
|
||||
|
||||
private async loadInstancesFromDatabasePostgres() {
|
||||
this.logger.verbose('Database enabled');
|
||||
await this.primaRepository.onModuleInit();
|
||||
|
||||
const instances = await this.primaRepository.instance.findMany();
|
||||
|
||||
if (instances.length === 0) {
|
||||
this.logger.verbose('No instances found');
|
||||
return;
|
||||
}
|
||||
|
||||
await Promise.all(instances.map(async (instance) => this.setInstance(instance.name)));
|
||||
}
|
||||
|
||||
private async loadInstancesFromProvider() {
|
||||
this.logger.verbose('Provider in files enabled');
|
||||
const [instances] = await this.providerFiles.allInstances();
|
||||
@@ -523,7 +539,7 @@ export class WAMonitoringService {
|
||||
return;
|
||||
}
|
||||
this.logger.verbose('Cleaning up temp instances');
|
||||
const auths = await this.repository.auth.list();
|
||||
const auths = await this.monogodbRepository.auth.list();
|
||||
if (auths.length === 0) {
|
||||
this.logger.verbose('No temp instances found');
|
||||
return;
|
||||
|
||||
Reference in New Issue
Block a user