log: removed excessive verbose logs

This commit is contained in:
Davidson Gomes
2024-06-06 18:04:45 -03:00
parent 51c873c19e
commit bdd1b8fa21
45 changed files with 5 additions and 1814 deletions

View File

@@ -19,8 +19,6 @@ export class AuthService {
private async apikey(instance: InstanceDto, token?: string) {
const apikey = token ? token : v4().toUpperCase();
this.logger.verbose(token ? 'APIKEY defined: ' + apikey : 'APIKEY created: ' + apikey);
const db = this.configService.get('DATABASE');
if (db.ENABLED) {
@@ -32,8 +30,6 @@ export class AuthService {
},
});
this.logger.verbose('APIKEY saved in database');
return { apikey };
} catch (error) {
this.logger.error({
@@ -48,22 +44,16 @@ export class AuthService {
public async checkDuplicateToken(token: string) {
const instances = await this.waMonitor.instanceInfo();
this.logger.verbose('checking duplicate token');
const instance = instances.find((instance) => instance.instance.apikey === token);
if (instance) {
throw new BadRequestException('Token already exists');
}
this.logger.verbose('available token');
return true;
}
public async generateHash(instance: InstanceDto, token?: string) {
this.logger.verbose('generating hash apiKey to instance: ' + instance.instanceName);
return (await this.apikey(instance, token)) as { apikey: string };
}
}

View File

@@ -8,9 +8,9 @@ export class CacheService {
constructor(private readonly cache: ICache) {
if (cache) {
this.logger.verbose(`cacheservice created using cache engine: ${cache.constructor?.name}`);
this.logger.info(`cacheservice created using cache engine: ${cache.constructor?.name}`);
} else {
this.logger.verbose(`cacheservice disabled`);
this.logger.info(`cacheservice disabled`);
}
}
@@ -18,7 +18,6 @@ export class CacheService {
if (!this.cache) {
return;
}
this.logger.verbose(`cacheservice getting key: ${key}`);
return this.cache.get(key);
}
@@ -41,7 +40,6 @@ export class CacheService {
if (!this.cache) {
return;
}
this.logger.verbose(`cacheservice setting key: ${key}`);
this.cache.set(key, value);
}
@@ -59,7 +57,6 @@ export class CacheService {
if (!this.cache) {
return;
}
this.logger.verbose(`cacheservice has key: ${key}`);
return this.cache.has(key);
}
@@ -67,7 +64,6 @@ export class CacheService {
if (!this.cache) {
return;
}
this.logger.verbose(`cacheservice deleting key: ${key}`);
return this.cache.delete(key);
}
@@ -85,7 +81,6 @@ export class CacheService {
if (!this.cache) {
return;
}
this.logger.verbose(`cacheservice deleting all keys`);
return this.cache.deleteAll(appendCriteria);
}
@@ -93,7 +88,6 @@ export class CacheService {
if (!this.cache) {
return;
}
this.logger.verbose(`cacheservice getting all keys`);
return this.cache.keys(appendCriteria);
}
}

View File

@@ -48,9 +48,7 @@ export class ChannelStartupService {
public readonly eventEmitter: EventEmitter2,
public readonly prismaRepository: PrismaRepository,
public readonly chatwootCache: CacheService,
) {
this.logger.verbose('ChannelStartupService initialized');
}
) {}
public readonly logger = new Logger(ChannelStartupService.name);
@@ -79,15 +77,11 @@ export class ChannelStartupService {
public set instanceName(name: string) {
this.logger.setInstance(name);
this.logger.verbose(`Initializing instance '${name}'`);
if (!name) {
this.logger.verbose('Instance name not found, generating random name with uuid');
this.instance.name = v4();
return;
}
this.instance.name = name;
this.logger.verbose(`Instance '${this.instance.name}' initialized`);
this.logger.verbose('Sending instance status to webhook');
this.sendDataWebhook(Events.STATUS_INSTANCE, {
instance: this.instance.name,
status: 'created',
@@ -106,32 +100,26 @@ export class ChannelStartupService {
}
public get instanceName() {
this.logger.verbose('Getting instance name');
return this.instance.name;
}
public set instanceId(id: string) {
if (!id) {
this.logger.verbose('Instance id not found, generating random id with uuid');
this.instance.id = v4();
return;
}
this.logger.verbose(`Setting instanceId: ${id}`);
this.instance.id = id;
}
public get instanceId() {
this.logger.verbose('Getting instanceId');
return this.instance.id;
}
public get wuid() {
this.logger.verbose('Getting remoteJid of instance');
return this.instance.wuid;
}
public async loadIntegration() {
this.logger.verbose('Loading webhook');
const data = await this.prismaRepository.integration.findUnique({
where: {
instanceId: this.instanceId,
@@ -139,19 +127,13 @@ export class ChannelStartupService {
});
this.localIntegration.integration = data?.integration;
this.logger.verbose(`Integration: ${this.localIntegration.integration}`);
this.localIntegration.number = data?.number;
this.logger.verbose(`Integration number: ${this.localIntegration.number}`);
this.localIntegration.token = data?.token;
this.logger.verbose(`Integration token: ${this.localIntegration.token}`);
this.logger.verbose('Integration loaded');
}
public async setIntegration(data: IntegrationDto) {
this.logger.verbose('Setting integration');
console.log('setIntegration');
await this.prismaRepository.integration.upsert({
where: {
@@ -170,15 +152,10 @@ export class ChannelStartupService {
},
});
this.logger.verbose(`Integration: ${data.integration}`);
this.logger.verbose(`Integration number: ${data.number}`);
this.logger.verbose(`Integration token: ${data.token}`);
Object.assign(this.localIntegration, data);
this.logger.verbose('Integration set');
}
public async findIntegration() {
this.logger.verbose('Finding integration');
let data;
data = await this.prismaRepository.integration.findUnique({
@@ -199,15 +176,10 @@ export class ChannelStartupService {
data = { integration: 'WHATSAPP-BAILEYS', number: '', token: '' };
}
this.logger.verbose(`Integration: ${data.integration}`);
this.logger.verbose(`Integration number: ${data.number}`);
this.logger.verbose(`Integration token: ${data.token}`);
return data;
}
public async loadSettings() {
this.logger.verbose('Loading settings');
const data = await this.prismaRepository.setting.findUnique({
where: {
instanceId: this.instanceId,
@@ -215,31 +187,15 @@ export class ChannelStartupService {
});
this.localSettings.rejectCall = data?.rejectCall;
this.logger.verbose(`Settings rejectCall: ${this.localSettings.rejectCall}`);
this.localSettings.msgCall = data?.msgCall;
this.logger.verbose(`Settings msgCall: ${this.localSettings.msgCall}`);
this.localSettings.groupsIgnore = data?.groupsIgnore;
this.logger.verbose(`Settings groupsIgnore: ${this.localSettings.groupsIgnore}`);
this.localSettings.alwaysOnline = data?.alwaysOnline;
this.logger.verbose(`Settings alwaysOnline: ${this.localSettings.alwaysOnline}`);
this.localSettings.readMessages = data?.readMessages;
this.logger.verbose(`Settings readMessages: ${this.localSettings.readMessages}`);
this.localSettings.readStatus = data?.readStatus;
this.logger.verbose(`Settings readStatus: ${this.localSettings.readStatus}`);
this.localSettings.syncFullHistory = data?.syncFullHistory;
this.logger.verbose(`Settings syncFullHistory: ${this.localSettings.syncFullHistory}`);
this.logger.verbose('Settings loaded');
}
public async setSettings(data: SettingsDto) {
this.logger.verbose('Setting settings');
await this.prismaRepository.setting.upsert({
where: {
instanceId: this.instanceId,
@@ -265,19 +221,10 @@ export class ChannelStartupService {
},
});
this.logger.verbose(`Settings rejectCall: ${data.rejectCall}`);
this.logger.verbose(`Settings msgCall: ${data.msgCall}`);
this.logger.verbose(`Settings groupsIgnore: ${data.groupsIgnore}`);
this.logger.verbose(`Settings alwaysOnline: ${data.alwaysOnline}`);
this.logger.verbose(`Settings readMessages: ${data.readMessages}`);
this.logger.verbose(`Settings readStatus: ${data.readStatus}`);
this.logger.verbose(`Settings syncFullHistory: ${data.syncFullHistory}`);
Object.assign(this.localSettings, data);
this.logger.verbose('Settings set');
}
public async findSettings() {
this.logger.verbose('Finding settings');
const data = await this.prismaRepository.setting.findUnique({
where: {
instanceId: this.instanceId,
@@ -285,17 +232,9 @@ export class ChannelStartupService {
});
if (!data) {
this.logger.verbose('Settings not found');
return null;
}
this.logger.verbose(`Settings url: ${data.rejectCall}`);
this.logger.verbose(`Settings msgCall: ${data.msgCall}`);
this.logger.verbose(`Settings groupsIgnore: ${data.groupsIgnore}`);
this.logger.verbose(`Settings alwaysOnline: ${data.alwaysOnline}`);
this.logger.verbose(`Settings readMessages: ${data.readMessages}`);
this.logger.verbose(`Settings readStatus: ${data.readStatus}`);
this.logger.verbose(`Settings syncFullHistory: ${data.syncFullHistory}`);
return {
rejectCall: data.rejectCall,
msgCall: data.msgCall,
@@ -308,7 +247,6 @@ export class ChannelStartupService {
}
public async loadWebhook() {
this.logger.verbose('Loading webhook');
const data = await this.prismaRepository.webhook.findUnique({
where: {
instanceId: this.instanceId,
@@ -316,25 +254,13 @@ export class ChannelStartupService {
});
this.localWebhook.url = data?.url;
this.logger.verbose(`Webhook url: ${this.localWebhook.url}`);
this.localWebhook.enabled = data?.enabled;
this.logger.verbose(`Webhook enabled: ${this.localWebhook.enabled}`);
this.localWebhook.events = data?.events;
this.logger.verbose(`Webhook events: ${this.localWebhook.events}`);
this.localWebhook.webhookByEvents = data?.webhookByEvents;
this.logger.verbose(`Webhook by events: ${this.localWebhook.webhookByEvents}`);
this.localWebhook.webhookBase64 = data?.webhookBase64;
this.logger.verbose(`Webhook by webhookBase64: ${this.localWebhook.webhookBase64}`);
this.logger.verbose('Webhook loaded');
}
public async setWebhook(data: WebhookDto) {
this.logger.verbose('Setting webhook');
await this.prismaRepository.webhook.create({
data: {
url: data.url,
@@ -346,14 +272,10 @@ export class ChannelStartupService {
},
});
this.logger.verbose(`Webhook url: ${data.url}`);
this.logger.verbose(`Webhook events: ${data.events}`);
Object.assign(this.localWebhook, data);
this.logger.verbose('Webhook set');
}
public async findWebhook() {
this.logger.verbose('Finding webhook');
const data = await this.prismaRepository.webhook.findUnique({
where: {
instanceId: this.instanceId,
@@ -361,13 +283,9 @@ export class ChannelStartupService {
});
if (!data) {
this.logger.verbose('Webhook not found');
throw new NotFoundException('Webhook not found');
}
this.logger.verbose(`Webhook url: ${data.url}`);
this.logger.verbose(`Webhook events: ${data.events}`);
return data;
}
@@ -376,7 +294,6 @@ export class ChannelStartupService {
return;
}
this.logger.verbose('Loading chatwoot');
const data = await this.prismaRepository.chatwoot.findUnique({
where: {
instanceId: this.instanceId,
@@ -384,57 +301,26 @@ export class ChannelStartupService {
});
this.localChatwoot.enabled = data?.enabled;
this.logger.verbose(`Chatwoot enabled: ${this.localChatwoot.enabled}`);
this.localChatwoot.accountId = data?.accountId;
this.logger.verbose(`Chatwoot account id: ${this.localChatwoot.accountId}`);
this.localChatwoot.token = data?.token;
this.logger.verbose(`Chatwoot token: ${this.localChatwoot.token}`);
this.localChatwoot.url = data?.url;
this.logger.verbose(`Chatwoot url: ${this.localChatwoot.url}`);
this.localChatwoot.nameInbox = data?.nameInbox;
this.logger.verbose(`Chatwoot inbox name: ${this.localChatwoot.nameInbox}`);
this.localChatwoot.signMsg = data?.signMsg;
this.logger.verbose(`Chatwoot sign msg: ${this.localChatwoot.signMsg}`);
this.localChatwoot.signDelimiter = data?.signDelimiter;
this.logger.verbose(`Chatwoot sign delimiter: ${this.localChatwoot.signDelimiter}`);
this.localChatwoot.number = data?.number;
this.logger.verbose(`Chatwoot number: ${this.localChatwoot.number}`);
this.localChatwoot.reopenConversation = data?.reopenConversation;
this.logger.verbose(`Chatwoot reopen conversation: ${this.localChatwoot.reopenConversation}`);
this.localChatwoot.conversationPending = data?.conversationPending;
this.logger.verbose(`Chatwoot conversation pending: ${this.localChatwoot.conversationPending}`);
this.localChatwoot.mergeBrazilContacts = data?.mergeBrazilContacts;
this.logger.verbose(`Chatwoot merge brazil contacts: ${this.localChatwoot.mergeBrazilContacts}`);
this.localChatwoot.importContacts = data?.importContacts;
this.logger.verbose(`Chatwoot import contacts: ${this.localChatwoot.importContacts}`);
this.localChatwoot.importMessages = data?.importMessages;
this.logger.verbose(`Chatwoot import messages: ${this.localChatwoot.importMessages}`);
this.localChatwoot.daysLimitImportMessages = data?.daysLimitImportMessages;
this.logger.verbose(`Chatwoot days limit import messages: ${this.localChatwoot.daysLimitImportMessages}`);
this.logger.verbose('Chatwoot loaded');
}
public async setChatwoot(data: ChatwootDto) {
if (!this.configService.get<Chatwoot>('CHATWOOT').ENABLED) {
this.logger.verbose('Chatwoot is not enabled');
return;
}
this.logger.verbose('Setting chatwoot');
await this.prismaRepository.chatwoot.create({
data: {
enabled: data.enabled,
@@ -454,33 +340,16 @@ export class ChannelStartupService {
},
});
this.logger.verbose(`Chatwoot account id: ${data.accountId}`);
this.logger.verbose(`Chatwoot token: ${data.token}`);
this.logger.verbose(`Chatwoot url: ${data.url}`);
this.logger.verbose(`Chatwoot inbox name: ${data.nameInbox}`);
this.logger.verbose(`Chatwoot sign msg: ${data.signMsg}`);
this.logger.verbose(`Chatwoot sign delimiter: ${data.signDelimiter}`);
this.logger.verbose(`Chatwoot reopen conversation: ${data.reopenConversation}`);
this.logger.verbose(`Chatwoot conversation pending: ${data.conversationPending}`);
this.logger.verbose(`Chatwoot merge brazil contacts: ${data.mergeBrazilContacts}`);
this.logger.verbose(`Chatwoot import contacts: ${data.importContacts}`);
this.logger.verbose(`Chatwoot import messages: ${data.importMessages}`);
this.logger.verbose(`Chatwoot days limit import messages: ${data.daysLimitImportMessages}`);
Object.assign(this.localChatwoot, { ...data, signDelimiter: data.signMsg ? data.signDelimiter : null });
this.clearCacheChatwoot();
this.logger.verbose('Chatwoot set');
}
public async findChatwoot() {
if (!this.configService.get<Chatwoot>('CHATWOOT').ENABLED) {
this.logger.verbose('Chatwoot is not enabled');
return null;
}
this.logger.verbose('Finding chatwoot');
const data = await this.prismaRepository.chatwoot.findUnique({
where: {
instanceId: this.instanceId,
@@ -488,23 +357,9 @@ export class ChannelStartupService {
});
if (!data) {
this.logger.verbose('Chatwoot not found');
return null;
}
this.logger.verbose(`Chatwoot account id: ${data.accountId}`);
this.logger.verbose(`Chatwoot token: ${data.token}`);
this.logger.verbose(`Chatwoot url: ${data.url}`);
this.logger.verbose(`Chatwoot inbox name: ${data.nameInbox}`);
this.logger.verbose(`Chatwoot sign msg: ${data.signMsg}`);
this.logger.verbose(`Chatwoot sign delimiter: ${data.signDelimiter}`);
this.logger.verbose(`Chatwoot reopen conversation: ${data.reopenConversation}`);
this.logger.verbose(`Chatwoot conversation pending: ${data.conversationPending}`);
this.logger.verbose(`Chatwoot merge brazilian contacts: ${data.mergeBrazilContacts}`);
this.logger.verbose(`Chatwoot import contacts: ${data.importContacts}`);
this.logger.verbose(`Chatwoot import messages: ${data.importMessages}`);
this.logger.verbose(`Chatwoot days limit import messages: ${data.daysLimitImportMessages}`);
return {
enabled: data.enabled,
accountId: data.accountId,
@@ -523,15 +378,12 @@ export class ChannelStartupService {
}
public clearCacheChatwoot() {
this.logger.verbose('Removing cache from chatwoot');
if (this.localChatwoot.enabled) {
this.chatwootService.getCache()?.deleteAll(this.instanceName);
}
}
public async loadWebsocket() {
this.logger.verbose('Loading websocket');
const data = await this.prismaRepository.websocket.findUnique({
where: {
instanceId: this.instanceId,
@@ -539,16 +391,10 @@ export class ChannelStartupService {
});
this.localWebsocket.enabled = data?.enabled;
this.logger.verbose(`Websocket enabled: ${this.localWebsocket.enabled}`);
this.localWebsocket.events = data?.events;
this.logger.verbose(`Websocket events: ${this.localWebsocket.events}`);
this.logger.verbose('Websocket loaded');
}
public async setWebsocket(data: WebsocketDto) {
this.logger.verbose('Setting websocket');
await this.prismaRepository.websocket.create({
data: {
enabled: data.enabled,
@@ -557,13 +403,10 @@ export class ChannelStartupService {
},
});
this.logger.verbose(`Websocket events: ${data.events}`);
Object.assign(this.localWebsocket, data);
this.logger.verbose('Websocket set');
}
public async findWebsocket() {
this.logger.verbose('Finding websocket');
const data = await this.prismaRepository.websocket.findUnique({
where: {
instanceId: this.instanceId,
@@ -571,16 +414,13 @@ export class ChannelStartupService {
});
if (!data) {
this.logger.verbose('Websocket not found');
throw new NotFoundException('Websocket not found');
}
this.logger.verbose(`Websocket events: ${data.events}`);
return data;
}
public async loadRabbitmq() {
this.logger.verbose('Loading rabbitmq');
const data = await this.prismaRepository.rabbitmq.findUnique({
where: {
instanceId: this.instanceId,
@@ -588,16 +428,10 @@ export class ChannelStartupService {
});
this.localRabbitmq.enabled = data?.enabled;
this.logger.verbose(`Rabbitmq enabled: ${this.localRabbitmq.enabled}`);
this.localRabbitmq.events = data?.events;
this.logger.verbose(`Rabbitmq events: ${this.localRabbitmq.events}`);
this.logger.verbose('Rabbitmq loaded');
}
public async setRabbitmq(data: RabbitmqDto) {
this.logger.verbose('Setting rabbitmq');
await this.prismaRepository.rabbitmq.create({
data: {
enabled: data.enabled,
@@ -606,13 +440,10 @@ export class ChannelStartupService {
},
});
this.logger.verbose(`Rabbitmq events: ${data.events}`);
Object.assign(this.localRabbitmq, data);
this.logger.verbose('Rabbitmq set');
}
public async findRabbitmq() {
this.logger.verbose('Finding rabbitmq');
const data = await this.prismaRepository.rabbitmq.findUnique({
where: {
instanceId: this.instanceId,
@@ -620,24 +451,19 @@ export class ChannelStartupService {
});
if (!data) {
this.logger.verbose('Rabbitmq not found');
throw new NotFoundException('Rabbitmq not found');
}
this.logger.verbose(`Rabbitmq events: ${data.events}`);
return data;
}
public async removeRabbitmqQueues() {
this.logger.verbose('Removing rabbitmq');
if (this.localRabbitmq.enabled) {
removeQueues(this.instanceName, this.localRabbitmq.events);
}
}
public async loadSqs() {
this.logger.verbose('Loading sqs');
const data = await this.prismaRepository.sqs.findUnique({
where: {
instanceId: this.instanceId,
@@ -645,16 +471,10 @@ export class ChannelStartupService {
});
this.localSqs.enabled = data?.enabled;
this.logger.verbose(`Sqs enabled: ${this.localSqs.enabled}`);
this.localSqs.events = data?.events;
this.logger.verbose(`Sqs events: ${this.localSqs.events}`);
this.logger.verbose('Sqs loaded');
}
public async setSqs(data: SqsDto) {
this.logger.verbose('Setting sqs');
await this.prismaRepository.sqs.create({
data: {
enabled: data.enabled,
@@ -663,13 +483,10 @@ export class ChannelStartupService {
},
});
this.logger.verbose(`Sqs events: ${data.events}`);
Object.assign(this.localSqs, data);
this.logger.verbose('Sqs set');
}
public async findSqs() {
this.logger.verbose('Finding sqs');
const data = await this.prismaRepository.sqs.findUnique({
where: {
instanceId: this.instanceId,
@@ -677,17 +494,13 @@ export class ChannelStartupService {
});
if (!data) {
this.logger.verbose('Sqs not found');
throw new NotFoundException('Sqs not found');
}
this.logger.verbose(`Sqs events: ${data.events}`);
return data;
}
public async removeSqsQueues() {
this.logger.verbose('Removing sqs');
if (this.localSqs.enabled) {
removeQueuesSQS(this.instanceName, this.localSqs.events);
}
@@ -697,7 +510,6 @@ export class ChannelStartupService {
if (!this.configService.get<Typebot>('TYPEBOT').ENABLED) {
return;
}
this.logger.verbose('Loading typebot');
const data = await this.prismaRepository.typebot.findUnique({
where: {
instanceId: this.instanceId,
@@ -708,40 +520,20 @@ export class ChannelStartupService {
});
this.localTypebot.enabled = data?.enabled;
this.logger.verbose(`Typebot enabled: ${this.localTypebot.enabled}`);
this.localTypebot.url = data?.url;
this.logger.verbose(`Typebot url: ${this.localTypebot.url}`);
this.localTypebot.typebot = data?.typebot;
this.logger.verbose(`Typebot typebot: ${this.localTypebot.typebot}`);
this.localTypebot.expire = data?.expire;
this.logger.verbose(`Typebot expire: ${this.localTypebot.expire}`);
this.localTypebot.keywordFinish = data?.keywordFinish;
this.logger.verbose(`Typebot keywordFinish: ${this.localTypebot.keywordFinish}`);
this.localTypebot.delayMessage = data?.delayMessage;
this.logger.verbose(`Typebot delayMessage: ${this.localTypebot.delayMessage}`);
this.localTypebot.unknownMessage = data?.unknownMessage;
this.logger.verbose(`Typebot unknownMessage: ${this.localTypebot.unknownMessage}`);
this.localTypebot.listeningFromMe = data?.listeningFromMe;
this.logger.verbose(`Typebot listeningFromMe: ${this.localTypebot.listeningFromMe}`);
this.localTypebot.sessions = data?.sessions;
this.logger.verbose('Typebot loaded');
}
public async setTypebot(data: TypebotDto) {
if (!this.configService.get<Typebot>('TYPEBOT').ENABLED) {
this.logger.verbose('Typebot is not enabled');
return;
}
this.logger.verbose('Setting typebot');
const typebot = await this.prismaRepository.typebot.create({
data: {
@@ -763,22 +555,13 @@ export class ChannelStartupService {
},
});
this.logger.verbose(`Typebot typebot: ${data.typebot}`);
this.logger.verbose(`Typebot expire: ${data.expire}`);
this.logger.verbose(`Typebot keywordFinish: ${data.keywordFinish}`);
this.logger.verbose(`Typebot delayMessage: ${data.delayMessage}`);
this.logger.verbose(`Typebot unknownMessage: ${data.unknownMessage}`);
this.logger.verbose(`Typebot listeningFromMe: ${data.listeningFromMe}`);
Object.assign(this.localTypebot, data);
this.logger.verbose('Typebot set');
}
public async findTypebot() {
if (!this.configService.get<Typebot>('TYPEBOT').ENABLED) {
this.logger.verbose('Typebot is not enabled');
return;
}
this.logger.verbose('Finding typebot');
const data = await this.prismaRepository.typebot.findUnique({
where: {
instanceId: this.instanceId,
@@ -789,7 +572,6 @@ export class ChannelStartupService {
});
if (!data) {
this.logger.verbose('Typebot not found');
throw new NotFoundException('Typebot not found');
}
@@ -807,7 +589,6 @@ export class ChannelStartupService {
}
public async loadProxy() {
this.logger.verbose('Loading proxy');
const data = await this.prismaRepository.proxy.findUnique({
where: {
instanceId: this.instanceId,
@@ -815,28 +596,14 @@ export class ChannelStartupService {
});
this.localProxy.enabled = data?.enabled;
this.logger.verbose(`Proxy enabled: ${this.localProxy.enabled}`);
this.localProxy.host = data?.host;
this.logger.verbose(`Proxy host: ${this.localProxy.host}`);
this.localProxy.port = data?.port;
this.logger.verbose(`Proxy port: ${this.localProxy.port}`);
this.localProxy.protocol = data?.protocol;
this.logger.verbose(`Proxy protocol: ${this.localProxy.protocol}`);
this.localProxy.username = data?.username;
this.logger.verbose(`Proxy username: ${this.localProxy.username}`);
this.localProxy.password = data?.password;
this.logger.verbose(`Proxy password: ${this.localProxy.password}`);
this.logger.verbose('Proxy loaded');
}
public async setProxy(data: ProxyDto) {
this.logger.verbose('Setting proxy');
await this.prismaRepository.proxy.create({
data: {
enabled: data.enabled,
@@ -849,13 +616,10 @@ export class ChannelStartupService {
},
});
this.logger.verbose(`Proxy proxy: ${data.host}`);
Object.assign(this.localProxy, data);
this.logger.verbose('Proxy set');
}
public async findProxy() {
this.logger.verbose('Finding proxy');
const data = await this.prismaRepository.proxy.findUnique({
where: {
instanceId: this.instanceId,
@@ -863,7 +627,6 @@ export class ChannelStartupService {
});
if (!data) {
this.logger.verbose('Proxy not found');
throw new NotFoundException('Proxy not found');
}
@@ -1098,7 +861,6 @@ export class ChannelStartupService {
}
if (this.configService.get<Websocket>('WEBSOCKET')?.ENABLED) {
this.logger.verbose('Sending data to websocket on channel: ' + this.instance.name);
const io = getIO();
const message = {
@@ -1138,9 +900,6 @@ export class ChannelStartupService {
}
if (this.localWebsocket.enabled && Array.isArray(websocketLocal) && websocketLocal.includes(we)) {
this.logger.verbose('Sending data to websocket on event: ' + event);
this.logger.verbose('Sending data to socket.io in channel: ' + this.instance.name);
io.of(`/${this.instance.name}`).emit(event, message);
if (this.configService.get<Websocket>('WEBSOCKET')?.GLOBAL_EVENTS) {
@@ -1172,7 +931,6 @@ export class ChannelStartupService {
if (local) {
if (Array.isArray(webhookLocal) && webhookLocal.includes(we)) {
this.logger.verbose('Sending data to webhook local');
let baseURL: string;
if (this.localWebhook.webhookByEvents) {
@@ -1240,7 +998,6 @@ export class ChannelStartupService {
if (webhookGlobal.GLOBAL?.ENABLED) {
if (webhookGlobal.EVENTS[we]) {
this.logger.verbose('Sending data to webhook global');
const globalWebhook = this.configService.get<Webhook>('WEBHOOK').GLOBAL;
let globalURL;
@@ -1311,11 +1068,9 @@ export class ChannelStartupService {
}
public cleanStore() {
this.logger.verbose('Cronjob to clean store initialized');
const cleanStore = this.configService.get<CleanStoreConf>('CLEAN_STORE');
const database = this.configService.get<Database>('DATABASE');
if (cleanStore?.CLEANING_INTERVAL && !database.ENABLED) {
this.logger.verbose('Cronjob to clean store enabled');
setInterval(() => {
try {
for (const [key, value] of Object.entries(cleanStore)) {
@@ -1323,9 +1078,6 @@ export class ChannelStartupService {
execSync(
`rm -rf ${join(this.storePath, key.toLowerCase().replace('_', '-'), this.instance.name)}/*.json`,
);
this.logger.verbose(
`Cleaned ${join(this.storePath, key.toLowerCase().replace('_', '-'), this.instance.name)}/*.json`,
);
}
}
} catch (error) {
@@ -1370,15 +1122,11 @@ export class ChannelStartupService {
}
public createJid(number: string): string {
this.logger.verbose('Creating jid with number: ' + number);
if (number.includes('@g.us') || number.includes('@s.whatsapp.net') || number.includes('@lid')) {
this.logger.verbose('Number already contains @g.us or @s.whatsapp.net or @lid');
return number;
}
if (number.includes('@broadcast')) {
this.logger.verbose('Number already contains @broadcast');
return number;
}
@@ -1391,7 +1139,6 @@ export class ChannelStartupService {
.split('@')[0];
if (number.includes('-') && number.length >= 24) {
this.logger.verbose('Jid created is group: ' + `${number}@g.us`);
number = number.replace(/[^\d-]/g, '');
return `${number}@g.us`;
}
@@ -1399,7 +1146,6 @@ export class ChannelStartupService {
number = number.replace(/\D/g, '');
if (number.length >= 18) {
this.logger.verbose('Jid created is group: ' + `${number}@g.us`);
number = number.replace(/[^\d-]/g, '');
return `${number}@g.us`;
}
@@ -1408,12 +1154,10 @@ export class ChannelStartupService {
number = this.formatBRNumber(number);
this.logger.verbose('Jid created is whatsapp: ' + `${number}@s.whatsapp.net`);
return `${number}@s.whatsapp.net`;
}
public async fetchContacts(query: any) {
this.logger.verbose('Fetching contacts');
if (query?.where) {
query.where.remoteJid = this.instance.name;
if (query.where?.remoteJid) {
@@ -1432,7 +1176,6 @@ export class ChannelStartupService {
}
public async fetchMessages(query: any) {
this.logger.verbose('Fetching messages');
if (query?.where) {
if (query.where?.key?.remoteJid) {
query.where.key.remoteJid = this.createJid(query.where.key.remoteJid);
@@ -1450,7 +1193,6 @@ export class ChannelStartupService {
}
public async fetchStatusMessage(query: any) {
this.logger.verbose('Fetching status messages');
if (query?.where) {
if (query.where?.remoteJid) {
query.where.remoteJid = this.createJid(query.where.remoteJid);
@@ -1468,7 +1210,6 @@ export class ChannelStartupService {
}
public async fetchChats() {
this.logger.verbose('Fetching chats');
return await this.prismaRepository.chat.findMany({ where: { instanceId: this.instanceId } });
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -39,7 +39,6 @@ export class BusinessStartupService extends ChannelStartupService {
private readonly providerFiles: ProviderFiles,
) {
super(configService, eventEmitter, prismaRepository, chatwootCache);
this.logger.verbose('BusinessStartupService initialized');
this.cleanStore();
}
@@ -49,7 +48,6 @@ export class BusinessStartupService extends ChannelStartupService {
public mobile: boolean;
public get connectionStatus() {
this.logger.verbose('Getting connection status');
return this.stateConnection;
}
@@ -58,8 +56,6 @@ export class BusinessStartupService extends ChannelStartupService {
}
public get qrCode(): wa.QrCode {
this.logger.verbose('Getting qrcode');
return {
pairingCode: this.instance.qrcode?.pairingCode,
code: this.instance.qrcode?.code,
@@ -69,7 +65,6 @@ export class BusinessStartupService extends ChannelStartupService {
}
public async logoutInstance() {
this.logger.verbose('Logging out instance');
await this.closeClient();
}
@@ -92,15 +87,12 @@ export class BusinessStartupService extends ChannelStartupService {
public async profilePicture(number: string) {
const jid = this.createJid(number);
this.logger.verbose('Getting profile picture with jid: ' + jid);
try {
this.logger.verbose('Getting profile picture url');
return {
wuid: jid,
profilePictureUrl: await this.client.profilePictureUrl(jid, 'image'),
};
} catch (error) {
this.logger.verbose('Profile picture not found');
return {
wuid: jid,
profilePictureUrl: null,
@@ -121,7 +113,6 @@ export class BusinessStartupService extends ChannelStartupService {
}
public async setWhatsappBusinessProfile(data: NumberBusiness): Promise<any> {
this.logger.verbose('set profile');
const content = {
messaging_product: 'whatsapp',
about: data.about,
@@ -146,14 +137,8 @@ export class BusinessStartupService extends ChannelStartupService {
this.loadSqs();
this.loadTypebot();
this.logger.verbose('Creating socket');
this.logger.verbose('Socket created');
this.eventHandler(content);
this.logger.verbose('Socket event handler initialized');
this.phoneNumber = this.createJid(
content.messages ? content.messages[0].from : content.statuses[0]?.recipient_id,
);
@@ -229,7 +214,6 @@ export class BusinessStartupService extends ChannelStartupService {
let content: any = {};
const vcard = (contact: any) => {
this.logger.verbose('Creating vcard');
let result =
'BEGIN:VCARD\n' +
'VERSION:3.0\n' +
@@ -237,22 +221,18 @@ export class BusinessStartupService extends ChannelStartupService {
`FN:${contact.name.formatted_name}\n`;
if (contact.org) {
this.logger.verbose('Organization defined');
result += `ORG:${contact.org.company};\n`;
}
if (contact.emails) {
this.logger.verbose('Email defined');
result += `EMAIL:${contact.emails[0].email}\n`;
}
if (contact.urls) {
this.logger.verbose('Url defined');
result += `URL:${contact.urls[0].url}\n`;
}
if (!contact.phones[0]?.wa_id) {
this.logger.verbose('Wuid defined');
contact.phones[0].wa_id = this.createJid(contact.phones[0].phone);
}
@@ -261,7 +241,6 @@ export class BusinessStartupService extends ChannelStartupService {
'item1.X-ABLabel:Celular\n' +
'END:VCARD';
this.logger.verbose('Vcard created');
return result;
};
@@ -405,8 +384,6 @@ export class BusinessStartupService extends ChannelStartupService {
this.logger.log(messageRaw);
this.logger.verbose('Sending data to webhook in event MESSAGES_UPSERT');
this.sendDataWebhook(Events.MESSAGES_UPSERT, messageRaw);
if (this.configService.get<Chatwoot>('CHATWOOT').ENABLED && this.localChatwoot.enabled) {
@@ -442,12 +419,10 @@ export class BusinessStartupService extends ChannelStartupService {
}
}
this.logger.verbose('Inserting message in database');
await this.prismaRepository.message.create({
data: messageRaw,
});
this.logger.verbose('Verifying contact from message');
const contact = await this.prismaRepository.contact.findFirst({
where: { instanceId: this.instanceId, remoteJid: key.remoteJid },
});
@@ -460,12 +435,10 @@ export class BusinessStartupService extends ChannelStartupService {
};
if (contactRaw.remoteJid === 'status@broadcast') {
this.logger.verbose('Contact is status@broadcast');
return;
}
if (contact) {
this.logger.verbose('Contact found in database');
const contactRaw: any = {
remoteJid: received.contacts[0].profile.phone,
pushName,
@@ -473,7 +446,6 @@ export class BusinessStartupService extends ChannelStartupService {
instanceId: this.instanceId,
};
this.logger.verbose('Sending data to webhook in event CONTACTS_UPDATE');
this.sendDataWebhook(Events.CONTACTS_UPDATE, contactRaw);
if (this.configService.get<Chatwoot>('CHATWOOT').ENABLED && this.localChatwoot.enabled) {
@@ -484,7 +456,6 @@ export class BusinessStartupService extends ChannelStartupService {
);
}
this.logger.verbose('Updating contact in database');
await this.prismaRepository.contact.updateMany({
where: { remoteJid: contact.remoteJid },
data: contactRaw,
@@ -492,17 +463,12 @@ export class BusinessStartupService extends ChannelStartupService {
return;
}
this.logger.verbose('Contact not found in database');
this.logger.verbose('Sending data to webhook in event CONTACTS_UPSERT');
this.sendDataWebhook(Events.CONTACTS_UPSERT, contactRaw);
this.logger.verbose('Inserting contact in database');
this.prismaRepository.contact.create({
data: contactRaw,
});
}
this.logger.verbose('Event received: messages.update');
if (received.statuses) {
for await (const item of received.statuses) {
const key = {
@@ -511,12 +477,9 @@ export class BusinessStartupService extends ChannelStartupService {
fromMe: this.phoneNumber === received.metadata.phone_number_id,
};
if (settings?.groups_ignore && key.remoteJid.includes('@g.us')) {
this.logger.verbose('group ignored');
return;
}
if (key.remoteJid !== 'status@broadcast' && !key?.remoteJid?.match(/(:\d+)/)) {
this.logger.verbose('Message update is valid');
if (item.status === 'read' && !key.fromMe) return;
const findMessage = await this.prismaRepository.message.findFirst({
@@ -530,9 +493,6 @@ export class BusinessStartupService extends ChannelStartupService {
});
if (item.message === null && item.status === undefined) {
this.logger.verbose('Message deleted');
this.logger.verbose('Sending data to webhook in event MESSAGE_DELETE');
this.sendDataWebhook(Events.MESSAGES_DELETE, key);
const message: any = {
@@ -546,9 +506,6 @@ export class BusinessStartupService extends ChannelStartupService {
instanceId: this.instanceId,
};
this.logger.verbose(message);
this.logger.verbose('Inserting message in database');
await this.prismaRepository.messageUpdate.create({
data: message,
});
@@ -575,12 +532,8 @@ export class BusinessStartupService extends ChannelStartupService {
instanceId: this.instanceId,
};
this.logger.verbose(message);
this.logger.verbose('Sending data to webhook in event MESSAGES_UPDATE');
this.sendDataWebhook(Events.MESSAGES_UPDATE, message);
this.logger.verbose('Inserting message in database');
await this.prismaRepository.messageUpdate.create({
data: message,
});
@@ -661,16 +614,13 @@ export class BusinessStartupService extends ChannelStartupService {
}
protected async eventHandler(content: any) {
this.logger.verbose('Initializing event handler');
const database = this.configService.get<Database>('DATABASE');
const settings = await this.findSettings();
this.logger.verbose('Listening event: messages.statuses');
this.messageHandle(content, database, settings);
}
protected async sendMessageWithTyping(number: string, message: any, options?: Options, isChatwoot = false) {
this.logger.verbose('Sending message with typing');
try {
let quoted: any;
const linkPreview = options?.linkPreview != false ? undefined : false;
@@ -684,13 +634,11 @@ export class BusinessStartupService extends ChannelStartupService {
}
quoted = msg;
this.logger.verbose('Quoted message');
}
let content: any;
const messageSent = await (async () => {
if (message['reactionMessage']) {
this.logger.verbose('Sending reaction');
content = {
messaging_product: 'whatsapp',
recipient_type: 'individual',
@@ -705,7 +653,6 @@ export class BusinessStartupService extends ChannelStartupService {
return await this.post(content, 'messages');
}
if (message['locationMessage']) {
this.logger.verbose('Sending message');
content = {
messaging_product: 'whatsapp',
recipient_type: 'individual',
@@ -722,7 +669,6 @@ export class BusinessStartupService extends ChannelStartupService {
return await this.post(content, 'messages');
}
if (message['contacts']) {
this.logger.verbose('Sending message');
content = {
messaging_product: 'whatsapp',
recipient_type: 'individual',
@@ -735,7 +681,6 @@ export class BusinessStartupService extends ChannelStartupService {
return await this.post(content, 'messages');
}
if (message['conversation']) {
this.logger.verbose('Sending message');
content = {
messaging_product: 'whatsapp',
recipient_type: 'individual',
@@ -750,7 +695,6 @@ export class BusinessStartupService extends ChannelStartupService {
return await this.post(content, 'messages');
}
if (message['media']) {
this.logger.verbose('Sending message');
content = {
messaging_product: 'whatsapp',
recipient_type: 'individual',
@@ -766,7 +710,6 @@ export class BusinessStartupService extends ChannelStartupService {
return await this.post(content, 'messages');
}
if (message['audio']) {
this.logger.verbose('Sending message');
content = {
messaging_product: 'whatsapp',
recipient_type: 'individual',
@@ -780,7 +723,6 @@ export class BusinessStartupService extends ChannelStartupService {
return await this.post(content, 'messages');
}
if (message['buttons']) {
this.logger.verbose('Sending message');
content = {
messaging_product: 'whatsapp',
recipient_type: 'individual',
@@ -805,7 +747,6 @@ export class BusinessStartupService extends ChannelStartupService {
return await this.post(content, 'messages');
}
if (message['sections']) {
this.logger.verbose('Sending message');
content = {
messaging_product: 'whatsapp',
recipient_type: 'individual',
@@ -841,7 +782,6 @@ export class BusinessStartupService extends ChannelStartupService {
return await this.post(content, 'messages');
}
if (message['template']) {
this.logger.verbose('Sending message');
content = {
messaging_product: 'whatsapp',
recipient_type: 'individual',
@@ -880,14 +820,12 @@ export class BusinessStartupService extends ChannelStartupService {
this.logger.log(messageRaw);
this.logger.verbose('Sending data to webhook in event SEND_MESSAGE');
this.sendDataWebhook(Events.SEND_MESSAGE, messageRaw);
if (this.configService.get<Chatwoot>('CHATWOOT').ENABLED && this.localChatwoot.enabled && !isChatwoot) {
this.chatwootService.eventWhatsapp(Events.SEND_MESSAGE, { instanceName: this.instance.name }, messageRaw);
}
this.logger.verbose('Inserting message in database');
await this.prismaRepository.message.create({
data: messageRaw,
});
@@ -901,7 +839,6 @@ export class BusinessStartupService extends ChannelStartupService {
// Send Message Controller
public async textMessage(data: SendTextDto, isChatwoot = false) {
this.logger.verbose('Sending text message');
const res = await this.sendMessageWithTyping(
data.number,
{
@@ -935,17 +872,10 @@ export class BusinessStartupService extends ChannelStartupService {
protected async prepareMediaMessage(mediaMessage: MediaMessage) {
try {
this.logger.verbose('Preparing media message');
const mediaType = mediaMessage.mediatype + 'Message';
this.logger.verbose('Media type: ' + mediaType);
if (mediaMessage.mediatype === 'document' && !mediaMessage.fileName) {
this.logger.verbose('If media type is document and file name is not defined then');
const regex = new RegExp(/.*\/(.+?)\./);
const arrayMatch = regex.exec(mediaMessage.media);
mediaMessage.fileName = arrayMatch[1];
this.logger.verbose('File name: ' + mediaMessage.fileName);
}
if (mediaMessage.mediatype === 'image' && !mediaMessage.fileName) {
@@ -983,7 +913,6 @@ export class BusinessStartupService extends ChannelStartupService {
prepareMedia.mimetype = mimetype;
this.logger.verbose('Generating wa message from content');
return prepareMedia;
} catch (error) {
this.logger.error(error);
@@ -992,18 +921,14 @@ export class BusinessStartupService extends ChannelStartupService {
}
public async mediaMessage(data: SendMediaDto, isChatwoot = false) {
this.logger.verbose('Sending media message');
const message = await this.prepareMediaMessage(data.mediaMessage);
return await this.sendMessageWithTyping(data.number, { ...message }, data?.options, isChatwoot);
}
public async processAudio(audio: string, number: string) {
this.logger.verbose('Processing audio');
number = number.replace(/\D/g, '');
const hash = `${number}-${new Date().getTime()}`;
this.logger.verbose('Hash to audio name: ' + hash);
let mimetype: string;
@@ -1030,15 +955,12 @@ export class BusinessStartupService extends ChannelStartupService {
}
public async audioWhatsapp(data: SendAudioDto, isChatwoot = false) {
this.logger.verbose('Sending audio whatsapp');
const message = await this.processAudio(data.audioMessage.audio, data.number);
return await this.sendMessageWithTyping(data.number, { ...message }, data?.options, isChatwoot);
}
public async buttonMessage(data: SendButtonDto) {
this.logger.verbose('Sending button message');
const embeddedMedia: any = {};
let mediatype = 'TEXT';
@@ -1079,7 +1001,6 @@ export class BusinessStartupService extends ChannelStartupService {
}
public async locationMessage(data: SendLocationDto) {
this.logger.verbose('Sending location message');
return await this.sendMessageWithTyping(
data.number,
{
@@ -1095,7 +1016,6 @@ export class BusinessStartupService extends ChannelStartupService {
}
public async listMessage(data: SendListDto) {
this.logger.verbose('Sending list message');
const sectionsItems = {
title: data.listMessage.sections.map((list) => list.title),
};
@@ -1129,7 +1049,6 @@ export class BusinessStartupService extends ChannelStartupService {
}
public async templateMessage(data: SendTemplateDto, isChatwoot = false) {
this.logger.verbose('Sending text message');
const res = await this.sendMessageWithTyping(
data.number,
{
@@ -1146,36 +1065,29 @@ export class BusinessStartupService extends ChannelStartupService {
}
public async contactMessage(data: SendContactDto) {
this.logger.verbose('Sending contact message');
const message: any = {};
const vcard = (contact: ContactMessage) => {
this.logger.verbose('Creating vcard');
let result = 'BEGIN:VCARD\n' + 'VERSION:3.0\n' + `N:${contact.fullName}\n` + `FN:${contact.fullName}\n`;
if (contact.organization) {
this.logger.verbose('Organization defined');
result += `ORG:${contact.organization};\n`;
}
if (contact.email) {
this.logger.verbose('Email defined');
result += `EMAIL:${contact.email}\n`;
}
if (contact.url) {
this.logger.verbose('Url defined');
result += `URL:${contact.url}\n`;
}
if (!contact.wuid) {
this.logger.verbose('Wuid defined');
contact.wuid = this.createJid(contact.phoneNumber);
}
result += `item1.TEL;waid=${contact.wuid}:${contact.phoneNumber}\n` + 'item1.X-ABLabel:Celular\n' + 'END:VCARD';
this.logger.verbose('Vcard created');
return result;
};
@@ -1214,7 +1126,6 @@ export class BusinessStartupService extends ChannelStartupService {
}
public async reactionMessage(data: SendReactionDto) {
this.logger.verbose('Sending reaction message');
return await this.sendMessageWithTyping(data.reactionMessage.key.remoteJid, {
reactionMessage: {
key: data.reactionMessage.key,
@@ -1226,11 +1137,9 @@ export class BusinessStartupService extends ChannelStartupService {
public async getBase64FromMediaMessage(data: any) {
try {
const msg = data.message;
this.logger.verbose('Getting base64 from media message');
const messageType = msg.messageType + 'Message';
const mediaMessage = msg.message[messageType];
this.logger.verbose('Media message downloaded');
return {
mediaType: msg.messageType,
fileName: mediaMessage?.fileName,

View File

@@ -11,7 +11,6 @@ export class IntegrationService {
private readonly logger = new Logger(IntegrationService.name);
public create(instance: InstanceDto, data: IntegrationDto) {
this.logger.verbose('create integration: ' + instance.instanceName);
this.waMonitor.waInstances[instance.instanceName].setIntegration(data);
return { integration: { ...instance, integration: data } };
@@ -19,7 +18,6 @@ export class IntegrationService {
public async find(instance: InstanceDto): Promise<Integration> {
try {
this.logger.verbose('find integration: ' + instance.instanceName);
const result = await this.waMonitor.waInstances[instance.instanceName].findIntegration();
if (Object.keys(result).length === 0) {

View File

@@ -33,8 +33,6 @@ export class WAMonitoringService {
private readonly chatwootCache: CacheService,
private readonly baileysCache: CacheService,
) {
this.logger.verbose('instance created');
this.removeInstance();
this.noConnection();
@@ -53,8 +51,6 @@ export class WAMonitoringService {
public delInstanceTime(instance: string) {
const time = this.configService.get<DelInstance>('DEL_INSTANCE');
if (typeof time === 'number' && time > 0) {
this.logger.verbose(`Instance "${instance}" don't have connection, will be removed in ${time} minutes`);
setTimeout(async () => {
if (this.waInstances[instance]?.connectionStatus?.state !== 'open') {
if (this.waInstances[instance]?.connectionStatus?.state === 'connecting') {
@@ -76,7 +72,6 @@ export class WAMonitoringService {
}
public async instanceInfo(instanceName?: string, arrayReturn = false) {
this.logger.verbose('get instance info');
if (instanceName && !this.waInstances[instanceName]) {
throw new NotFoundException(`Instance "${instanceName}" not found`);
}
@@ -85,7 +80,6 @@ export class WAMonitoringService {
for await (const [key, value] of Object.entries(this.waInstances)) {
if (value) {
this.logger.verbose('get instance info: ' + key);
let chatwoot: any;
const urlServer = this.configService.get<HttpServer>('SERVER').URL;
@@ -111,8 +105,6 @@ export class WAMonitoringService {
}
if (value.connectionStatus.state === 'open') {
this.logger.verbose('instance: ' + key + ' - connectionStatus: open');
const instanceData = {
instance: {
instanceName: key,
@@ -141,8 +133,6 @@ export class WAMonitoringService {
instances.push(instanceData);
} else {
this.logger.verbose('instance: ' + key + ' - connectionStatus: ' + value.connectionStatus.state);
const instanceData = {
instance: {
instanceName: key,
@@ -170,8 +160,6 @@ export class WAMonitoringService {
}
}
this.logger.verbose('return instance info: ' + instances.length);
if (arrayReturn) {
return [instances.find((i) => i.instance.instanceName === instanceName) ?? instances];
}
@@ -179,7 +167,6 @@ export class WAMonitoringService {
}
public async instanceInfoById(instanceId?: string, number?: string) {
this.logger.verbose('get instance info');
let instanceName: string;
if (instanceId) {
instanceName = await this.prismaRepository.instance.findFirst({ where: { id: instanceId } }).then((r) => r?.name);
@@ -207,10 +194,7 @@ export class WAMonitoringService {
}
public async cleaningUp(instanceName: string) {
this.logger.verbose('cleaning up instance: ' + instanceName);
if (this.db.ENABLED && this.db.SAVE_DATA.INSTANCE) {
this.logger.verbose('cleaning up instance in database: ' + instanceName);
await this.prismaRepository.instance.update({
where: { name: instanceName },
data: { connectionStatus: 'close' },
@@ -221,12 +205,10 @@ export class WAMonitoringService {
}
if (this.redis.REDIS.ENABLED && this.redis.REDIS.SAVE_INSTANCES) {
this.logger.verbose('cleaning up instance in redis: ' + instanceName);
await this.cache.delete(instanceName);
return;
}
this.logger.verbose('cleaning up instance in files: ' + instanceName);
if (this.providerSession?.ENABLED) {
await this.providerFiles.removeSession(instanceName);
}
@@ -235,7 +217,6 @@ export class WAMonitoringService {
public async cleaningStoreFiles(instanceName: string) {
if (!this.db.ENABLED) {
this.logger.verbose('cleaning store files instance: ' + instanceName);
if (this.providerSession?.ENABLED) {
await this.providerFiles.removeSession(instanceName);
}
@@ -259,8 +240,6 @@ export class WAMonitoringService {
return;
}
this.logger.verbose('cleaning store database instance: ' + instanceName);
await this.prismaRepository.session.deleteMany({ where: { sessionId: instanceName } });
await this.prismaRepository.chat.deleteMany({ where: { instanceId: instanceName } });
@@ -285,8 +264,6 @@ export class WAMonitoringService {
}
public async loadInstance() {
this.logger.verbose('Loading instances');
try {
if (this.providerSession.ENABLED) {
await this.loadInstancesFromProvider();
@@ -370,31 +347,23 @@ export class WAMonitoringService {
}
}
this.logger.verbose('Instance loaded: ' + name);
await instance.connectToWhatsapp();
this.logger.verbose('connectToWhatsapp: ' + name);
this.waInstances[name] = instance;
}
private async loadInstancesFromRedis() {
this.logger.verbose('Redis enabled');
const keys = await this.cache.keys();
if (keys?.length > 0) {
this.logger.verbose('Reading instance keys and setting instances');
await Promise.all(keys.map((k) => this.setInstance(k.split(':')[1], k.split(':')[2])));
} else {
this.logger.verbose('No instance keys found');
}
}
private async loadInstancesFromDatabasePostgres() {
this.logger.verbose('Database enabled');
const instances = await this.prismaRepository.instance.findMany();
if (instances.length === 0) {
this.logger.verbose('No instances found');
return;
}
@@ -402,11 +371,9 @@ 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;
}
@@ -414,21 +381,17 @@ export class WAMonitoringService {
}
private async loadInstancesFromFiles() {
this.logger.verbose('Store in files enabled');
const dir = opendirSync(INSTANCE_DIR, { encoding: 'utf-8' });
const instanceDirs = [];
for await (const dirent of dir) {
if (dirent.isDirectory()) {
instanceDirs.push(dirent.name);
} else {
this.logger.verbose('No instance files found');
}
}
await Promise.all(
instanceDirs.map(async (instanceName) => {
this.logger.verbose('Reading instance files and setting instances: ' + instanceName);
const files = readdirSync(join(INSTANCE_DIR, instanceName), { encoding: 'utf-8' });
if (files.length === 0) {
@@ -442,16 +405,13 @@ export class WAMonitoringService {
private removeInstance() {
this.eventEmitter.on('remove.instance', async (instanceName: string) => {
this.logger.verbose('remove instance: ' + instanceName);
try {
this.logger.verbose('instance: ' + instanceName + ' - removing from memory');
this.waInstances[instanceName] = undefined;
} catch (error) {
this.logger.error(error);
}
try {
this.logger.verbose('request cleaning up instance: ' + instanceName);
this.cleaningUp(instanceName);
this.cleaningStoreFiles(instanceName);
} finally {
@@ -459,10 +419,8 @@ export class WAMonitoringService {
}
});
this.eventEmitter.on('logout.instance', async (instanceName: string) => {
this.logger.verbose('logout instance: ' + instanceName);
try {
if (this.configService.get<Chatwoot>('CHATWOOT').ENABLED) this.waInstances[instanceName]?.clearCacheChatwoot();
this.logger.verbose('request cleaning up instance: ' + instanceName);
this.cleaningUp(instanceName);
} finally {
this.logger.warn(`Instance "${instanceName}" - LOGOUT`);
@@ -471,13 +429,10 @@ export class WAMonitoringService {
}
private noConnection() {
this.logger.verbose('checking instances without connection');
this.eventEmitter.on('no.connection', async (instanceName) => {
try {
this.logger.verbose('logging out instance: ' + instanceName);
await this.waInstances[instanceName]?.client?.logout('Log out instance: ' + instanceName);
this.logger.verbose('close connection instance: ' + instanceName);
this.waInstances[instanceName]?.client?.ws?.close();
this.waInstances[instanceName].instance.qrcode = { count: 0 };
@@ -495,7 +450,6 @@ export class WAMonitoringService {
}
private delInstanceFiles() {
this.logger.verbose('cron to delete instance files started');
setInterval(async () => {
const dir = opendirSync(INSTANCE_DIR, { encoding: 'utf-8' });
for await (const dirent of dir) {
@@ -511,7 +465,6 @@ export class WAMonitoringService {
});
}
});
this.logger.verbose('instance files deleted: ' + dirent.name);
}
}
}, 3600 * 1000 * 2);
@@ -520,10 +473,8 @@ export class WAMonitoringService {
private async deleteTempInstances() {
const shouldDelete = this.configService.get<boolean>('DEL_TEMP_INSTANCES');
if (!shouldDelete) {
this.logger.verbose('Temp instances deletion is disabled');
return;
}
this.logger.verbose('Cleaning up temp instances');
const instancesClosed = await this.prismaRepository.instance.findMany({ where: { connectionStatus: 'close' } });
let tempInstances = 0;
@@ -531,6 +482,6 @@ export class WAMonitoringService {
tempInstances++;
this.eventEmitter.emit('remove.instance', instance.id, 'inner');
});
this.logger.verbose('Temp instances removed: ' + tempInstances);
this.logger.log('Temp instances removed: ' + tempInstances);
}
}

View File

@@ -11,7 +11,6 @@ export class ProxyService {
private readonly logger = new Logger(ProxyService.name);
public create(instance: InstanceDto, data: ProxyDto) {
this.logger.verbose('create proxy: ' + instance.instanceName);
this.waMonitor.waInstances[instance.instanceName].setProxy(data);
return { proxy: { ...instance, proxy: data } };
@@ -19,7 +18,6 @@ export class ProxyService {
public async find(instance: InstanceDto): Promise<Proxy> {
try {
this.logger.verbose('find proxy: ' + instance.instanceName);
const result = await this.waMonitor.waInstances[instance.instanceName].findProxy();
if (Object.keys(result).length === 0) {

View File

@@ -9,7 +9,6 @@ export class SettingsService {
private readonly logger = new Logger(SettingsService.name);
public create(instance: InstanceDto, data: SettingsDto) {
this.logger.verbose('create settings: ' + instance.instanceName);
this.waMonitor.waInstances[instance.instanceName].setSettings(data);
return { settings: { ...instance, settings: data } };
@@ -17,7 +16,6 @@ export class SettingsService {
public async find(instance: InstanceDto): Promise<SettingsDto> {
try {
this.logger.verbose('find settings: ' + instance.instanceName);
const result = await this.waMonitor.waInstances[instance.instanceName].findSettings();
if (Object.keys(result).length === 0) {

View File

@@ -11,7 +11,6 @@ export class WebhookService {
private readonly logger = new Logger(WebhookService.name);
public create(instance: InstanceDto, data: WebhookDto) {
this.logger.verbose('create webhook: ' + instance.instanceName);
this.waMonitor.waInstances[instance.instanceName].setWebhook(data);
return { webhook: { ...instance, webhook: data } };
@@ -19,7 +18,6 @@ export class WebhookService {
public async find(instance: InstanceDto): Promise<Webhook> {
try {
this.logger.verbose('find webhook: ' + instance.instanceName);
const result = await this.waMonitor.waInstances[instance.instanceName].findWebhook();
if (Object.keys(result).length === 0) {