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

@ -1,6 +1,5 @@
import { Contact, Message, MessageUpdate } from '@prisma/client'; import { Contact, Message, MessageUpdate } from '@prisma/client';
import { Logger } from '../../config/logger.config';
import { import {
ArchiveChatDto, ArchiveChatDto,
BlockUserDto, BlockUserDto,
@ -21,118 +20,94 @@ import { InstanceDto } from '../dto/instance.dto';
import { Query } from '../repository/repository.service'; import { Query } from '../repository/repository.service';
import { WAMonitoringService } from '../services/monitor.service'; import { WAMonitoringService } from '../services/monitor.service';
const logger = new Logger('ChatController');
export class ChatController { export class ChatController {
constructor(private readonly waMonitor: WAMonitoringService) {} constructor(private readonly waMonitor: WAMonitoringService) {}
public async whatsappNumber({ instanceName }: InstanceDto, data: WhatsAppNumberDto) { public async whatsappNumber({ instanceName }: InstanceDto, data: WhatsAppNumberDto) {
logger.verbose('requested whatsappNumber from ' + instanceName + ' instance');
return await this.waMonitor.waInstances[instanceName].whatsappNumber(data); return await this.waMonitor.waInstances[instanceName].whatsappNumber(data);
} }
public async readMessage({ instanceName }: InstanceDto, data: ReadMessageDto) { public async readMessage({ instanceName }: InstanceDto, data: ReadMessageDto) {
logger.verbose('requested readMessage from ' + instanceName + ' instance');
return await this.waMonitor.waInstances[instanceName].markMessageAsRead(data); return await this.waMonitor.waInstances[instanceName].markMessageAsRead(data);
} }
public async archiveChat({ instanceName }: InstanceDto, data: ArchiveChatDto) { public async archiveChat({ instanceName }: InstanceDto, data: ArchiveChatDto) {
logger.verbose('requested archiveChat from ' + instanceName + ' instance');
return await this.waMonitor.waInstances[instanceName].archiveChat(data); return await this.waMonitor.waInstances[instanceName].archiveChat(data);
} }
public async markChatUnread({ instanceName }: InstanceDto, data: MarkChatUnreadDto) { public async markChatUnread({ instanceName }: InstanceDto, data: MarkChatUnreadDto) {
logger.verbose('requested markChatUnread from ' + instanceName + ' instance');
return await this.waMonitor.waInstances[instanceName].markChatUnread(data); return await this.waMonitor.waInstances[instanceName].markChatUnread(data);
} }
public async deleteMessage({ instanceName }: InstanceDto, data: DeleteMessage) { public async deleteMessage({ instanceName }: InstanceDto, data: DeleteMessage) {
logger.verbose('requested deleteMessage from ' + instanceName + ' instance');
return await this.waMonitor.waInstances[instanceName].deleteMessage(data); return await this.waMonitor.waInstances[instanceName].deleteMessage(data);
} }
public async fetchProfilePicture({ instanceName }: InstanceDto, data: NumberDto) { public async fetchProfilePicture({ instanceName }: InstanceDto, data: NumberDto) {
logger.verbose('requested fetchProfilePicture from ' + instanceName + ' instance');
return await this.waMonitor.waInstances[instanceName].profilePicture(data.number); return await this.waMonitor.waInstances[instanceName].profilePicture(data.number);
} }
public async fetchProfile({ instanceName }: InstanceDto, data: NumberDto) { public async fetchProfile({ instanceName }: InstanceDto, data: NumberDto) {
logger.verbose('requested fetchProfile from ' + instanceName + ' instance');
return await this.waMonitor.waInstances[instanceName].fetchProfile(instanceName, data.number); return await this.waMonitor.waInstances[instanceName].fetchProfile(instanceName, data.number);
} }
public async fetchContacts({ instanceName }: InstanceDto, query: Query<Contact>) { public async fetchContacts({ instanceName }: InstanceDto, query: Query<Contact>) {
logger.verbose('requested fetchContacts from ' + instanceName + ' instance');
return await this.waMonitor.waInstances[instanceName].fetchContacts(query); return await this.waMonitor.waInstances[instanceName].fetchContacts(query);
} }
public async getBase64FromMediaMessage({ instanceName }: InstanceDto, data: getBase64FromMediaMessageDto) { public async getBase64FromMediaMessage({ instanceName }: InstanceDto, data: getBase64FromMediaMessageDto) {
logger.verbose('requested getBase64FromMediaMessage from ' + instanceName + ' instance');
return await this.waMonitor.waInstances[instanceName].getBase64FromMediaMessage(data); return await this.waMonitor.waInstances[instanceName].getBase64FromMediaMessage(data);
} }
public async fetchMessages({ instanceName }: InstanceDto, query: Query<Message>) { public async fetchMessages({ instanceName }: InstanceDto, query: Query<Message>) {
logger.verbose('requested fetchMessages from ' + instanceName + ' instance');
return await this.waMonitor.waInstances[instanceName].fetchMessages(query); return await this.waMonitor.waInstances[instanceName].fetchMessages(query);
} }
public async fetchStatusMessage({ instanceName }: InstanceDto, query: Query<MessageUpdate>) { public async fetchStatusMessage({ instanceName }: InstanceDto, query: Query<MessageUpdate>) {
logger.verbose('requested fetchStatusMessage from ' + instanceName + ' instance');
return await this.waMonitor.waInstances[instanceName].fetchStatusMessage(query); return await this.waMonitor.waInstances[instanceName].fetchStatusMessage(query);
} }
public async fetchChats({ instanceName }: InstanceDto) { public async fetchChats({ instanceName }: InstanceDto) {
logger.verbose('requested fetchChats from ' + instanceName + ' instance');
return await this.waMonitor.waInstances[instanceName].fetchChats(); return await this.waMonitor.waInstances[instanceName].fetchChats();
} }
public async sendPresence({ instanceName }: InstanceDto, data: SendPresenceDto) { public async sendPresence({ instanceName }: InstanceDto, data: SendPresenceDto) {
logger.verbose('requested sendPresence from ' + instanceName + ' instance');
return await this.waMonitor.waInstances[instanceName].sendPresence(data); return await this.waMonitor.waInstances[instanceName].sendPresence(data);
} }
public async fetchPrivacySettings({ instanceName }: InstanceDto) { public async fetchPrivacySettings({ instanceName }: InstanceDto) {
logger.verbose('requested fetchPrivacySettings from ' + instanceName + ' instance');
return await this.waMonitor.waInstances[instanceName].fetchPrivacySettings(); return await this.waMonitor.waInstances[instanceName].fetchPrivacySettings();
} }
public async updatePrivacySettings({ instanceName }: InstanceDto, data: PrivacySettingDto) { public async updatePrivacySettings({ instanceName }: InstanceDto, data: PrivacySettingDto) {
logger.verbose('requested updatePrivacySettings from ' + instanceName + ' instance');
return await this.waMonitor.waInstances[instanceName].updatePrivacySettings(data); return await this.waMonitor.waInstances[instanceName].updatePrivacySettings(data);
} }
public async fetchBusinessProfile({ instanceName }: InstanceDto, data: ProfilePictureDto) { public async fetchBusinessProfile({ instanceName }: InstanceDto, data: ProfilePictureDto) {
logger.verbose('requested fetchBusinessProfile from ' + instanceName + ' instance');
return await this.waMonitor.waInstances[instanceName].fetchBusinessProfile(data.number); return await this.waMonitor.waInstances[instanceName].fetchBusinessProfile(data.number);
} }
public async updateProfileName({ instanceName }: InstanceDto, data: ProfileNameDto) { public async updateProfileName({ instanceName }: InstanceDto, data: ProfileNameDto) {
logger.verbose('requested updateProfileName from ' + instanceName + ' instance');
return await this.waMonitor.waInstances[instanceName].updateProfileName(data.name); return await this.waMonitor.waInstances[instanceName].updateProfileName(data.name);
} }
public async updateProfileStatus({ instanceName }: InstanceDto, data: ProfileStatusDto) { public async updateProfileStatus({ instanceName }: InstanceDto, data: ProfileStatusDto) {
logger.verbose('requested updateProfileStatus from ' + instanceName + ' instance');
return await this.waMonitor.waInstances[instanceName].updateProfileStatus(data.status); return await this.waMonitor.waInstances[instanceName].updateProfileStatus(data.status);
} }
public async updateProfilePicture({ instanceName }: InstanceDto, data: ProfilePictureDto) { public async updateProfilePicture({ instanceName }: InstanceDto, data: ProfilePictureDto) {
logger.verbose('requested updateProfilePicture from ' + instanceName + ' instance');
return await this.waMonitor.waInstances[instanceName].updateProfilePicture(data.picture); return await this.waMonitor.waInstances[instanceName].updateProfilePicture(data.picture);
} }
public async removeProfilePicture({ instanceName }: InstanceDto) { public async removeProfilePicture({ instanceName }: InstanceDto) {
logger.verbose('requested removeProfilePicture from ' + instanceName + ' instance');
return await this.waMonitor.waInstances[instanceName].removeProfilePicture(); return await this.waMonitor.waInstances[instanceName].removeProfilePicture();
} }
public async updateMessage({ instanceName }: InstanceDto, data: UpdateMessageDto) { public async updateMessage({ instanceName }: InstanceDto, data: UpdateMessageDto) {
logger.verbose('requested updateMessage from ' + instanceName + ' instance');
return await this.waMonitor.waInstances[instanceName].updateMessage(data); return await this.waMonitor.waInstances[instanceName].updateMessage(data);
} }
public async blockUser({ instanceName }: InstanceDto, data: BlockUserDto) { public async blockUser({ instanceName }: InstanceDto, data: BlockUserDto) {
logger.verbose('requested blockUser from ' + instanceName + ' instance');
return await this.waMonitor.waInstances[instanceName].blockUser(data); return await this.waMonitor.waInstances[instanceName].blockUser(data);
} }
} }

View File

@ -1,4 +1,3 @@
import { Logger } from '../../config/logger.config';
import { import {
AcceptGroupInvite, AcceptGroupInvite,
CreateGroupDto, CreateGroupDto,
@ -16,88 +15,70 @@ import {
import { InstanceDto } from '../dto/instance.dto'; import { InstanceDto } from '../dto/instance.dto';
import { WAMonitoringService } from '../services/monitor.service'; import { WAMonitoringService } from '../services/monitor.service';
const logger = new Logger('ChatController');
export class GroupController { export class GroupController {
constructor(private readonly waMonitor: WAMonitoringService) {} constructor(private readonly waMonitor: WAMonitoringService) {}
public async createGroup(instance: InstanceDto, create: CreateGroupDto) { public async createGroup(instance: InstanceDto, create: CreateGroupDto) {
logger.verbose('requested createGroup from ' + instance.instanceName + ' instance');
return await this.waMonitor.waInstances[instance.instanceName].createGroup(create); return await this.waMonitor.waInstances[instance.instanceName].createGroup(create);
} }
public async updateGroupPicture(instance: InstanceDto, update: GroupPictureDto) { public async updateGroupPicture(instance: InstanceDto, update: GroupPictureDto) {
logger.verbose('requested updateGroupPicture from ' + instance.instanceName + ' instance');
return await this.waMonitor.waInstances[instance.instanceName].updateGroupPicture(update); return await this.waMonitor.waInstances[instance.instanceName].updateGroupPicture(update);
} }
public async updateGroupSubject(instance: InstanceDto, update: GroupSubjectDto) { public async updateGroupSubject(instance: InstanceDto, update: GroupSubjectDto) {
logger.verbose('requested updateGroupSubject from ' + instance.instanceName + ' instance');
return await this.waMonitor.waInstances[instance.instanceName].updateGroupSubject(update); return await this.waMonitor.waInstances[instance.instanceName].updateGroupSubject(update);
} }
public async updateGroupDescription(instance: InstanceDto, update: GroupDescriptionDto) { public async updateGroupDescription(instance: InstanceDto, update: GroupDescriptionDto) {
logger.verbose('requested updateGroupDescription from ' + instance.instanceName + ' instance');
return await this.waMonitor.waInstances[instance.instanceName].updateGroupDescription(update); return await this.waMonitor.waInstances[instance.instanceName].updateGroupDescription(update);
} }
public async findGroupInfo(instance: InstanceDto, groupJid: GroupJid) { public async findGroupInfo(instance: InstanceDto, groupJid: GroupJid) {
logger.verbose('requested findGroupInfo from ' + instance.instanceName + ' instance');
return await this.waMonitor.waInstances[instance.instanceName].findGroup(groupJid); return await this.waMonitor.waInstances[instance.instanceName].findGroup(groupJid);
} }
public async fetchAllGroups(instance: InstanceDto, getPaticipants: GetParticipant) { public async fetchAllGroups(instance: InstanceDto, getPaticipants: GetParticipant) {
logger.verbose('requested fetchAllGroups from ' + instance.instanceName + ' instance');
return await this.waMonitor.waInstances[instance.instanceName].fetchAllGroups(getPaticipants); return await this.waMonitor.waInstances[instance.instanceName].fetchAllGroups(getPaticipants);
} }
public async inviteCode(instance: InstanceDto, groupJid: GroupJid) { public async inviteCode(instance: InstanceDto, groupJid: GroupJid) {
logger.verbose('requested inviteCode from ' + instance.instanceName + ' instance');
return await this.waMonitor.waInstances[instance.instanceName].inviteCode(groupJid); return await this.waMonitor.waInstances[instance.instanceName].inviteCode(groupJid);
} }
public async inviteInfo(instance: InstanceDto, inviteCode: GroupInvite) { public async inviteInfo(instance: InstanceDto, inviteCode: GroupInvite) {
logger.verbose('requested inviteInfo from ' + instance.instanceName + ' instance');
return await this.waMonitor.waInstances[instance.instanceName].inviteInfo(inviteCode); return await this.waMonitor.waInstances[instance.instanceName].inviteInfo(inviteCode);
} }
public async sendInvite(instance: InstanceDto, data: GroupSendInvite) { public async sendInvite(instance: InstanceDto, data: GroupSendInvite) {
logger.verbose('requested sendInvite from ' + instance.instanceName + ' instance');
return await this.waMonitor.waInstances[instance.instanceName].sendInvite(data); return await this.waMonitor.waInstances[instance.instanceName].sendInvite(data);
} }
public async acceptInviteCode(instance: InstanceDto, inviteCode: AcceptGroupInvite) { public async acceptInviteCode(instance: InstanceDto, inviteCode: AcceptGroupInvite) {
logger.verbose('requested acceptInviteCode from ' + instance.instanceName + ' instance');
return await this.waMonitor.waInstances[instance.instanceName].acceptInviteCode(inviteCode); return await this.waMonitor.waInstances[instance.instanceName].acceptInviteCode(inviteCode);
} }
public async revokeInviteCode(instance: InstanceDto, groupJid: GroupJid) { public async revokeInviteCode(instance: InstanceDto, groupJid: GroupJid) {
logger.verbose('requested revokeInviteCode from ' + instance.instanceName + ' instance');
return await this.waMonitor.waInstances[instance.instanceName].revokeInviteCode(groupJid); return await this.waMonitor.waInstances[instance.instanceName].revokeInviteCode(groupJid);
} }
public async findParticipants(instance: InstanceDto, groupJid: GroupJid) { public async findParticipants(instance: InstanceDto, groupJid: GroupJid) {
logger.verbose('requested findParticipants from ' + instance.instanceName + ' instance');
return await this.waMonitor.waInstances[instance.instanceName].findParticipants(groupJid); return await this.waMonitor.waInstances[instance.instanceName].findParticipants(groupJid);
} }
public async updateGParticipate(instance: InstanceDto, update: GroupUpdateParticipantDto) { public async updateGParticipate(instance: InstanceDto, update: GroupUpdateParticipantDto) {
logger.verbose('requested updateGParticipate from ' + instance.instanceName + ' instance');
return await this.waMonitor.waInstances[instance.instanceName].updateGParticipant(update); return await this.waMonitor.waInstances[instance.instanceName].updateGParticipant(update);
} }
public async updateGSetting(instance: InstanceDto, update: GroupUpdateSettingDto) { public async updateGSetting(instance: InstanceDto, update: GroupUpdateSettingDto) {
logger.verbose('requested updateGSetting from ' + instance.instanceName + ' instance');
return await this.waMonitor.waInstances[instance.instanceName].updateGSetting(update); return await this.waMonitor.waInstances[instance.instanceName].updateGSetting(update);
} }
public async toggleEphemeral(instance: InstanceDto, update: GroupToggleEphemeralDto) { public async toggleEphemeral(instance: InstanceDto, update: GroupToggleEphemeralDto) {
logger.verbose('requested toggleEphemeral from ' + instance.instanceName + ' instance');
return await this.waMonitor.waInstances[instance.instanceName].toggleEphemeral(update); return await this.waMonitor.waInstances[instance.instanceName].toggleEphemeral(update);
} }
public async leaveGroup(instance: InstanceDto, groupJid: GroupJid) { public async leaveGroup(instance: InstanceDto, groupJid: GroupJid) {
logger.verbose('requested leaveGroup from ' + instance.instanceName + ' instance');
return await this.waMonitor.waInstances[instance.instanceName].leaveGroup(groupJid); return await this.waMonitor.waInstances[instance.instanceName].leaveGroup(groupJid);
} }
} }

View File

@ -94,16 +94,12 @@ export class InstanceController {
proxy, proxy,
}: InstanceDto) { }: InstanceDto) {
try { try {
this.logger.verbose('requested createInstance from ' + instanceName + ' instance');
this.logger.verbose('checking duplicate token');
await this.authService.checkDuplicateToken(token); await this.authService.checkDuplicateToken(token);
if (!token && integration === Integration.WHATSAPP_BUSINESS) { if (!token && integration === Integration.WHATSAPP_BUSINESS) {
throw new BadRequestException('token is required'); throw new BadRequestException('token is required');
} }
this.logger.verbose('creating instance');
let instance: BaileysStartupService | BusinessStartupService; let instance: BaileysStartupService | BusinessStartupService;
if (integration === Integration.WHATSAPP_BUSINESS) { if (integration === Integration.WHATSAPP_BUSINESS) {
instance = new BusinessStartupService( instance = new BusinessStartupService(
@ -139,12 +135,9 @@ export class InstanceController {
instanceId: instanceId, instanceId: instanceId,
}); });
this.logger.verbose('instance: ' + instance.instanceName + ' created');
this.waMonitor.waInstances[instance.instanceName] = instance; this.waMonitor.waInstances[instance.instanceName] = instance;
this.waMonitor.delInstanceTime(instance.instanceName); this.waMonitor.delInstanceTime(instance.instanceName);
this.logger.verbose('generating hash');
const hash = await this.authService.generateHash( const hash = await this.authService.generateHash(
{ {
instanceName: instance.instanceName, instanceName: instance.instanceName,
@ -153,8 +146,6 @@ export class InstanceController {
token, token,
); );
this.logger.verbose('hash: ' + hash + ' generated');
let getWebhookEvents: string[]; let getWebhookEvents: string[];
if (webhook) { if (webhook) {
@ -162,7 +153,6 @@ export class InstanceController {
throw new BadRequestException('Invalid "url" property in webhook'); throw new BadRequestException('Invalid "url" property in webhook');
} }
this.logger.verbose('creating webhook');
try { try {
let newEvents: string[] = []; let newEvents: string[] = [];
if (webhookEvents.length === 0) { if (webhookEvents.length === 0) {
@ -214,7 +204,6 @@ export class InstanceController {
let getWebsocketEvents: string[]; let getWebsocketEvents: string[];
if (websocketEnabled) { if (websocketEnabled) {
this.logger.verbose('creating websocket');
try { try {
let newEvents: string[] = []; let newEvents: string[] = [];
if (websocketEvents.length === 0) { if (websocketEvents.length === 0) {
@ -254,7 +243,6 @@ export class InstanceController {
const websocketEventsJson: JsonValue = (await this.websocketService.find(instance)).events; const websocketEventsJson: JsonValue = (await this.websocketService.find(instance)).events;
// websocketEvents = (await this.websocketService.find(instance)).events;
getWebsocketEvents = Array.isArray(websocketEventsJson) getWebsocketEvents = Array.isArray(websocketEventsJson)
? websocketEventsJson.map((event) => String(event)) ? websocketEventsJson.map((event) => String(event))
: []; : [];
@ -266,7 +254,6 @@ export class InstanceController {
let getRabbitmqEvents: string[]; let getRabbitmqEvents: string[];
if (rabbitmqEnabled) { if (rabbitmqEnabled) {
this.logger.verbose('creating rabbitmq');
try { try {
let newEvents: string[] = []; let newEvents: string[] = [];
if (rabbitmqEvents.length === 0) { if (rabbitmqEvents.length === 0) {
@ -317,7 +304,6 @@ export class InstanceController {
let getSqsEvents: string[]; let getSqsEvents: string[];
if (sqsEnabled) { if (sqsEnabled) {
this.logger.verbose('creating sqs');
try { try {
let newEvents: string[] = []; let newEvents: string[] = [];
if (sqsEvents.length === 0) { if (sqsEvents.length === 0) {
@ -387,8 +373,6 @@ export class InstanceController {
throw new BadRequestException('Invalid "url" property in typebotUrl'); throw new BadRequestException('Invalid "url" property in typebotUrl');
} }
this.logger.verbose('creating typebot');
this.typebotService.create(instance, { this.typebotService.create(instance, {
enabled: true, enabled: true,
url: typebotUrl, url: typebotUrl,
@ -404,7 +388,6 @@ export class InstanceController {
} }
} }
this.logger.verbose('creating settings');
const settings: wa.LocalSettings = { const settings: wa.LocalSettings = {
rejectCall: rejectCall || false, rejectCall: rejectCall || false,
msgCall: msgCall || '', msgCall: msgCall || '',
@ -415,8 +398,6 @@ export class InstanceController {
syncFullHistory: syncFullHistory ?? false, syncFullHistory: syncFullHistory ?? false,
}; };
this.logger.verbose('settings: ' + JSON.stringify(settings));
this.settingsService.create(instance, settings); this.settingsService.create(instance, settings);
let webhookWaBusiness = null, let webhookWaBusiness = null,
@ -440,7 +421,6 @@ export class InstanceController {
let getQrcode: wa.QrCode; let getQrcode: wa.QrCode;
if (qrcode) { if (qrcode) {
this.logger.verbose('creating qrcode');
await instance.connectToWhatsapp(number); await instance.connectToWhatsapp(number);
await delay(5000); await delay(5000);
getQrcode = instance.qrCode; getQrcode = instance.qrCode;
@ -488,9 +468,6 @@ export class InstanceController {
qrcode: getQrcode, qrcode: getQrcode,
}; };
this.logger.verbose('instance created');
this.logger.verbose(result);
return result; return result;
} }
@ -612,13 +589,9 @@ export class InstanceController {
public async connectToWhatsapp({ instanceName, number = null }: InstanceDto) { public async connectToWhatsapp({ instanceName, number = null }: InstanceDto) {
try { try {
this.logger.verbose('requested connectToWhatsapp from ' + instanceName + ' instance');
const instance = this.waMonitor.waInstances[instanceName]; const instance = this.waMonitor.waInstances[instanceName];
const state = instance?.connectionStatus?.state; const state = instance?.connectionStatus?.state;
this.logger.verbose('state: ' + state);
if (!state) { if (!state) {
throw new BadRequestException('The "' + instanceName + '" instance does not exist'); throw new BadRequestException('The "' + instanceName + '" instance does not exist');
} }
@ -632,7 +605,6 @@ export class InstanceController {
} }
if (state == 'close') { if (state == 'close') {
this.logger.verbose('connecting');
await instance.connectToWhatsapp(number); await instance.connectToWhatsapp(number);
await delay(5000); await delay(5000);
@ -653,14 +625,11 @@ export class InstanceController {
public async restartInstance({ instanceName }: InstanceDto) { public async restartInstance({ instanceName }: InstanceDto) {
try { try {
this.logger.verbose('requested restartInstance from ' + instanceName + ' instance');
const instance = this.waMonitor.waInstances[instanceName]; const instance = this.waMonitor.waInstances[instanceName];
const state = instance?.connectionStatus?.state; const state = instance?.connectionStatus?.state;
switch (state) { switch (state) {
case 'open': case 'open':
this.logger.verbose('logging out instance: ' + instanceName);
if (this.configService.get<Chatwoot>('CHATWOOT').ENABLED) instance.clearCacheChatwoot(); if (this.configService.get<Chatwoot>('CHATWOOT').ENABLED) instance.clearCacheChatwoot();
await instance.reloadConnection(); await instance.reloadConnection();
await delay(2000); await delay(2000);
@ -675,7 +644,6 @@ export class InstanceController {
} }
public async connectionState({ instanceName }: InstanceDto) { public async connectionState({ instanceName }: InstanceDto) {
this.logger.verbose('requested connectionState from ' + instanceName + ' instance');
return { return {
instance: { instance: {
instanceName: instanceName, instanceName: instanceName,
@ -709,24 +677,19 @@ export class InstanceController {
} }
if (name) { if (name) {
this.logger.verbose('requested fetchInstances from ' + name + ' instance');
this.logger.verbose('instanceName: ' + name);
return this.waMonitor.instanceInfo(name, arrayReturn); return this.waMonitor.instanceInfo(name, arrayReturn);
} else if (instanceId || number) { } else if (instanceId || number) {
return this.waMonitor.instanceInfoById(instanceId, number); return this.waMonitor.instanceInfoById(instanceId, number);
} }
this.logger.verbose('requested fetchInstances (all instances)');
return this.waMonitor.instanceInfo(); return this.waMonitor.instanceInfo();
} }
public async setPresence({ instanceName }: InstanceDto, data: SetPresenceDto) { public async setPresence({ instanceName }: InstanceDto, data: SetPresenceDto) {
this.logger.verbose('requested sendPresence from ' + instanceName + ' instance');
return await this.waMonitor.waInstances[instanceName].setPresence(data); return await this.waMonitor.waInstances[instanceName].setPresence(data);
} }
public async logout({ instanceName }: InstanceDto) { public async logout({ instanceName }: InstanceDto) {
this.logger.verbose('requested logout from ' + instanceName + ' instance');
const { instance } = await this.connectionState({ instanceName }); const { instance } = await this.connectionState({ instanceName });
if (instance.state === 'close') { if (instance.state === 'close') {
@ -743,7 +706,6 @@ export class InstanceController {
} }
public async deleteInstance({ instanceName }: InstanceDto) { public async deleteInstance({ instanceName }: InstanceDto) {
this.logger.verbose('requested deleteInstance from ' + instanceName + ' instance');
const { instance } = await this.connectionState({ instanceName }); const { instance } = await this.connectionState({ instanceName });
if (instance.state === 'open') { if (instance.state === 'open') {
@ -755,13 +717,9 @@ export class InstanceController {
if (this.configService.get<Chatwoot>('CHATWOOT').ENABLED) waInstances?.clearCacheChatwoot(); if (this.configService.get<Chatwoot>('CHATWOOT').ENABLED) waInstances?.clearCacheChatwoot();
if (instance.state === 'connecting') { if (instance.state === 'connecting') {
this.logger.verbose('logging out instance: ' + instanceName);
await this.logout({ instanceName }); await this.logout({ instanceName });
} }
this.logger.verbose('deleting instance: ' + instanceName);
try { try {
waInstances?.sendDataWebhook(Events.INSTANCE_DELETE, { waInstances?.sendDataWebhook(Events.INSTANCE_DELETE, {
instanceName, instanceName,

View File

@ -1,20 +1,15 @@
import { Logger } from '../../config/logger.config';
import { InstanceDto } from '../dto/instance.dto'; import { InstanceDto } from '../dto/instance.dto';
import { HandleLabelDto } from '../dto/label.dto'; import { HandleLabelDto } from '../dto/label.dto';
import { WAMonitoringService } from '../services/monitor.service'; import { WAMonitoringService } from '../services/monitor.service';
const logger = new Logger('LabelController');
export class LabelController { export class LabelController {
constructor(private readonly waMonitor: WAMonitoringService) {} constructor(private readonly waMonitor: WAMonitoringService) {}
public async fetchLabels({ instanceName }: InstanceDto) { public async fetchLabels({ instanceName }: InstanceDto) {
logger.verbose('requested fetchLabels from ' + instanceName + ' instance');
return await this.waMonitor.waInstances[instanceName].fetchLabels(); return await this.waMonitor.waInstances[instanceName].fetchLabels();
} }
public async handleLabel({ instanceName }: InstanceDto, data: HandleLabelDto) { public async handleLabel({ instanceName }: InstanceDto, data: HandleLabelDto) {
logger.verbose('requested chat label change from ' + instanceName + ' instance');
return await this.waMonitor.waInstances[instanceName].handleLabel(data); return await this.waMonitor.waInstances[instanceName].handleLabel(data);
} }
} }

View File

@ -14,14 +14,11 @@ export class ProxyController {
constructor(private readonly proxyService: ProxyService, private readonly waMonitor: WAMonitoringService) {} constructor(private readonly proxyService: ProxyService, private readonly waMonitor: WAMonitoringService) {}
public async createProxy(instance: InstanceDto, data: ProxyDto) { public async createProxy(instance: InstanceDto, data: ProxyDto) {
logger.verbose('requested createProxy from ' + instance.instanceName + ' instance');
if (!this.waMonitor.waInstances[instance.instanceName]) { if (!this.waMonitor.waInstances[instance.instanceName]) {
throw new NotFoundException(`The "${instance.instanceName}" instance does not exist`); throw new NotFoundException(`The "${instance.instanceName}" instance does not exist`);
} }
if (!data.enabled) { if (!data.enabled) {
logger.verbose('proxy disabled');
data.host = ''; data.host = '';
data.port = ''; data.port = '';
data.protocol = ''; data.protocol = '';
@ -34,15 +31,12 @@ export class ProxyController {
if (!testProxy) { if (!testProxy) {
throw new BadRequestException('Invalid proxy'); throw new BadRequestException('Invalid proxy');
} }
logger.verbose('proxy enabled');
} }
return this.proxyService.create(instance, data); return this.proxyService.create(instance, data);
} }
public async findProxy(instance: InstanceDto) { public async findProxy(instance: InstanceDto) {
logger.verbose('requested findProxy from ' + instance.instanceName + ' instance');
if (!this.waMonitor.waInstances[instance.instanceName]) { if (!this.waMonitor.waInstances[instance.instanceName]) {
throw new NotFoundException(`The "${instance.instanceName}" instance does not exist`); throw new NotFoundException(`The "${instance.instanceName}" instance does not exist`);
} }
@ -51,24 +45,20 @@ export class ProxyController {
} }
public async testProxy(proxy: ProxyDto) { public async testProxy(proxy: ProxyDto) {
logger.verbose('requested testProxy');
try { try {
const serverIp = await axios.get('https://icanhazip.com/'); const serverIp = await axios.get('https://icanhazip.com/');
const response = await axios.get('https://icanhazip.com/', { const response = await axios.get('https://icanhazip.com/', {
httpsAgent: makeProxyAgent(proxy), httpsAgent: makeProxyAgent(proxy),
}); });
logger.verbose('[testProxy] from IP: ' + response?.data + ' To IP: ' + serverIp?.data);
return response?.data !== serverIp?.data; return response?.data !== serverIp?.data;
} catch (error) { } catch (error) {
if (axios.isAxiosError(error) && error.response?.data) { if (axios.isAxiosError(error) && error.response?.data) {
logger.error('testProxy error: ' + error.response.data); logger.error('testProxy error: ' + error.response.data);
} else if (axios.isAxiosError(error)) { } else if (axios.isAxiosError(error)) {
logger.error('testProxy error: '); logger.error('testProxy error: ');
logger.verbose(error.cause ?? error.message);
} else { } else {
logger.error('testProxy error: '); logger.error('testProxy error: ');
logger.verbose(error);
} }
return false; return false;
} }

View File

@ -1,6 +1,5 @@
import { isBase64, isURL } from 'class-validator'; import { isBase64, isURL } from 'class-validator';
import { Logger } from '../../config/logger.config';
import { BadRequestException } from '../../exceptions'; import { BadRequestException } from '../../exceptions';
import { InstanceDto } from '../dto/instance.dto'; import { InstanceDto } from '../dto/instance.dto';
import { import {
@ -19,24 +18,18 @@ import {
} from '../dto/sendMessage.dto'; } from '../dto/sendMessage.dto';
import { WAMonitoringService } from '../services/monitor.service'; import { WAMonitoringService } from '../services/monitor.service';
const logger = new Logger('MessageRouter');
export class SendMessageController { export class SendMessageController {
constructor(private readonly waMonitor: WAMonitoringService) {} constructor(private readonly waMonitor: WAMonitoringService) {}
public async sendText({ instanceName }: InstanceDto, data: SendTextDto) { public async sendText({ instanceName }: InstanceDto, data: SendTextDto) {
logger.verbose('requested sendText from ' + instanceName + ' instance');
return await this.waMonitor.waInstances[instanceName].textMessage(data); return await this.waMonitor.waInstances[instanceName].textMessage(data);
} }
public async sendTemplate({ instanceName }: InstanceDto, data: SendTemplateDto) { public async sendTemplate({ instanceName }: InstanceDto, data: SendTemplateDto) {
logger.verbose('requested sendList from ' + instanceName + ' instance');
return await this.waMonitor.waInstances[instanceName].templateMessage(data); return await this.waMonitor.waInstances[instanceName].templateMessage(data);
} }
public async sendMedia({ instanceName }: InstanceDto, data: SendMediaDto) { public async sendMedia({ instanceName }: InstanceDto, data: SendMediaDto) {
logger.verbose('requested sendMedia from ' + instanceName + ' instance');
if ( if (
isBase64(data?.mediaMessage?.media) && isBase64(data?.mediaMessage?.media) &&
!data?.mediaMessage?.fileName && !data?.mediaMessage?.fileName &&
@ -45,7 +38,6 @@ export class SendMessageController {
throw new BadRequestException('For base64 the file name must be informed.'); throw new BadRequestException('For base64 the file name must be informed.');
} }
logger.verbose('isURL: ' + isURL(data?.mediaMessage?.media) + ', isBase64: ' + isBase64(data?.mediaMessage?.media));
if (isURL(data?.mediaMessage?.media) || isBase64(data?.mediaMessage?.media)) { if (isURL(data?.mediaMessage?.media) || isBase64(data?.mediaMessage?.media)) {
return await this.waMonitor.waInstances[instanceName].mediaMessage(data); return await this.waMonitor.waInstances[instanceName].mediaMessage(data);
} }
@ -53,11 +45,6 @@ export class SendMessageController {
} }
public async sendSticker({ instanceName }: InstanceDto, data: SendStickerDto) { public async sendSticker({ instanceName }: InstanceDto, data: SendStickerDto) {
logger.verbose('requested sendSticker from ' + instanceName + ' instance');
logger.verbose(
'isURL: ' + isURL(data?.stickerMessage?.image) + ', isBase64: ' + isBase64(data?.stickerMessage?.image),
);
if (isURL(data.stickerMessage.image) || isBase64(data.stickerMessage.image)) { if (isURL(data.stickerMessage.image) || isBase64(data.stickerMessage.image)) {
return await this.waMonitor.waInstances[instanceName].mediaSticker(data); return await this.waMonitor.waInstances[instanceName].mediaSticker(data);
} }
@ -65,9 +52,6 @@ export class SendMessageController {
} }
public async sendWhatsAppAudio({ instanceName }: InstanceDto, data: SendAudioDto) { public async sendWhatsAppAudio({ instanceName }: InstanceDto, data: SendAudioDto) {
logger.verbose('requested sendWhatsAppAudio from ' + instanceName + ' instance');
logger.verbose('isURL: ' + isURL(data?.audioMessage?.audio) + ', isBase64: ' + isBase64(data?.audioMessage?.audio));
if (isURL(data.audioMessage.audio) || isBase64(data.audioMessage.audio)) { if (isURL(data.audioMessage.audio) || isBase64(data.audioMessage.audio)) {
return await this.waMonitor.waInstances[instanceName].audioWhatsapp(data); return await this.waMonitor.waInstances[instanceName].audioWhatsapp(data);
} }
@ -75,7 +59,6 @@ export class SendMessageController {
} }
public async sendButtons({ instanceName }: InstanceDto, data: SendButtonDto) { public async sendButtons({ instanceName }: InstanceDto, data: SendButtonDto) {
logger.verbose('requested sendButtons from ' + instanceName + ' instance');
if (isBase64(data.buttonMessage.mediaMessage?.media) && !data.buttonMessage.mediaMessage?.fileName) { if (isBase64(data.buttonMessage.mediaMessage?.media) && !data.buttonMessage.mediaMessage?.fileName) {
throw new BadRequestException('For bse64 the file name must be informed.'); throw new BadRequestException('For bse64 the file name must be informed.');
} }
@ -83,22 +66,18 @@ export class SendMessageController {
} }
public async sendLocation({ instanceName }: InstanceDto, data: SendLocationDto) { public async sendLocation({ instanceName }: InstanceDto, data: SendLocationDto) {
logger.verbose('requested sendLocation from ' + instanceName + ' instance');
return await this.waMonitor.waInstances[instanceName].locationMessage(data); return await this.waMonitor.waInstances[instanceName].locationMessage(data);
} }
public async sendList({ instanceName }: InstanceDto, data: SendListDto) { public async sendList({ instanceName }: InstanceDto, data: SendListDto) {
logger.verbose('requested sendList from ' + instanceName + ' instance');
return await this.waMonitor.waInstances[instanceName].listMessage(data); return await this.waMonitor.waInstances[instanceName].listMessage(data);
} }
public async sendContact({ instanceName }: InstanceDto, data: SendContactDto) { public async sendContact({ instanceName }: InstanceDto, data: SendContactDto) {
logger.verbose('requested sendContact from ' + instanceName + ' instance');
return await this.waMonitor.waInstances[instanceName].contactMessage(data); return await this.waMonitor.waInstances[instanceName].contactMessage(data);
} }
public async sendReaction({ instanceName }: InstanceDto, data: SendReactionDto) { public async sendReaction({ instanceName }: InstanceDto, data: SendReactionDto) {
logger.verbose('requested sendReaction from ' + instanceName + ' instance');
if (!data.reactionMessage.reaction.match(/[^()\w\sà-ú"-+]+/)) { if (!data.reactionMessage.reaction.match(/[^()\w\sà-ú"-+]+/)) {
throw new BadRequestException('"reaction" must be an emoji'); throw new BadRequestException('"reaction" must be an emoji');
} }
@ -106,12 +85,10 @@ export class SendMessageController {
} }
public async sendPoll({ instanceName }: InstanceDto, data: SendPollDto) { public async sendPoll({ instanceName }: InstanceDto, data: SendPollDto) {
logger.verbose('requested sendPoll from ' + instanceName + ' instance');
return await this.waMonitor.waInstances[instanceName].pollMessage(data); return await this.waMonitor.waInstances[instanceName].pollMessage(data);
} }
public async sendStatus({ instanceName }: InstanceDto, data: SendStatusDto) { public async sendStatus({ instanceName }: InstanceDto, data: SendStatusDto) {
logger.verbose('requested sendStatus from ' + instanceName + ' instance');
return await this.waMonitor.waInstances[instanceName].statusMessage(data); return await this.waMonitor.waInstances[instanceName].statusMessage(data);
} }
} }

View File

@ -1,21 +1,15 @@
import { Logger } from '../../config/logger.config';
import { InstanceDto } from '../dto/instance.dto'; import { InstanceDto } from '../dto/instance.dto';
import { SettingsDto } from '../dto/settings.dto'; import { SettingsDto } from '../dto/settings.dto';
import { SettingsService } from '../services/settings.service'; import { SettingsService } from '../services/settings.service';
const logger = new Logger('SettingsController');
export class SettingsController { export class SettingsController {
constructor(private readonly settingsService: SettingsService) {} constructor(private readonly settingsService: SettingsService) {}
public async createSettings(instance: InstanceDto, data: SettingsDto) { public async createSettings(instance: InstanceDto, data: SettingsDto) {
logger.verbose('requested createSettings from ' + instance.instanceName + ' instance');
return this.settingsService.create(instance, data); return this.settingsService.create(instance, data);
} }
public async findSettings(instance: InstanceDto) { public async findSettings(instance: InstanceDto) {
logger.verbose('requested findSettings from ' + instance.instanceName + ' instance');
const settings = this.settingsService.find(instance); const settings = this.settingsService.find(instance);
return settings; return settings;
} }

View File

@ -1,20 +1,15 @@
import { isURL } from 'class-validator'; import { isURL } from 'class-validator';
import { Logger } from '../../config/logger.config';
import { BadRequestException } from '../../exceptions'; import { BadRequestException } from '../../exceptions';
import { InstanceDto } from '../dto/instance.dto'; import { InstanceDto } from '../dto/instance.dto';
import { WebhookDto } from '../dto/webhook.dto'; import { WebhookDto } from '../dto/webhook.dto';
import { WAMonitoringService } from '../services/monitor.service'; import { WAMonitoringService } from '../services/monitor.service';
import { WebhookService } from '../services/webhook.service'; import { WebhookService } from '../services/webhook.service';
const logger = new Logger('WebhookController');
export class WebhookController { export class WebhookController {
constructor(private readonly webhookService: WebhookService, private readonly waMonitor: WAMonitoringService) {} constructor(private readonly webhookService: WebhookService, private readonly waMonitor: WAMonitoringService) {}
public async createWebhook(instance: InstanceDto, data: WebhookDto) { public async createWebhook(instance: InstanceDto, data: WebhookDto) {
logger.verbose('requested createWebhook from ' + instance.instanceName + ' instance');
if (!isURL(data.url, { require_tld: false })) { if (!isURL(data.url, { require_tld: false })) {
throw new BadRequestException('Invalid "url" property'); throw new BadRequestException('Invalid "url" property');
} }
@ -22,11 +17,9 @@ export class WebhookController {
data.enabled = data.enabled ?? true; data.enabled = data.enabled ?? true;
if (!data.enabled) { if (!data.enabled) {
logger.verbose('webhook disabled');
data.url = ''; data.url = '';
data.events = []; data.events = [];
} else if (data.events.length === 0) { } else if (data.events.length === 0) {
logger.verbose('webhook events empty');
data.events = [ data.events = [
'APPLICATION_STARTUP', 'APPLICATION_STARTUP',
'QRCODE_UPDATED', 'QRCODE_UPDATED',
@ -59,12 +52,10 @@ export class WebhookController {
} }
public async findWebhook(instance: InstanceDto) { public async findWebhook(instance: InstanceDto) {
logger.verbose('requested findWebhook from ' + instance.instanceName + ' instance');
return this.webhookService.find(instance); return this.webhookService.find(instance);
} }
public async receiveWebhook(instance: InstanceDto, data: any) { public async receiveWebhook(instance: InstanceDto, data: any) {
logger.verbose('requested receiveWebhook from ' + instance.instanceName + ' instance');
return await this.waMonitor.waInstances[instance.instanceName].connectToWhatsapp(data); return await this.waMonitor.waInstances[instance.instanceName].connectToWhatsapp(data);
} }
} }

View File

@ -2,7 +2,6 @@ import { isURL } from 'class-validator';
import { CacheEngine } from '../../../../cache/cacheengine'; import { CacheEngine } from '../../../../cache/cacheengine';
import { Chatwoot, ConfigService, HttpServer } from '../../../../config/env.config'; import { Chatwoot, ConfigService, HttpServer } from '../../../../config/env.config';
import { Logger } from '../../../../config/logger.config';
import { BadRequestException } from '../../../../exceptions'; import { BadRequestException } from '../../../../exceptions';
import { InstanceDto } from '../../../dto/instance.dto'; import { InstanceDto } from '../../../dto/instance.dto';
import { PrismaRepository } from '../../../repository/repository.service'; import { PrismaRepository } from '../../../repository/repository.service';
@ -11,8 +10,6 @@ import { CacheService } from '../../../services/cache.service';
import { ChatwootDto } from '../dto/chatwoot.dto'; import { ChatwootDto } from '../dto/chatwoot.dto';
import { ChatwootService } from '../services/chatwoot.service'; import { ChatwootService } from '../services/chatwoot.service';
const logger = new Logger('ChatwootController');
export class ChatwootController { export class ChatwootController {
constructor( constructor(
private readonly chatwootService: ChatwootService, private readonly chatwootService: ChatwootService,
@ -23,8 +20,6 @@ export class ChatwootController {
public async createChatwoot(instance: InstanceDto, data: ChatwootDto) { public async createChatwoot(instance: InstanceDto, data: ChatwootDto) {
if (!this.configService.get<Chatwoot>('CHATWOOT').ENABLED) throw new BadRequestException('Chatwoot is disabled'); if (!this.configService.get<Chatwoot>('CHATWOOT').ENABLED) throw new BadRequestException('Chatwoot is disabled');
logger.verbose('requested createChatwoot from ' + instance.instanceName + ' instance');
if (data.enabled) { if (data.enabled) {
if (!isURL(data.url, { require_tld: false })) { if (!isURL(data.url, { require_tld: false })) {
throw new BadRequestException('url is not valid'); throw new BadRequestException('url is not valid');
@ -45,7 +40,6 @@ export class ChatwootController {
} }
if (!data.enabled) { if (!data.enabled) {
logger.verbose('chatwoot disabled');
data.accountId = ''; data.accountId = '';
data.token = ''; data.token = '';
data.url = ''; data.url = '';
@ -80,7 +74,6 @@ export class ChatwootController {
public async findChatwoot(instance: InstanceDto) { public async findChatwoot(instance: InstanceDto) {
if (!this.configService.get<Chatwoot>('CHATWOOT').ENABLED) throw new BadRequestException('Chatwoot is disabled'); if (!this.configService.get<Chatwoot>('CHATWOOT').ENABLED) throw new BadRequestException('Chatwoot is disabled');
logger.verbose('requested findChatwoot from ' + instance.instanceName + ' instance');
const result = await this.chatwootService.find(instance); const result = await this.chatwootService.find(instance);
const urlServer = this.configService.get<HttpServer>('SERVER').URL; const urlServer = this.configService.get<HttpServer>('SERVER').URL;
@ -108,8 +101,6 @@ export class ChatwootController {
public async receiveWebhook(instance: InstanceDto, data: any) { public async receiveWebhook(instance: InstanceDto, data: any) {
if (!this.configService.get<Chatwoot>('CHATWOOT').ENABLED) throw new BadRequestException('Chatwoot is disabled'); if (!this.configService.get<Chatwoot>('CHATWOOT').ENABLED) throw new BadRequestException('Chatwoot is disabled');
logger.verbose('requested receiveWebhook from ' + instance.instanceName + ' instance');
const chatwootCache = new CacheService(new CacheEngine(this.configService, ChatwootService.name).getEngine()); const chatwootCache = new CacheService(new CacheEngine(this.configService, ChatwootService.name).getEngine());
const chatwootService = new ChatwootService(waMonitor, this.configService, this.prismaRepository, chatwootCache); const chatwootService = new ChatwootService(waMonitor, this.configService, this.prismaRepository, chatwootCache);

View File

@ -27,7 +27,6 @@ class Postgres {
}); });
try { try {
this.logger.verbose('connecting new postgres');
this.connected = true; this.connected = true;
} catch (e) { } catch (e) {
this.connected = false; this.connected = false;

View File

@ -1,6 +1,5 @@
import { RequestHandler, Router } from 'express'; import { RequestHandler, Router } from 'express';
import { Logger } from '../../../../config/logger.config';
import { chatwootSchema, instanceNameSchema } from '../../../../validate/validate.schema'; import { chatwootSchema, instanceNameSchema } from '../../../../validate/validate.schema';
import { RouterBroker } from '../../../abstract/abstract.router'; import { RouterBroker } from '../../../abstract/abstract.router';
import { InstanceDto } from '../../../dto/instance.dto'; import { InstanceDto } from '../../../dto/instance.dto';
@ -8,19 +7,11 @@ import { HttpStatus } from '../../../routes/index.router';
import { chatwootController } from '../../../server.module'; import { chatwootController } from '../../../server.module';
import { ChatwootDto } from '../dto/chatwoot.dto'; import { ChatwootDto } from '../dto/chatwoot.dto';
const logger = new Logger('ChatwootRouter');
export class ChatwootRouter extends RouterBroker { export class ChatwootRouter extends RouterBroker {
constructor(...guards: RequestHandler[]) { constructor(...guards: RequestHandler[]) {
super(); super();
this.router this.router
.post(this.routerPath('set'), ...guards, async (req, res) => { .post(this.routerPath('set'), ...guards, async (req, res) => {
logger.verbose('request received in setChatwoot');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<ChatwootDto>({ const response = await this.dataValidate<ChatwootDto>({
request: req, request: req,
schema: chatwootSchema, schema: chatwootSchema,
@ -31,12 +22,6 @@ export class ChatwootRouter extends RouterBroker {
res.status(HttpStatus.CREATED).json(response); res.status(HttpStatus.CREATED).json(response);
}) })
.get(this.routerPath('find'), ...guards, async (req, res) => { .get(this.routerPath('find'), ...guards, async (req, res) => {
logger.verbose('request received in findChatwoot');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<InstanceDto>({ const response = await this.dataValidate<InstanceDto>({
request: req, request: req,
schema: instanceNameSchema, schema: instanceNameSchema,
@ -47,12 +32,6 @@ export class ChatwootRouter extends RouterBroker {
res.status(HttpStatus.OK).json(response); res.status(HttpStatus.OK).json(response);
}) })
.post(this.routerPath('webhook'), async (req, res) => { .post(this.routerPath('webhook'), async (req, res) => {
logger.verbose('request received in findChatwoot');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<InstanceDto>({ const response = await this.dataValidate<InstanceDto>({
request: req, request: req,
schema: instanceNameSchema, schema: instanceNameSchema,

File diff suppressed because it is too large Load Diff

View File

@ -1,27 +1,20 @@
import { configService, Rabbitmq } from '../../../../config/env.config'; import { configService, Rabbitmq } from '../../../../config/env.config';
import { Logger } from '../../../../config/logger.config';
import { BadRequestException } from '../../../../exceptions'; import { BadRequestException } from '../../../../exceptions';
import { InstanceDto } from '../../../dto/instance.dto'; import { InstanceDto } from '../../../dto/instance.dto';
import { RabbitmqDto } from '../dto/rabbitmq.dto'; import { RabbitmqDto } from '../dto/rabbitmq.dto';
import { RabbitmqService } from '../services/rabbitmq.service'; import { RabbitmqService } from '../services/rabbitmq.service';
const logger = new Logger('RabbitmqController');
export class RabbitmqController { export class RabbitmqController {
constructor(private readonly rabbitmqService: RabbitmqService) {} constructor(private readonly rabbitmqService: RabbitmqService) {}
public async createRabbitmq(instance: InstanceDto, data: RabbitmqDto) { public async createRabbitmq(instance: InstanceDto, data: RabbitmqDto) {
if (!configService.get<Rabbitmq>('RABBITMQ').ENABLED) throw new BadRequestException('Rabbitmq is disabled'); if (!configService.get<Rabbitmq>('RABBITMQ').ENABLED) throw new BadRequestException('Rabbitmq is disabled');
logger.verbose('requested createRabbitmq from ' + instance.instanceName + ' instance');
if (!data.enabled) { if (!data.enabled) {
logger.verbose('rabbitmq disabled');
data.events = []; data.events = [];
} }
if (data.events.length === 0) { if (data.events.length === 0) {
logger.verbose('rabbitmq events empty');
data.events = [ data.events = [
'APPLICATION_STARTUP', 'APPLICATION_STARTUP',
'QRCODE_UPDATED', 'QRCODE_UPDATED',
@ -54,7 +47,6 @@ export class RabbitmqController {
} }
public async findRabbitmq(instance: InstanceDto) { public async findRabbitmq(instance: InstanceDto) {
logger.verbose('requested findRabbitmq from ' + instance.instanceName + ' instance');
return this.rabbitmqService.find(instance); return this.rabbitmqService.find(instance);
} }
} }

View File

@ -1,6 +1,5 @@
import { RequestHandler, Router } from 'express'; import { RequestHandler, Router } from 'express';
import { Logger } from '../../../../config/logger.config';
import { instanceNameSchema, rabbitmqSchema } from '../../../../validate/validate.schema'; import { instanceNameSchema, rabbitmqSchema } from '../../../../validate/validate.schema';
import { RouterBroker } from '../../../abstract/abstract.router'; import { RouterBroker } from '../../../abstract/abstract.router';
import { InstanceDto } from '../../../dto/instance.dto'; import { InstanceDto } from '../../../dto/instance.dto';
@ -8,19 +7,11 @@ import { HttpStatus } from '../../../routes/index.router';
import { rabbitmqController } from '../../../server.module'; import { rabbitmqController } from '../../../server.module';
import { RabbitmqDto } from '../dto/rabbitmq.dto'; import { RabbitmqDto } from '../dto/rabbitmq.dto';
const logger = new Logger('RabbitmqRouter');
export class RabbitmqRouter extends RouterBroker { export class RabbitmqRouter extends RouterBroker {
constructor(...guards: RequestHandler[]) { constructor(...guards: RequestHandler[]) {
super(); super();
this.router this.router
.post(this.routerPath('set'), ...guards, async (req, res) => { .post(this.routerPath('set'), ...guards, async (req, res) => {
logger.verbose('request received in setRabbitmq');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<RabbitmqDto>({ const response = await this.dataValidate<RabbitmqDto>({
request: req, request: req,
schema: rabbitmqSchema, schema: rabbitmqSchema,
@ -31,12 +22,6 @@ export class RabbitmqRouter extends RouterBroker {
res.status(HttpStatus.CREATED).json(response); res.status(HttpStatus.CREATED).json(response);
}) })
.get(this.routerPath('find'), ...guards, async (req, res) => { .get(this.routerPath('find'), ...guards, async (req, res) => {
logger.verbose('request received in findRabbitmq');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<InstanceDto>({ const response = await this.dataValidate<InstanceDto>({
request: req, request: req,
schema: instanceNameSchema, schema: instanceNameSchema,

View File

@ -12,7 +12,6 @@ export class RabbitmqService {
private readonly logger = new Logger(RabbitmqService.name); private readonly logger = new Logger(RabbitmqService.name);
public create(instance: InstanceDto, data: RabbitmqDto) { public create(instance: InstanceDto, data: RabbitmqDto) {
this.logger.verbose('create rabbitmq: ' + instance.instanceName);
this.waMonitor.waInstances[instance.instanceName].setRabbitmq(data); this.waMonitor.waInstances[instance.instanceName].setRabbitmq(data);
initQueues(instance.instanceName, data.events); initQueues(instance.instanceName, data.events);
@ -21,7 +20,6 @@ export class RabbitmqService {
public async find(instance: InstanceDto): Promise<Rabbitmq> { public async find(instance: InstanceDto): Promise<Rabbitmq> {
try { try {
this.logger.verbose('find rabbitmq: ' + instance.instanceName);
const result = await this.waMonitor.waInstances[instance.instanceName].findRabbitmq(); const result = await this.waMonitor.waInstances[instance.instanceName].findRabbitmq();
if (Object.keys(result).length === 0) { if (Object.keys(result).length === 0) {

View File

@ -1,26 +1,20 @@
import { configService, Sqs } from '../../../../config/env.config'; import { configService, Sqs } from '../../../../config/env.config';
import { Logger } from '../../../../config/logger.config';
import { BadRequestException } from '../../../../exceptions'; import { BadRequestException } from '../../../../exceptions';
import { InstanceDto } from '../../../dto/instance.dto'; import { InstanceDto } from '../../../dto/instance.dto';
import { SqsDto } from '../dto/sqs.dto'; import { SqsDto } from '../dto/sqs.dto';
import { SqsService } from '../services/sqs.service'; import { SqsService } from '../services/sqs.service';
const logger = new Logger('SqsController');
export class SqsController { export class SqsController {
constructor(private readonly sqsService: SqsService) {} constructor(private readonly sqsService: SqsService) {}
public async createSqs(instance: InstanceDto, data: SqsDto) { public async createSqs(instance: InstanceDto, data: SqsDto) {
if (!configService.get<Sqs>('SQS').ENABLED) throw new BadRequestException('Sqs is disabled'); if (!configService.get<Sqs>('SQS').ENABLED) throw new BadRequestException('Sqs is disabled');
logger.verbose('requested createSqs from ' + instance.instanceName + ' instance');
if (!data.enabled) { if (!data.enabled) {
logger.verbose('sqs disabled');
data.events = []; data.events = [];
} }
if (data.events.length === 0) { if (data.events.length === 0) {
logger.verbose('sqs events empty');
data.events = [ data.events = [
'APPLICATION_STARTUP', 'APPLICATION_STARTUP',
'QRCODE_UPDATED', 'QRCODE_UPDATED',
@ -53,7 +47,6 @@ export class SqsController {
} }
public async findSqs(instance: InstanceDto) { public async findSqs(instance: InstanceDto) {
logger.verbose('requested findSqs from ' + instance.instanceName + ' instance');
return this.sqsService.find(instance); return this.sqsService.find(instance);
} }
} }

View File

@ -1,6 +1,5 @@
import { RequestHandler, Router } from 'express'; import { RequestHandler, Router } from 'express';
import { Logger } from '../../../../config/logger.config';
import { instanceNameSchema, sqsSchema } from '../../../../validate/validate.schema'; import { instanceNameSchema, sqsSchema } from '../../../../validate/validate.schema';
import { RouterBroker } from '../../../abstract/abstract.router'; import { RouterBroker } from '../../../abstract/abstract.router';
import { InstanceDto } from '../../../dto/instance.dto'; import { InstanceDto } from '../../../dto/instance.dto';
@ -8,19 +7,11 @@ import { HttpStatus } from '../../../routes/index.router';
import { sqsController } from '../../../server.module'; import { sqsController } from '../../../server.module';
import { SqsDto } from '../dto/sqs.dto'; import { SqsDto } from '../dto/sqs.dto';
const logger = new Logger('SqsRouter');
export class SqsRouter extends RouterBroker { export class SqsRouter extends RouterBroker {
constructor(...guards: RequestHandler[]) { constructor(...guards: RequestHandler[]) {
super(); super();
this.router this.router
.post(this.routerPath('set'), ...guards, async (req, res) => { .post(this.routerPath('set'), ...guards, async (req, res) => {
logger.verbose('request received in setSqs');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<SqsDto>({ const response = await this.dataValidate<SqsDto>({
request: req, request: req,
schema: sqsSchema, schema: sqsSchema,
@ -31,12 +22,6 @@ export class SqsRouter extends RouterBroker {
res.status(HttpStatus.CREATED).json(response); res.status(HttpStatus.CREATED).json(response);
}) })
.get(this.routerPath('find'), ...guards, async (req, res) => { .get(this.routerPath('find'), ...guards, async (req, res) => {
logger.verbose('request received in findSqs');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<InstanceDto>({ const response = await this.dataValidate<InstanceDto>({
request: req, request: req,
schema: instanceNameSchema, schema: instanceNameSchema,

View File

@ -12,7 +12,6 @@ export class SqsService {
private readonly logger = new Logger(SqsService.name); private readonly logger = new Logger(SqsService.name);
public create(instance: InstanceDto, data: SqsDto) { public create(instance: InstanceDto, data: SqsDto) {
this.logger.verbose('create sqs: ' + instance.instanceName);
this.waMonitor.waInstances[instance.instanceName].setSqs(data); this.waMonitor.waInstances[instance.instanceName].setSqs(data);
initQueues(instance.instanceName, data.events); initQueues(instance.instanceName, data.events);
@ -21,7 +20,6 @@ export class SqsService {
public async find(instance: InstanceDto): Promise<Sqs> { public async find(instance: InstanceDto): Promise<Sqs> {
try { try {
this.logger.verbose('find sqs: ' + instance.instanceName);
const result = await this.waMonitor.waInstances[instance.instanceName].findSqs(); const result = await this.waMonitor.waInstances[instance.instanceName].findSqs();
if (Object.keys(result).length === 0) { if (Object.keys(result).length === 0) {

View File

@ -1,22 +1,16 @@
import { configService, Typebot } from '../../../../config/env.config'; import { configService, Typebot } from '../../../../config/env.config';
import { Logger } from '../../../../config/logger.config';
import { BadRequestException } from '../../../../exceptions'; import { BadRequestException } from '../../../../exceptions';
import { InstanceDto } from '../../../dto/instance.dto'; import { InstanceDto } from '../../../dto/instance.dto';
import { TypebotDto } from '../dto/typebot.dto'; import { TypebotDto } from '../dto/typebot.dto';
import { TypebotService } from '../services/typebot.service'; import { TypebotService } from '../services/typebot.service';
const logger = new Logger('TypebotController');
export class TypebotController { export class TypebotController {
constructor(private readonly typebotService: TypebotService) {} constructor(private readonly typebotService: TypebotService) {}
public async createTypebot(instance: InstanceDto, data: TypebotDto) { public async createTypebot(instance: InstanceDto, data: TypebotDto) {
if (!configService.get<Typebot>('TYPEBOT').ENABLED) throw new BadRequestException('Typebot is disabled'); if (!configService.get<Typebot>('TYPEBOT').ENABLED) throw new BadRequestException('Typebot is disabled');
logger.verbose('requested createTypebot from ' + instance.instanceName + ' instance');
if (!data.enabled) { if (!data.enabled) {
logger.verbose('typebot disabled');
data.url = ''; data.url = '';
data.typebot = ''; data.typebot = '';
data.expire = 0; data.expire = 0;
@ -25,7 +19,6 @@ export class TypebotController {
const saveData = await this.typebotService.find(instance); const saveData = await this.typebotService.find(instance);
if (saveData.enabled) { if (saveData.enabled) {
logger.verbose('typebot enabled');
data.sessions = saveData.sessions; data.sessions = saveData.sessions;
} }
} }
@ -36,21 +29,18 @@ export class TypebotController {
public async findTypebot(instance: InstanceDto) { public async findTypebot(instance: InstanceDto) {
if (!configService.get<Typebot>('TYPEBOT').ENABLED) throw new BadRequestException('Typebot is disabled'); if (!configService.get<Typebot>('TYPEBOT').ENABLED) throw new BadRequestException('Typebot is disabled');
logger.verbose('requested findTypebot from ' + instance.instanceName + ' instance');
return this.typebotService.find(instance); return this.typebotService.find(instance);
} }
public async changeStatus(instance: InstanceDto, data: any) { public async changeStatus(instance: InstanceDto, data: any) {
if (!configService.get<Typebot>('TYPEBOT').ENABLED) throw new BadRequestException('Typebot is disabled'); if (!configService.get<Typebot>('TYPEBOT').ENABLED) throw new BadRequestException('Typebot is disabled');
logger.verbose('requested changeStatus from ' + instance.instanceName + ' instance');
return this.typebotService.changeStatus(instance, data); return this.typebotService.changeStatus(instance, data);
} }
public async startTypebot(instance: InstanceDto, data: any) { public async startTypebot(instance: InstanceDto, data: any) {
if (!configService.get<Typebot>('TYPEBOT').ENABLED) throw new BadRequestException('Typebot is disabled'); if (!configService.get<Typebot>('TYPEBOT').ENABLED) throw new BadRequestException('Typebot is disabled');
logger.verbose('requested startTypebot from ' + instance.instanceName + ' instance');
return this.typebotService.startTypebot(instance, data); return this.typebotService.startTypebot(instance, data);
} }
} }

View File

@ -1,6 +1,5 @@
import { RequestHandler, Router } from 'express'; import { RequestHandler, Router } from 'express';
import { Logger } from '../../../../config/logger.config';
import { import {
instanceNameSchema, instanceNameSchema,
typebotSchema, typebotSchema,
@ -13,19 +12,11 @@ import { HttpStatus } from '../../../routes/index.router';
import { typebotController } from '../../../server.module'; import { typebotController } from '../../../server.module';
import { TypebotDto } from '../dto/typebot.dto'; import { TypebotDto } from '../dto/typebot.dto';
const logger = new Logger('TypebotRouter');
export class TypebotRouter extends RouterBroker { export class TypebotRouter extends RouterBroker {
constructor(...guards: RequestHandler[]) { constructor(...guards: RequestHandler[]) {
super(); super();
this.router this.router
.post(this.routerPath('set'), ...guards, async (req, res) => { .post(this.routerPath('set'), ...guards, async (req, res) => {
logger.verbose('request received in setTypebot');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<TypebotDto>({ const response = await this.dataValidate<TypebotDto>({
request: req, request: req,
schema: typebotSchema, schema: typebotSchema,
@ -36,12 +27,6 @@ export class TypebotRouter extends RouterBroker {
res.status(HttpStatus.CREATED).json(response); res.status(HttpStatus.CREATED).json(response);
}) })
.get(this.routerPath('find'), ...guards, async (req, res) => { .get(this.routerPath('find'), ...guards, async (req, res) => {
logger.verbose('request received in findTypebot');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<InstanceDto>({ const response = await this.dataValidate<InstanceDto>({
request: req, request: req,
schema: instanceNameSchema, schema: instanceNameSchema,
@ -52,12 +37,6 @@ export class TypebotRouter extends RouterBroker {
res.status(HttpStatus.OK).json(response); res.status(HttpStatus.OK).json(response);
}) })
.post(this.routerPath('changeStatus'), ...guards, async (req, res) => { .post(this.routerPath('changeStatus'), ...guards, async (req, res) => {
logger.verbose('request received in changeStatusTypebot');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<InstanceDto>({ const response = await this.dataValidate<InstanceDto>({
request: req, request: req,
schema: typebotStatusSchema, schema: typebotStatusSchema,
@ -68,12 +47,6 @@ export class TypebotRouter extends RouterBroker {
res.status(HttpStatus.OK).json(response); res.status(HttpStatus.OK).json(response);
}) })
.post(this.routerPath('start'), ...guards, async (req, res) => { .post(this.routerPath('start'), ...guards, async (req, res) => {
logger.verbose('request received in startTypebot');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<InstanceDto>({ const response = await this.dataValidate<InstanceDto>({
request: req, request: req,
schema: typebotStartSchema, schema: typebotStartSchema,

View File

@ -26,7 +26,6 @@ export class TypebotService {
private readonly logger = new Logger(TypebotService.name); private readonly logger = new Logger(TypebotService.name);
public create(instance: InstanceDto, data: TypebotDto) { public create(instance: InstanceDto, data: TypebotDto) {
this.logger.verbose('create typebot: ' + instance.instanceName);
this.waMonitor.waInstances[instance.instanceName].setTypebot(data); this.waMonitor.waInstances[instance.instanceName].setTypebot(data);
return { typebot: { ...instance, typebot: data } }; return { typebot: { ...instance, typebot: data } };
@ -34,7 +33,6 @@ export class TypebotService {
public async find(instance: InstanceDto): Promise<TypebotDto> { public async find(instance: InstanceDto): Promise<TypebotDto> {
try { try {
this.logger.verbose('find typebot: ' + instance.instanceName);
const result = await this.waMonitor.waInstances[instance.instanceName].findTypebot(); const result = await this.waMonitor.waInstances[instance.instanceName].findTypebot();
if (Object.keys(result).length === 0) { if (Object.keys(result).length === 0) {
@ -270,7 +268,6 @@ export class TypebotService {
} }
private getTypeMessage(msg: any) { private getTypeMessage(msg: any) {
this.logger.verbose('get type message');
const types = { const types = {
conversation: msg.conversation, conversation: msg.conversation,
extendedTextMessage: msg.extendedTextMessage?.text, extendedTextMessage: msg.extendedTextMessage?.text,
@ -290,128 +287,89 @@ export class TypebotService {
const messageType = Object.keys(types).find((key) => types[key] !== undefined) || 'unknown'; const messageType = Object.keys(types).find((key) => types[key] !== undefined) || 'unknown';
this.logger.verbose('Type message: ' + JSON.stringify(types));
return { ...types, messageType }; return { ...types, messageType };
} }
private getMessageContent(types: any) { private getMessageContent(types: any) {
this.logger.verbose('get message content');
const typeKey = Object.keys(types).find((key) => types[key] !== undefined); const typeKey = Object.keys(types).find((key) => types[key] !== undefined);
const result = typeKey ? types[typeKey] : undefined; const result = typeKey ? types[typeKey] : undefined;
this.logger.verbose('message content: ' + result);
return result; return result;
} }
private getConversationMessage(msg: any) { private getConversationMessage(msg: any) {
this.logger.verbose('get conversation message');
const types = this.getTypeMessage(msg); const types = this.getTypeMessage(msg);
const messageContent = this.getMessageContent(types); const messageContent = this.getMessageContent(types);
this.logger.verbose('conversation message: ' + messageContent);
return messageContent; return messageContent;
} }
private getAudioMessageContent(msg: any) { private getAudioMessageContent(msg: any) {
this.logger.verbose('get audio message content');
const types = this.getTypeMessage(msg); const types = this.getTypeMessage(msg);
const audioContent = types.audioMessage; const audioContent = types.audioMessage;
this.logger.verbose('audio message URL: ' + audioContent);
return audioContent; return audioContent;
} }
private getImageMessageContent(msg: any) { private getImageMessageContent(msg: any) {
this.logger.verbose('get image message content');
const types = this.getTypeMessage(msg); const types = this.getTypeMessage(msg);
const imageContent = types.imageMessage; const imageContent = types.imageMessage;
this.logger.verbose('image message URL: ' + imageContent);
return imageContent; return imageContent;
} }
private getVideoMessageContent(msg: any) { private getVideoMessageContent(msg: any) {
this.logger.verbose('get video message content');
const types = this.getTypeMessage(msg); const types = this.getTypeMessage(msg);
const videoContent = types.videoMessage; const videoContent = types.videoMessage;
this.logger.verbose('video message URL: ' + videoContent);
return videoContent; return videoContent;
} }
private getDocumentMessageContent(msg: any) { private getDocumentMessageContent(msg: any) {
this.logger.verbose('get document message content');
const types = this.getTypeMessage(msg); const types = this.getTypeMessage(msg);
const documentContent = types.documentMessage; const documentContent = types.documentMessage;
this.logger.verbose('document message fileName: ' + documentContent);
return documentContent; return documentContent;
} }
private getContactMessageContent(msg: any) { private getContactMessageContent(msg: any) {
this.logger.verbose('get contact message content');
const types = this.getTypeMessage(msg); const types = this.getTypeMessage(msg);
const contactContent = types.contactMessage; const contactContent = types.contactMessage;
this.logger.verbose('contact message displayName: ' + contactContent);
return contactContent; return contactContent;
} }
private getLocationMessageContent(msg: any) { private getLocationMessageContent(msg: any) {
this.logger.verbose('get location message content');
const types = this.getTypeMessage(msg); const types = this.getTypeMessage(msg);
const locationContent = types.locationMessage; const locationContent = types.locationMessage;
this.logger.verbose('location message degreesLatitude: ' + locationContent);
return locationContent; return locationContent;
} }
private getViewOnceMessageV2Content(msg: any) { private getViewOnceMessageV2Content(msg: any) {
this.logger.verbose('get viewOnceMessageV2 content');
const types = this.getTypeMessage(msg); const types = this.getTypeMessage(msg);
const viewOnceContent = types.viewOnceMessageV2; const viewOnceContent = types.viewOnceMessageV2;
this.logger.verbose('viewOnceMessageV2 URL: ' + viewOnceContent);
return viewOnceContent; return viewOnceContent;
} }
private getListResponseMessageContent(msg: any) { private getListResponseMessageContent(msg: any) {
this.logger.verbose('get listResponseMessage content');
const types = this.getTypeMessage(msg); const types = this.getTypeMessage(msg);
const listResponseContent = types.listResponseMessage || types.responseRowId; const listResponseContent = types.listResponseMessage || types.responseRowId;
this.logger.verbose('listResponseMessage selectedRowId: ' + listResponseContent);
return listResponseContent; return listResponseContent;
} }
public async createNewSession(instance: InstanceDto, data: any) { public async createNewSession(instance: InstanceDto, data: any) {
if (data.remoteJid === 'status@broadcast') return; if (data.remoteJid === 'status@broadcast') return;
const id = Math.floor(Math.random() * 10000000000).toString(); const id = Math.floor(Math.random() * 10000000000).toString();

View File

@ -1,23 +1,16 @@
import { Logger } from '../../../../config/logger.config';
import { InstanceDto } from '../../../dto/instance.dto'; import { InstanceDto } from '../../../dto/instance.dto';
import { WebsocketDto } from '../dto/websocket.dto'; import { WebsocketDto } from '../dto/websocket.dto';
import { WebsocketService } from '../services/websocket.service'; import { WebsocketService } from '../services/websocket.service';
const logger = new Logger('WebsocketController');
export class WebsocketController { export class WebsocketController {
constructor(private readonly websocketService: WebsocketService) {} constructor(private readonly websocketService: WebsocketService) {}
public async createWebsocket(instance: InstanceDto, data: WebsocketDto) { public async createWebsocket(instance: InstanceDto, data: WebsocketDto) {
logger.verbose('requested createWebsocket from ' + instance.instanceName + ' instance');
if (!data.enabled) { if (!data.enabled) {
logger.verbose('websocket disabled');
data.events = []; data.events = [];
} }
if (data.events.length === 0) { if (data.events.length === 0) {
logger.verbose('websocket events empty');
data.events = [ data.events = [
'APPLICATION_STARTUP', 'APPLICATION_STARTUP',
'QRCODE_UPDATED', 'QRCODE_UPDATED',
@ -50,7 +43,6 @@ export class WebsocketController {
} }
public async findWebsocket(instance: InstanceDto) { public async findWebsocket(instance: InstanceDto) {
logger.verbose('requested findWebsocket from ' + instance.instanceName + ' instance');
return this.websocketService.find(instance); return this.websocketService.find(instance);
} }
} }

View File

@ -33,8 +33,6 @@ export const initIO = (httpServer: Server) => {
}; };
export const getIO = (): SocketIO => { export const getIO = (): SocketIO => {
logger.verbose('Getting Socket.io');
if (!io) { if (!io) {
logger.error('Socket.io not initialized'); logger.error('Socket.io not initialized');
throw new Error('Socket.io not initialized'); throw new Error('Socket.io not initialized');

View File

@ -1,6 +1,5 @@
import { RequestHandler, Router } from 'express'; import { RequestHandler, Router } from 'express';
import { Logger } from '../../../../config/logger.config';
import { instanceNameSchema, websocketSchema } from '../../../../validate/validate.schema'; import { instanceNameSchema, websocketSchema } from '../../../../validate/validate.schema';
import { RouterBroker } from '../../../abstract/abstract.router'; import { RouterBroker } from '../../../abstract/abstract.router';
import { InstanceDto } from '../../../dto/instance.dto'; import { InstanceDto } from '../../../dto/instance.dto';
@ -8,19 +7,11 @@ import { HttpStatus } from '../../../routes/index.router';
import { websocketController } from '../../../server.module'; import { websocketController } from '../../../server.module';
import { WebsocketDto } from '../dto/websocket.dto'; import { WebsocketDto } from '../dto/websocket.dto';
const logger = new Logger('WebsocketRouter');
export class WebsocketRouter extends RouterBroker { export class WebsocketRouter extends RouterBroker {
constructor(...guards: RequestHandler[]) { constructor(...guards: RequestHandler[]) {
super(); super();
this.router this.router
.post(this.routerPath('set'), ...guards, async (req, res) => { .post(this.routerPath('set'), ...guards, async (req, res) => {
logger.verbose('request received in setWebsocket');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<WebsocketDto>({ const response = await this.dataValidate<WebsocketDto>({
request: req, request: req,
schema: websocketSchema, schema: websocketSchema,
@ -31,12 +22,6 @@ export class WebsocketRouter extends RouterBroker {
res.status(HttpStatus.CREATED).json(response); res.status(HttpStatus.CREATED).json(response);
}) })
.get(this.routerPath('find'), ...guards, async (req, res) => { .get(this.routerPath('find'), ...guards, async (req, res) => {
logger.verbose('request received in findWebsocket');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<InstanceDto>({ const response = await this.dataValidate<InstanceDto>({
request: req, request: req,
schema: instanceNameSchema, schema: instanceNameSchema,

View File

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

View File

@ -1,7 +1,6 @@
import { Contact, Message, MessageUpdate } from '@prisma/client'; import { Contact, Message, MessageUpdate } from '@prisma/client';
import { RequestHandler, Router } from 'express'; import { RequestHandler, Router } from 'express';
import { Logger } from '../../config/logger.config';
import { import {
archiveChatSchema, archiveChatSchema,
blockUserSchema, blockUserSchema,
@ -42,20 +41,11 @@ import { Query } from '../repository/repository.service';
import { chatController } from '../server.module'; import { chatController } from '../server.module';
import { HttpStatus } from './index.router'; import { HttpStatus } from './index.router';
const logger = new Logger('ChatRouter');
export class ChatRouter extends RouterBroker { export class ChatRouter extends RouterBroker {
constructor(...guards: RequestHandler[]) { constructor(...guards: RequestHandler[]) {
super(); super();
this.router this.router
.post(this.routerPath('whatsappNumbers'), ...guards, async (req, res) => { .post(this.routerPath('whatsappNumbers'), ...guards, async (req, res) => {
logger.verbose('request received in whatsappNumbers');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<WhatsAppNumberDto>({ const response = await this.dataValidate<WhatsAppNumberDto>({
request: req, request: req,
schema: whatsappNumberSchema, schema: whatsappNumberSchema,
@ -66,13 +56,6 @@ export class ChatRouter extends RouterBroker {
return res.status(HttpStatus.OK).json(response); return res.status(HttpStatus.OK).json(response);
}) })
.put(this.routerPath('markMessageAsRead'), ...guards, async (req, res) => { .put(this.routerPath('markMessageAsRead'), ...guards, async (req, res) => {
logger.verbose('request received in markMessageAsRead');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<ReadMessageDto>({ const response = await this.dataValidate<ReadMessageDto>({
request: req, request: req,
schema: readMessageSchema, schema: readMessageSchema,
@ -83,13 +66,6 @@ export class ChatRouter extends RouterBroker {
return res.status(HttpStatus.CREATED).json(response); return res.status(HttpStatus.CREATED).json(response);
}) })
.put(this.routerPath('archiveChat'), ...guards, async (req, res) => { .put(this.routerPath('archiveChat'), ...guards, async (req, res) => {
logger.verbose('request received in archiveChat');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<ArchiveChatDto>({ const response = await this.dataValidate<ArchiveChatDto>({
request: req, request: req,
schema: archiveChatSchema, schema: archiveChatSchema,
@ -100,13 +76,6 @@ export class ChatRouter extends RouterBroker {
return res.status(HttpStatus.CREATED).json(response); return res.status(HttpStatus.CREATED).json(response);
}) })
.put(this.routerPath('markChatUnread'), ...guards, async (req, res) => { .put(this.routerPath('markChatUnread'), ...guards, async (req, res) => {
logger.verbose('request received in markChatUnread');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<MarkChatUnreadDto>({ const response = await this.dataValidate<MarkChatUnreadDto>({
request: req, request: req,
schema: markChatUnreadSchema, schema: markChatUnreadSchema,
@ -117,13 +86,6 @@ export class ChatRouter extends RouterBroker {
return res.status(HttpStatus.CREATED).json(response); return res.status(HttpStatus.CREATED).json(response);
}) })
.delete(this.routerPath('deleteMessageForEveryone'), ...guards, async (req, res) => { .delete(this.routerPath('deleteMessageForEveryone'), ...guards, async (req, res) => {
logger.verbose('request received in deleteMessageForEveryone');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<DeleteMessage>({ const response = await this.dataValidate<DeleteMessage>({
request: req, request: req,
schema: deleteMessageSchema, schema: deleteMessageSchema,
@ -134,13 +96,6 @@ export class ChatRouter extends RouterBroker {
return res.status(HttpStatus.CREATED).json(response); return res.status(HttpStatus.CREATED).json(response);
}) })
.post(this.routerPath('fetchProfilePictureUrl'), ...guards, async (req, res) => { .post(this.routerPath('fetchProfilePictureUrl'), ...guards, async (req, res) => {
logger.verbose('request received in fetchProfilePictureUrl');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<NumberDto>({ const response = await this.dataValidate<NumberDto>({
request: req, request: req,
schema: profilePictureSchema, schema: profilePictureSchema,
@ -151,13 +106,6 @@ export class ChatRouter extends RouterBroker {
return res.status(HttpStatus.OK).json(response); return res.status(HttpStatus.OK).json(response);
}) })
.post(this.routerPath('fetchProfile'), ...guards, async (req, res) => { .post(this.routerPath('fetchProfile'), ...guards, async (req, res) => {
logger.verbose('request received in fetchProfile');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<NumberDto>({ const response = await this.dataValidate<NumberDto>({
request: req, request: req,
schema: profileSchema, schema: profileSchema,
@ -168,13 +116,6 @@ export class ChatRouter extends RouterBroker {
return res.status(HttpStatus.OK).json(response); return res.status(HttpStatus.OK).json(response);
}) })
.post(this.routerPath('findContacts'), ...guards, async (req, res) => { .post(this.routerPath('findContacts'), ...guards, async (req, res) => {
logger.verbose('request received in findContacts');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<Query<Contact>>({ const response = await this.dataValidate<Query<Contact>>({
request: req, request: req,
schema: contactValidateSchema, schema: contactValidateSchema,
@ -185,13 +126,6 @@ export class ChatRouter extends RouterBroker {
return res.status(HttpStatus.OK).json(response); return res.status(HttpStatus.OK).json(response);
}) })
.post(this.routerPath('getBase64FromMediaMessage'), ...guards, async (req, res) => { .post(this.routerPath('getBase64FromMediaMessage'), ...guards, async (req, res) => {
logger.verbose('request received in getBase64FromMediaMessage');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<getBase64FromMediaMessageDto>({ const response = await this.dataValidate<getBase64FromMediaMessageDto>({
request: req, request: req,
schema: null, schema: null,
@ -202,13 +136,6 @@ export class ChatRouter extends RouterBroker {
return res.status(HttpStatus.CREATED).json(response); return res.status(HttpStatus.CREATED).json(response);
}) })
.post(this.routerPath('findMessages'), ...guards, async (req, res) => { .post(this.routerPath('findMessages'), ...guards, async (req, res) => {
logger.verbose('request received in findMessages');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<Query<Message>>({ const response = await this.dataValidate<Query<Message>>({
request: req, request: req,
schema: messageValidateSchema, schema: messageValidateSchema,
@ -219,13 +146,6 @@ export class ChatRouter extends RouterBroker {
return res.status(HttpStatus.OK).json(response); return res.status(HttpStatus.OK).json(response);
}) })
.post(this.routerPath('findStatusMessage'), ...guards, async (req, res) => { .post(this.routerPath('findStatusMessage'), ...guards, async (req, res) => {
logger.verbose('request received in findStatusMessage');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<Query<MessageUpdate>>({ const response = await this.dataValidate<Query<MessageUpdate>>({
request: req, request: req,
schema: messageUpSchema, schema: messageUpSchema,
@ -236,13 +156,6 @@ export class ChatRouter extends RouterBroker {
return res.status(HttpStatus.OK).json(response); return res.status(HttpStatus.OK).json(response);
}) })
.get(this.routerPath('findChats'), ...guards, async (req, res) => { .get(this.routerPath('findChats'), ...guards, async (req, res) => {
logger.verbose('request received in findChats');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<InstanceDto>({ const response = await this.dataValidate<InstanceDto>({
request: req, request: req,
schema: null, schema: null,
@ -253,12 +166,6 @@ export class ChatRouter extends RouterBroker {
return res.status(HttpStatus.OK).json(response); return res.status(HttpStatus.OK).json(response);
}) })
.post(this.routerPath('sendPresence'), ...guards, async (req, res) => { .post(this.routerPath('sendPresence'), ...guards, async (req, res) => {
logger.verbose('request received in sendPresence');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<null>({ const response = await this.dataValidate<null>({
request: req, request: req,
schema: presenceSchema, schema: presenceSchema,
@ -270,13 +177,6 @@ export class ChatRouter extends RouterBroker {
}) })
// Profile routes // Profile routes
.get(this.routerPath('fetchPrivacySettings'), ...guards, async (req, res) => { .get(this.routerPath('fetchPrivacySettings'), ...guards, async (req, res) => {
logger.verbose('request received in fetchPrivacySettings');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<InstanceDto>({ const response = await this.dataValidate<InstanceDto>({
request: req, request: req,
schema: null, schema: null,
@ -287,13 +187,6 @@ export class ChatRouter extends RouterBroker {
return res.status(HttpStatus.OK).json(response); return res.status(HttpStatus.OK).json(response);
}) })
.put(this.routerPath('updatePrivacySettings'), ...guards, async (req, res) => { .put(this.routerPath('updatePrivacySettings'), ...guards, async (req, res) => {
logger.verbose('request received in updatePrivacySettings');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<PrivacySettingDto>({ const response = await this.dataValidate<PrivacySettingDto>({
request: req, request: req,
schema: privacySettingsSchema, schema: privacySettingsSchema,
@ -304,13 +197,6 @@ export class ChatRouter extends RouterBroker {
return res.status(HttpStatus.CREATED).json(response); return res.status(HttpStatus.CREATED).json(response);
}) })
.post(this.routerPath('fetchBusinessProfile'), ...guards, async (req, res) => { .post(this.routerPath('fetchBusinessProfile'), ...guards, async (req, res) => {
logger.verbose('request received in fetchBusinessProfile');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<ProfilePictureDto>({ const response = await this.dataValidate<ProfilePictureDto>({
request: req, request: req,
schema: profilePictureSchema, schema: profilePictureSchema,
@ -321,13 +207,6 @@ export class ChatRouter extends RouterBroker {
return res.status(HttpStatus.OK).json(response); return res.status(HttpStatus.OK).json(response);
}) })
.post(this.routerPath('updateProfileName'), ...guards, async (req, res) => { .post(this.routerPath('updateProfileName'), ...guards, async (req, res) => {
logger.verbose('request received in updateProfileName');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<ProfileNameDto>({ const response = await this.dataValidate<ProfileNameDto>({
request: req, request: req,
schema: profileNameSchema, schema: profileNameSchema,
@ -338,13 +217,6 @@ export class ChatRouter extends RouterBroker {
return res.status(HttpStatus.OK).json(response); return res.status(HttpStatus.OK).json(response);
}) })
.post(this.routerPath('updateProfileStatus'), ...guards, async (req, res) => { .post(this.routerPath('updateProfileStatus'), ...guards, async (req, res) => {
logger.verbose('request received in updateProfileStatus');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<ProfileStatusDto>({ const response = await this.dataValidate<ProfileStatusDto>({
request: req, request: req,
schema: profileStatusSchema, schema: profileStatusSchema,
@ -355,13 +227,6 @@ export class ChatRouter extends RouterBroker {
return res.status(HttpStatus.OK).json(response); return res.status(HttpStatus.OK).json(response);
}) })
.put(this.routerPath('updateProfilePicture'), ...guards, async (req, res) => { .put(this.routerPath('updateProfilePicture'), ...guards, async (req, res) => {
logger.verbose('request received in updateProfilePicture');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<ProfilePictureDto>({ const response = await this.dataValidate<ProfilePictureDto>({
request: req, request: req,
schema: profilePictureSchema, schema: profilePictureSchema,
@ -372,13 +237,6 @@ export class ChatRouter extends RouterBroker {
return res.status(HttpStatus.OK).json(response); return res.status(HttpStatus.OK).json(response);
}) })
.delete(this.routerPath('removeProfilePicture'), ...guards, async (req, res) => { .delete(this.routerPath('removeProfilePicture'), ...guards, async (req, res) => {
logger.verbose('request received in removeProfilePicture');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<ProfilePictureDto>({ const response = await this.dataValidate<ProfilePictureDto>({
request: req, request: req,
schema: profilePictureSchema, schema: profilePictureSchema,
@ -389,13 +247,6 @@ export class ChatRouter extends RouterBroker {
return res.status(HttpStatus.OK).json(response); return res.status(HttpStatus.OK).json(response);
}) })
.put(this.routerPath('updateMessage'), ...guards, async (req, res) => { .put(this.routerPath('updateMessage'), ...guards, async (req, res) => {
logger.verbose('request received in updateMessage');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<UpdateMessageDto>({ const response = await this.dataValidate<UpdateMessageDto>({
request: req, request: req,
schema: updateMessageSchema, schema: updateMessageSchema,
@ -406,13 +257,6 @@ export class ChatRouter extends RouterBroker {
return res.status(HttpStatus.OK).json(response); return res.status(HttpStatus.OK).json(response);
}) })
.put(this.routerPath('updateBlockStatus'), ...guards, async (req, res) => { .put(this.routerPath('updateBlockStatus'), ...guards, async (req, res) => {
logger.verbose('request received in updateBlockStatus');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<BlockUserDto>({ const response = await this.dataValidate<BlockUserDto>({
request: req, request: req,
schema: blockUserSchema, schema: blockUserSchema,

View File

@ -1,6 +1,5 @@
import { RequestHandler, Router } from 'express'; import { RequestHandler, Router } from 'express';
import { Logger } from '../../config/logger.config';
import { import {
AcceptGroupInviteSchema, AcceptGroupInviteSchema,
createGroupSchema, createGroupSchema,
@ -33,19 +32,11 @@ import {
import { groupController } from '../server.module'; import { groupController } from '../server.module';
import { HttpStatus } from './index.router'; import { HttpStatus } from './index.router';
const logger = new Logger('GroupRouter');
export class GroupRouter extends RouterBroker { export class GroupRouter extends RouterBroker {
constructor(...guards: RequestHandler[]) { constructor(...guards: RequestHandler[]) {
super(); super();
this.router this.router
.post(this.routerPath('create'), ...guards, async (req, res) => { .post(this.routerPath('create'), ...guards, async (req, res) => {
logger.verbose('request received in createGroup');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<CreateGroupDto>({ const response = await this.dataValidate<CreateGroupDto>({
request: req, request: req,
schema: createGroupSchema, schema: createGroupSchema,
@ -56,13 +47,6 @@ export class GroupRouter extends RouterBroker {
res.status(HttpStatus.CREATED).json(response); res.status(HttpStatus.CREATED).json(response);
}) })
.put(this.routerPath('updateGroupSubject'), ...guards, async (req, res) => { .put(this.routerPath('updateGroupSubject'), ...guards, async (req, res) => {
logger.verbose('request received in updateGroupSubject');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.groupValidate<GroupSubjectDto>({ const response = await this.groupValidate<GroupSubjectDto>({
request: req, request: req,
schema: updateGroupSubjectSchema, schema: updateGroupSubjectSchema,
@ -73,12 +57,6 @@ export class GroupRouter extends RouterBroker {
res.status(HttpStatus.CREATED).json(response); res.status(HttpStatus.CREATED).json(response);
}) })
.put(this.routerPath('updateGroupPicture'), ...guards, async (req, res) => { .put(this.routerPath('updateGroupPicture'), ...guards, async (req, res) => {
logger.verbose('request received in updateGroupPicture');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.groupValidate<GroupPictureDto>({ const response = await this.groupValidate<GroupPictureDto>({
request: req, request: req,
schema: updateGroupPictureSchema, schema: updateGroupPictureSchema,
@ -89,12 +67,6 @@ export class GroupRouter extends RouterBroker {
res.status(HttpStatus.CREATED).json(response); res.status(HttpStatus.CREATED).json(response);
}) })
.put(this.routerPath('updateGroupDescription'), ...guards, async (req, res) => { .put(this.routerPath('updateGroupDescription'), ...guards, async (req, res) => {
logger.verbose('request received in updateGroupDescription');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.groupValidate<GroupDescriptionDto>({ const response = await this.groupValidate<GroupDescriptionDto>({
request: req, request: req,
schema: updateGroupDescriptionSchema, schema: updateGroupDescriptionSchema,
@ -105,12 +77,6 @@ export class GroupRouter extends RouterBroker {
res.status(HttpStatus.CREATED).json(response); res.status(HttpStatus.CREATED).json(response);
}) })
.get(this.routerPath('findGroupInfos'), ...guards, async (req, res) => { .get(this.routerPath('findGroupInfos'), ...guards, async (req, res) => {
logger.verbose('request received in findGroupInfos');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.groupValidate<GroupJid>({ const response = await this.groupValidate<GroupJid>({
request: req, request: req,
schema: groupJidSchema, schema: groupJidSchema,
@ -121,12 +87,6 @@ export class GroupRouter extends RouterBroker {
res.status(HttpStatus.OK).json(response); res.status(HttpStatus.OK).json(response);
}) })
.get(this.routerPath('fetchAllGroups'), ...guards, async (req, res) => { .get(this.routerPath('fetchAllGroups'), ...guards, async (req, res) => {
logger.verbose('request received in fetchAllGroups');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.getParticipantsValidate<GetParticipant>({ const response = await this.getParticipantsValidate<GetParticipant>({
request: req, request: req,
schema: getParticipantsSchema, schema: getParticipantsSchema,
@ -137,12 +97,6 @@ export class GroupRouter extends RouterBroker {
res.status(HttpStatus.OK).json(response); res.status(HttpStatus.OK).json(response);
}) })
.get(this.routerPath('participants'), ...guards, async (req, res) => { .get(this.routerPath('participants'), ...guards, async (req, res) => {
logger.verbose('request received in participants');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.groupValidate<GroupJid>({ const response = await this.groupValidate<GroupJid>({
request: req, request: req,
schema: groupJidSchema, schema: groupJidSchema,
@ -153,12 +107,6 @@ export class GroupRouter extends RouterBroker {
res.status(HttpStatus.OK).json(response); res.status(HttpStatus.OK).json(response);
}) })
.get(this.routerPath('inviteCode'), ...guards, async (req, res) => { .get(this.routerPath('inviteCode'), ...guards, async (req, res) => {
logger.verbose('request received in inviteCode');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.groupValidate<GroupJid>({ const response = await this.groupValidate<GroupJid>({
request: req, request: req,
schema: groupJidSchema, schema: groupJidSchema,
@ -169,12 +117,6 @@ export class GroupRouter extends RouterBroker {
res.status(HttpStatus.OK).json(response); res.status(HttpStatus.OK).json(response);
}) })
.get(this.routerPath('inviteInfo'), ...guards, async (req, res) => { .get(this.routerPath('inviteInfo'), ...guards, async (req, res) => {
logger.verbose('request received in inviteInfo');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.inviteCodeValidate<GroupInvite>({ const response = await this.inviteCodeValidate<GroupInvite>({
request: req, request: req,
schema: groupInviteSchema, schema: groupInviteSchema,
@ -185,12 +127,6 @@ export class GroupRouter extends RouterBroker {
res.status(HttpStatus.OK).json(response); res.status(HttpStatus.OK).json(response);
}) })
.get(this.routerPath('acceptInviteCode'), ...guards, async (req, res) => { .get(this.routerPath('acceptInviteCode'), ...guards, async (req, res) => {
logger.verbose('request received in acceptInviteCode');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.inviteCodeValidate<AcceptGroupInvite>({ const response = await this.inviteCodeValidate<AcceptGroupInvite>({
request: req, request: req,
schema: AcceptGroupInviteSchema, schema: AcceptGroupInviteSchema,
@ -201,12 +137,6 @@ export class GroupRouter extends RouterBroker {
res.status(HttpStatus.OK).json(response); res.status(HttpStatus.OK).json(response);
}) })
.post(this.routerPath('sendInvite'), ...guards, async (req, res) => { .post(this.routerPath('sendInvite'), ...guards, async (req, res) => {
logger.verbose('request received in sendInvite');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.groupNoValidate<GroupSendInvite>({ const response = await this.groupNoValidate<GroupSendInvite>({
request: req, request: req,
schema: groupSendInviteSchema, schema: groupSendInviteSchema,
@ -217,12 +147,6 @@ export class GroupRouter extends RouterBroker {
res.status(HttpStatus.OK).json(response); res.status(HttpStatus.OK).json(response);
}) })
.put(this.routerPath('revokeInviteCode'), ...guards, async (req, res) => { .put(this.routerPath('revokeInviteCode'), ...guards, async (req, res) => {
logger.verbose('request received in revokeInviteCode');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.groupValidate<GroupJid>({ const response = await this.groupValidate<GroupJid>({
request: req, request: req,
schema: groupJidSchema, schema: groupJidSchema,
@ -233,12 +157,6 @@ export class GroupRouter extends RouterBroker {
res.status(HttpStatus.CREATED).json(response); res.status(HttpStatus.CREATED).json(response);
}) })
.put(this.routerPath('updateParticipant'), ...guards, async (req, res) => { .put(this.routerPath('updateParticipant'), ...guards, async (req, res) => {
logger.verbose('request received in updateParticipant');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.groupValidate<GroupUpdateParticipantDto>({ const response = await this.groupValidate<GroupUpdateParticipantDto>({
request: req, request: req,
schema: updateParticipantsSchema, schema: updateParticipantsSchema,
@ -249,12 +167,6 @@ export class GroupRouter extends RouterBroker {
res.status(HttpStatus.CREATED).json(response); res.status(HttpStatus.CREATED).json(response);
}) })
.put(this.routerPath('updateSetting'), ...guards, async (req, res) => { .put(this.routerPath('updateSetting'), ...guards, async (req, res) => {
logger.verbose('request received in updateSetting');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.groupValidate<GroupUpdateSettingDto>({ const response = await this.groupValidate<GroupUpdateSettingDto>({
request: req, request: req,
schema: updateSettingsSchema, schema: updateSettingsSchema,
@ -265,12 +177,6 @@ export class GroupRouter extends RouterBroker {
res.status(HttpStatus.CREATED).json(response); res.status(HttpStatus.CREATED).json(response);
}) })
.put(this.routerPath('toggleEphemeral'), ...guards, async (req, res) => { .put(this.routerPath('toggleEphemeral'), ...guards, async (req, res) => {
logger.verbose('request received in toggleEphemeral');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.groupValidate<GroupToggleEphemeralDto>({ const response = await this.groupValidate<GroupToggleEphemeralDto>({
request: req, request: req,
schema: toggleEphemeralSchema, schema: toggleEphemeralSchema,
@ -281,12 +187,6 @@ export class GroupRouter extends RouterBroker {
res.status(HttpStatus.CREATED).json(response); res.status(HttpStatus.CREATED).json(response);
}) })
.delete(this.routerPath('leaveGroup'), ...guards, async (req, res) => { .delete(this.routerPath('leaveGroup'), ...guards, async (req, res) => {
logger.verbose('request received in leaveGroup');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.groupValidate<GroupJid>({ const response = await this.groupValidate<GroupJid>({
request: req, request: req,
schema: {}, schema: {},

View File

@ -1,27 +1,17 @@
import { RequestHandler, Router } from 'express'; import { RequestHandler, Router } from 'express';
import { ConfigService } from '../../config/env.config'; import { ConfigService } from '../../config/env.config';
import { Logger } from '../../config/logger.config';
import { instanceNameSchema, presenceOnlySchema } from '../../validate/validate.schema'; import { instanceNameSchema, presenceOnlySchema } from '../../validate/validate.schema';
import { RouterBroker } from '../abstract/abstract.router'; import { RouterBroker } from '../abstract/abstract.router';
import { InstanceDto, SetPresenceDto } from '../dto/instance.dto'; import { InstanceDto, SetPresenceDto } from '../dto/instance.dto';
import { instanceController } from '../server.module'; import { instanceController } from '../server.module';
import { HttpStatus } from './index.router'; import { HttpStatus } from './index.router';
const logger = new Logger('InstanceRouter');
export class InstanceRouter extends RouterBroker { export class InstanceRouter extends RouterBroker {
constructor(readonly configService: ConfigService, ...guards: RequestHandler[]) { constructor(readonly configService: ConfigService, ...guards: RequestHandler[]) {
super(); super();
this.router this.router
.post('/create', ...guards, async (req, res) => { .post('/create', ...guards, async (req, res) => {
logger.verbose('request received in createInstance');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<InstanceDto>({ const response = await this.dataValidate<InstanceDto>({
request: req, request: req,
schema: instanceNameSchema, schema: instanceNameSchema,
@ -32,12 +22,6 @@ export class InstanceRouter extends RouterBroker {
return res.status(HttpStatus.CREATED).json(response); return res.status(HttpStatus.CREATED).json(response);
}) })
.put(this.routerPath('restart'), ...guards, async (req, res) => { .put(this.routerPath('restart'), ...guards, async (req, res) => {
logger.verbose('request received in restartInstance');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<InstanceDto>({ const response = await this.dataValidate<InstanceDto>({
request: req, request: req,
schema: instanceNameSchema, schema: instanceNameSchema,
@ -48,12 +32,6 @@ export class InstanceRouter extends RouterBroker {
return res.status(HttpStatus.OK).json(response); return res.status(HttpStatus.OK).json(response);
}) })
.get(this.routerPath('connect'), ...guards, async (req, res) => { .get(this.routerPath('connect'), ...guards, async (req, res) => {
logger.verbose('request received in connectInstance');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<InstanceDto>({ const response = await this.dataValidate<InstanceDto>({
request: req, request: req,
schema: instanceNameSchema, schema: instanceNameSchema,
@ -64,12 +42,6 @@ export class InstanceRouter extends RouterBroker {
return res.status(HttpStatus.OK).json(response); return res.status(HttpStatus.OK).json(response);
}) })
.get(this.routerPath('connectionState'), ...guards, async (req, res) => { .get(this.routerPath('connectionState'), ...guards, async (req, res) => {
logger.verbose('request received in connectionState');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<InstanceDto>({ const response = await this.dataValidate<InstanceDto>({
request: req, request: req,
schema: instanceNameSchema, schema: instanceNameSchema,
@ -80,14 +52,8 @@ export class InstanceRouter extends RouterBroker {
return res.status(HttpStatus.OK).json(response); return res.status(HttpStatus.OK).json(response);
}) })
.get(this.routerPath('fetchInstances', false), ...guards, async (req, res) => { .get(this.routerPath('fetchInstances', false), ...guards, async (req, res) => {
logger.verbose('request received in fetchInstances');
logger.verbose('request body: ');
logger.verbose(req.body);
const key = req.get('apikey'); const key = req.get('apikey');
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<InstanceDto>({ const response = await this.dataValidate<InstanceDto>({
request: req, request: req,
schema: null, schema: null,
@ -98,12 +64,6 @@ export class InstanceRouter extends RouterBroker {
return res.status(HttpStatus.OK).json(response); return res.status(HttpStatus.OK).json(response);
}) })
.post(this.routerPath('setPresence'), ...guards, async (req, res) => { .post(this.routerPath('setPresence'), ...guards, async (req, res) => {
logger.verbose('request received in setPresence');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<null>({ const response = await this.dataValidate<null>({
request: req, request: req,
schema: presenceOnlySchema, schema: presenceOnlySchema,
@ -114,12 +74,6 @@ export class InstanceRouter extends RouterBroker {
return res.status(HttpStatus.CREATED).json(response); return res.status(HttpStatus.CREATED).json(response);
}) })
.delete(this.routerPath('logout'), ...guards, async (req, res) => { .delete(this.routerPath('logout'), ...guards, async (req, res) => {
logger.verbose('request received in logoutInstances');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<InstanceDto>({ const response = await this.dataValidate<InstanceDto>({
request: req, request: req,
schema: instanceNameSchema, schema: instanceNameSchema,
@ -130,12 +84,6 @@ export class InstanceRouter extends RouterBroker {
return res.status(HttpStatus.OK).json(response); return res.status(HttpStatus.OK).json(response);
}) })
.delete(this.routerPath('delete'), ...guards, async (req, res) => { .delete(this.routerPath('delete'), ...guards, async (req, res) => {
logger.verbose('request received in deleteInstances');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<InstanceDto>({ const response = await this.dataValidate<InstanceDto>({
request: req, request: req,
schema: instanceNameSchema, schema: instanceNameSchema,

View File

@ -1,26 +1,16 @@
import { RequestHandler, Router } from 'express'; import { RequestHandler, Router } from 'express';
import { Logger } from '../../config/logger.config';
import { handleLabelSchema } from '../../validate/validate.schema'; import { handleLabelSchema } from '../../validate/validate.schema';
import { RouterBroker } from '../abstract/abstract.router'; import { RouterBroker } from '../abstract/abstract.router';
import { HandleLabelDto, LabelDto } from '../dto/label.dto'; import { HandleLabelDto, LabelDto } from '../dto/label.dto';
import { labelController } from '../server.module'; import { labelController } from '../server.module';
import { HttpStatus } from './index.router'; import { HttpStatus } from './index.router';
const logger = new Logger('LabelRouter');
export class LabelRouter extends RouterBroker { export class LabelRouter extends RouterBroker {
constructor(...guards: RequestHandler[]) { constructor(...guards: RequestHandler[]) {
super(); super();
this.router this.router
.get(this.routerPath('findLabels'), ...guards, async (req, res) => { .get(this.routerPath('findLabels'), ...guards, async (req, res) => {
logger.verbose('request received in findLabels');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<LabelDto>({ const response = await this.dataValidate<LabelDto>({
request: req, request: req,
schema: null, schema: null,
@ -31,13 +21,6 @@ export class LabelRouter extends RouterBroker {
return res.status(HttpStatus.OK).json(response); return res.status(HttpStatus.OK).json(response);
}) })
.put(this.routerPath('handleLabel'), ...guards, async (req, res) => { .put(this.routerPath('handleLabel'), ...guards, async (req, res) => {
logger.verbose('request received in handleLabel');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<HandleLabelDto>({ const response = await this.dataValidate<HandleLabelDto>({
request: req, request: req,
schema: handleLabelSchema, schema: handleLabelSchema,

View File

@ -1,6 +1,5 @@
import { RequestHandler, Router } from 'express'; import { RequestHandler, Router } from 'express';
import { Logger } from '../../config/logger.config';
import { instanceNameSchema, proxySchema } from '../../validate/validate.schema'; import { instanceNameSchema, proxySchema } from '../../validate/validate.schema';
import { RouterBroker } from '../abstract/abstract.router'; import { RouterBroker } from '../abstract/abstract.router';
import { InstanceDto } from '../dto/instance.dto'; import { InstanceDto } from '../dto/instance.dto';
@ -8,19 +7,11 @@ import { ProxyDto } from '../dto/proxy.dto';
import { proxyController } from '../server.module'; import { proxyController } from '../server.module';
import { HttpStatus } from './index.router'; import { HttpStatus } from './index.router';
const logger = new Logger('ProxyRouter');
export class ProxyRouter extends RouterBroker { export class ProxyRouter extends RouterBroker {
constructor(...guards: RequestHandler[]) { constructor(...guards: RequestHandler[]) {
super(); super();
this.router this.router
.post(this.routerPath('set'), ...guards, async (req, res) => { .post(this.routerPath('set'), ...guards, async (req, res) => {
logger.verbose('request received in setProxy');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<ProxyDto>({ const response = await this.dataValidate<ProxyDto>({
request: req, request: req,
schema: proxySchema, schema: proxySchema,
@ -31,12 +22,6 @@ export class ProxyRouter extends RouterBroker {
res.status(HttpStatus.CREATED).json(response); res.status(HttpStatus.CREATED).json(response);
}) })
.get(this.routerPath('find'), ...guards, async (req, res) => { .get(this.routerPath('find'), ...guards, async (req, res) => {
logger.verbose('request received in findProxy');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<InstanceDto>({ const response = await this.dataValidate<InstanceDto>({
request: req, request: req,
schema: instanceNameSchema, schema: instanceNameSchema,

View File

@ -1,6 +1,5 @@
import { RequestHandler, Router } from 'express'; import { RequestHandler, Router } from 'express';
import { Logger } from '../../config/logger.config';
import { import {
audioMessageSchema, audioMessageSchema,
buttonMessageSchema, buttonMessageSchema,
@ -33,19 +32,11 @@ import {
import { sendMessageController } from '../server.module'; import { sendMessageController } from '../server.module';
import { HttpStatus } from './index.router'; import { HttpStatus } from './index.router';
const logger = new Logger('MessageRouter');
export class MessageRouter extends RouterBroker { export class MessageRouter extends RouterBroker {
constructor(...guards: RequestHandler[]) { constructor(...guards: RequestHandler[]) {
super(); super();
this.router this.router
.post(this.routerPath('sendText'), ...guards, async (req, res) => { .post(this.routerPath('sendText'), ...guards, async (req, res) => {
logger.verbose('request received in sendText');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<SendTextDto>({ const response = await this.dataValidate<SendTextDto>({
request: req, request: req,
schema: textMessageSchema, schema: textMessageSchema,
@ -56,12 +47,6 @@ export class MessageRouter extends RouterBroker {
return res.status(HttpStatus.CREATED).json(response); return res.status(HttpStatus.CREATED).json(response);
}) })
.post(this.routerPath('sendMedia'), ...guards, async (req, res) => { .post(this.routerPath('sendMedia'), ...guards, async (req, res) => {
logger.verbose('request received in sendMedia');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<SendMediaDto>({ const response = await this.dataValidate<SendMediaDto>({
request: req, request: req,
schema: mediaMessageSchema, schema: mediaMessageSchema,
@ -72,12 +57,6 @@ export class MessageRouter extends RouterBroker {
return res.status(HttpStatus.CREATED).json(response); return res.status(HttpStatus.CREATED).json(response);
}) })
.post(this.routerPath('sendWhatsAppAudio'), ...guards, async (req, res) => { .post(this.routerPath('sendWhatsAppAudio'), ...guards, async (req, res) => {
logger.verbose('request received in sendWhatsAppAudio');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<SendAudioDto>({ const response = await this.dataValidate<SendAudioDto>({
request: req, request: req,
schema: audioMessageSchema, schema: audioMessageSchema,
@ -88,12 +67,6 @@ export class MessageRouter extends RouterBroker {
return res.status(HttpStatus.CREATED).json(response); return res.status(HttpStatus.CREATED).json(response);
}) })
.post(this.routerPath('sendTemplate'), ...guards, async (req, res) => { .post(this.routerPath('sendTemplate'), ...guards, async (req, res) => {
logger.verbose('request received in sendTemplate');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<SendTemplateDto>({ const response = await this.dataValidate<SendTemplateDto>({
request: req, request: req,
schema: templateMessageSchema, schema: templateMessageSchema,
@ -104,12 +77,6 @@ export class MessageRouter extends RouterBroker {
return res.status(HttpStatus.CREATED).json(response); return res.status(HttpStatus.CREATED).json(response);
}) })
.post(this.routerPath('sendButtons'), ...guards, async (req, res) => { .post(this.routerPath('sendButtons'), ...guards, async (req, res) => {
logger.verbose('request received in sendButtons');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<SendButtonDto>({ const response = await this.dataValidate<SendButtonDto>({
request: req, request: req,
schema: buttonMessageSchema, schema: buttonMessageSchema,
@ -120,12 +87,6 @@ export class MessageRouter extends RouterBroker {
return res.status(HttpStatus.CREATED).json(response); return res.status(HttpStatus.CREATED).json(response);
}) })
.post(this.routerPath('sendLocation'), ...guards, async (req, res) => { .post(this.routerPath('sendLocation'), ...guards, async (req, res) => {
logger.verbose('request received in sendLocation');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<SendLocationDto>({ const response = await this.dataValidate<SendLocationDto>({
request: req, request: req,
schema: locationMessageSchema, schema: locationMessageSchema,
@ -136,12 +97,6 @@ export class MessageRouter extends RouterBroker {
return res.status(HttpStatus.CREATED).json(response); return res.status(HttpStatus.CREATED).json(response);
}) })
.post(this.routerPath('sendList'), ...guards, async (req, res) => { .post(this.routerPath('sendList'), ...guards, async (req, res) => {
logger.verbose('request received in sendList');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<SendListDto>({ const response = await this.dataValidate<SendListDto>({
request: req, request: req,
schema: listMessageSchema, schema: listMessageSchema,
@ -152,12 +107,6 @@ export class MessageRouter extends RouterBroker {
return res.status(HttpStatus.CREATED).json(response); return res.status(HttpStatus.CREATED).json(response);
}) })
.post(this.routerPath('sendContact'), ...guards, async (req, res) => { .post(this.routerPath('sendContact'), ...guards, async (req, res) => {
logger.verbose('request received in sendContact');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<SendContactDto>({ const response = await this.dataValidate<SendContactDto>({
request: req, request: req,
schema: contactMessageSchema, schema: contactMessageSchema,
@ -168,12 +117,6 @@ export class MessageRouter extends RouterBroker {
return res.status(HttpStatus.CREATED).json(response); return res.status(HttpStatus.CREATED).json(response);
}) })
.post(this.routerPath('sendReaction'), ...guards, async (req, res) => { .post(this.routerPath('sendReaction'), ...guards, async (req, res) => {
logger.verbose('request received in sendReaction');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<SendReactionDto>({ const response = await this.dataValidate<SendReactionDto>({
request: req, request: req,
schema: reactionMessageSchema, schema: reactionMessageSchema,
@ -184,12 +127,6 @@ export class MessageRouter extends RouterBroker {
return res.status(HttpStatus.CREATED).json(response); return res.status(HttpStatus.CREATED).json(response);
}) })
.post(this.routerPath('sendPoll'), ...guards, async (req, res) => { .post(this.routerPath('sendPoll'), ...guards, async (req, res) => {
logger.verbose('request received in sendPoll');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<SendPollDto>({ const response = await this.dataValidate<SendPollDto>({
request: req, request: req,
schema: pollMessageSchema, schema: pollMessageSchema,
@ -200,12 +137,6 @@ export class MessageRouter extends RouterBroker {
return res.status(HttpStatus.CREATED).json(response); return res.status(HttpStatus.CREATED).json(response);
}) })
.post(this.routerPath('sendStatus'), ...guards, async (req, res) => { .post(this.routerPath('sendStatus'), ...guards, async (req, res) => {
logger.verbose('request received in sendStatus');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<SendStatusDto>({ const response = await this.dataValidate<SendStatusDto>({
request: req, request: req,
schema: statusMessageSchema, schema: statusMessageSchema,
@ -216,12 +147,6 @@ export class MessageRouter extends RouterBroker {
return res.status(HttpStatus.CREATED).json(response); return res.status(HttpStatus.CREATED).json(response);
}) })
.post(this.routerPath('sendSticker'), ...guards, async (req, res) => { .post(this.routerPath('sendSticker'), ...guards, async (req, res) => {
logger.verbose('request received in sendSticker');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<SendStickerDto>({ const response = await this.dataValidate<SendStickerDto>({
request: req, request: req,
schema: stickerMessageSchema, schema: stickerMessageSchema,

View File

@ -1,6 +1,5 @@
import { RequestHandler, Router } from 'express'; import { RequestHandler, Router } from 'express';
import { Logger } from '../../config/logger.config';
import { instanceNameSchema, settingsSchema } from '../../validate/validate.schema'; import { instanceNameSchema, settingsSchema } from '../../validate/validate.schema';
import { RouterBroker } from '../abstract/abstract.router'; import { RouterBroker } from '../abstract/abstract.router';
import { InstanceDto } from '../dto/instance.dto'; import { InstanceDto } from '../dto/instance.dto';
@ -8,19 +7,11 @@ import { SettingsDto } from '../dto/settings.dto';
import { settingsController } from '../server.module'; import { settingsController } from '../server.module';
import { HttpStatus } from './index.router'; import { HttpStatus } from './index.router';
const logger = new Logger('SettingsRouter');
export class SettingsRouter extends RouterBroker { export class SettingsRouter extends RouterBroker {
constructor(...guards: RequestHandler[]) { constructor(...guards: RequestHandler[]) {
super(); super();
this.router this.router
.post(this.routerPath('set'), ...guards, async (req, res) => { .post(this.routerPath('set'), ...guards, async (req, res) => {
logger.verbose('request received in setSettings');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<SettingsDto>({ const response = await this.dataValidate<SettingsDto>({
request: req, request: req,
schema: settingsSchema, schema: settingsSchema,
@ -31,12 +22,6 @@ export class SettingsRouter extends RouterBroker {
res.status(HttpStatus.CREATED).json(response); res.status(HttpStatus.CREATED).json(response);
}) })
.get(this.routerPath('find'), ...guards, async (req, res) => { .get(this.routerPath('find'), ...guards, async (req, res) => {
logger.verbose('request received in findSettings');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<InstanceDto>({ const response = await this.dataValidate<InstanceDto>({
request: req, request: req,
schema: instanceNameSchema, schema: instanceNameSchema,

View File

@ -1,7 +1,6 @@
import { RequestHandler, Router } from 'express'; import { RequestHandler, Router } from 'express';
import { ConfigService, WaBusiness } from '../../config/env.config'; import { ConfigService, WaBusiness } from '../../config/env.config';
import { Logger } from '../../config/logger.config';
import { instanceNameSchema, webhookSchema } from '../../validate/validate.schema'; import { instanceNameSchema, webhookSchema } from '../../validate/validate.schema';
import { RouterBroker } from '../abstract/abstract.router'; import { RouterBroker } from '../abstract/abstract.router';
import { InstanceDto } from '../dto/instance.dto'; import { InstanceDto } from '../dto/instance.dto';
@ -9,19 +8,11 @@ import { WebhookDto } from '../dto/webhook.dto';
import { webhookController } from '../server.module'; import { webhookController } from '../server.module';
import { HttpStatus } from './index.router'; import { HttpStatus } from './index.router';
const logger = new Logger('WebhookRouter');
export class WebhookRouter extends RouterBroker { export class WebhookRouter extends RouterBroker {
constructor(readonly configService: ConfigService, ...guards: RequestHandler[]) { constructor(readonly configService: ConfigService, ...guards: RequestHandler[]) {
super(); super();
this.router this.router
.post(this.routerPath('set'), ...guards, async (req, res) => { .post(this.routerPath('set'), ...guards, async (req, res) => {
logger.verbose('request received in setWebhook');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<WebhookDto>({ const response = await this.dataValidate<WebhookDto>({
request: req, request: req,
schema: webhookSchema, schema: webhookSchema,
@ -32,12 +23,6 @@ export class WebhookRouter extends RouterBroker {
res.status(HttpStatus.CREATED).json(response); res.status(HttpStatus.CREATED).json(response);
}) })
.get(this.routerPath('find'), ...guards, async (req, res) => { .get(this.routerPath('find'), ...guards, async (req, res) => {
logger.verbose('request received in findWebhook');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<InstanceDto>({ const response = await this.dataValidate<InstanceDto>({
request: req, request: req,
schema: instanceNameSchema, schema: instanceNameSchema,
@ -48,12 +33,6 @@ export class WebhookRouter extends RouterBroker {
res.status(HttpStatus.OK).json(response); res.status(HttpStatus.OK).json(response);
}) })
.post(this.routerPath('whatsapp'), async (req, res) => { .post(this.routerPath('whatsapp'), async (req, res) => {
logger.verbose('request received in webhook');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<InstanceDto>({ const response = await this.dataValidate<InstanceDto>({
request: req, request: req,
schema: instanceNameSchema, schema: instanceNameSchema,
@ -64,13 +43,9 @@ export class WebhookRouter extends RouterBroker {
res.status(HttpStatus.OK).json(response); res.status(HttpStatus.OK).json(response);
}) })
.get(this.routerPath('whatsapp'), async (req, res) => { .get(this.routerPath('whatsapp'), async (req, res) => {
logger.verbose('request received in webhook');
logger.verbose('request query: ');
logger.verbose(req.query);
if (req.query['hub.verify_token'] === this.configService.get<WaBusiness>('WA_BUSINESS').TOKEN_WEBHOOK) if (req.query['hub.verify_token'] === this.configService.get<WaBusiness>('WA_BUSINESS').TOKEN_WEBHOOK)
res.send(req.query['hub.challenge']); res.send(req.query['hub.challenge']);
else res.send('Error, wrong validation token'); else res.send('Error, wrong validation token');
logger.verbose('Error, wrong validation token');
}); });
} }

View File

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

View File

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

View File

@ -48,9 +48,7 @@ export class ChannelStartupService {
public readonly eventEmitter: EventEmitter2, public readonly eventEmitter: EventEmitter2,
public readonly prismaRepository: PrismaRepository, public readonly prismaRepository: PrismaRepository,
public readonly chatwootCache: CacheService, public readonly chatwootCache: CacheService,
) { ) {}
this.logger.verbose('ChannelStartupService initialized');
}
public readonly logger = new Logger(ChannelStartupService.name); public readonly logger = new Logger(ChannelStartupService.name);
@ -79,15 +77,11 @@ export class ChannelStartupService {
public set instanceName(name: string) { public set instanceName(name: string) {
this.logger.setInstance(name); this.logger.setInstance(name);
this.logger.verbose(`Initializing instance '${name}'`);
if (!name) { if (!name) {
this.logger.verbose('Instance name not found, generating random name with uuid');
this.instance.name = v4(); this.instance.name = v4();
return; return;
} }
this.instance.name = name; 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, { this.sendDataWebhook(Events.STATUS_INSTANCE, {
instance: this.instance.name, instance: this.instance.name,
status: 'created', status: 'created',
@ -106,32 +100,26 @@ export class ChannelStartupService {
} }
public get instanceName() { public get instanceName() {
this.logger.verbose('Getting instance name');
return this.instance.name; return this.instance.name;
} }
public set instanceId(id: string) { public set instanceId(id: string) {
if (!id) { if (!id) {
this.logger.verbose('Instance id not found, generating random id with uuid');
this.instance.id = v4(); this.instance.id = v4();
return; return;
} }
this.logger.verbose(`Setting instanceId: ${id}`);
this.instance.id = id; this.instance.id = id;
} }
public get instanceId() { public get instanceId() {
this.logger.verbose('Getting instanceId');
return this.instance.id; return this.instance.id;
} }
public get wuid() { public get wuid() {
this.logger.verbose('Getting remoteJid of instance');
return this.instance.wuid; return this.instance.wuid;
} }
public async loadIntegration() { public async loadIntegration() {
this.logger.verbose('Loading webhook');
const data = await this.prismaRepository.integration.findUnique({ const data = await this.prismaRepository.integration.findUnique({
where: { where: {
instanceId: this.instanceId, instanceId: this.instanceId,
@ -139,19 +127,13 @@ export class ChannelStartupService {
}); });
this.localIntegration.integration = data?.integration; this.localIntegration.integration = data?.integration;
this.logger.verbose(`Integration: ${this.localIntegration.integration}`);
this.localIntegration.number = data?.number; this.localIntegration.number = data?.number;
this.logger.verbose(`Integration number: ${this.localIntegration.number}`);
this.localIntegration.token = data?.token; this.localIntegration.token = data?.token;
this.logger.verbose(`Integration token: ${this.localIntegration.token}`);
this.logger.verbose('Integration loaded');
} }
public async setIntegration(data: IntegrationDto) { public async setIntegration(data: IntegrationDto) {
this.logger.verbose('Setting integration');
console.log('setIntegration'); console.log('setIntegration');
await this.prismaRepository.integration.upsert({ await this.prismaRepository.integration.upsert({
where: { 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); Object.assign(this.localIntegration, data);
this.logger.verbose('Integration set');
} }
public async findIntegration() { public async findIntegration() {
this.logger.verbose('Finding integration');
let data; let data;
data = await this.prismaRepository.integration.findUnique({ data = await this.prismaRepository.integration.findUnique({
@ -199,15 +176,10 @@ export class ChannelStartupService {
data = { integration: 'WHATSAPP-BAILEYS', number: '', token: '' }; 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; return data;
} }
public async loadSettings() { public async loadSettings() {
this.logger.verbose('Loading settings');
const data = await this.prismaRepository.setting.findUnique({ const data = await this.prismaRepository.setting.findUnique({
where: { where: {
instanceId: this.instanceId, instanceId: this.instanceId,
@ -215,31 +187,15 @@ export class ChannelStartupService {
}); });
this.localSettings.rejectCall = data?.rejectCall; this.localSettings.rejectCall = data?.rejectCall;
this.logger.verbose(`Settings rejectCall: ${this.localSettings.rejectCall}`);
this.localSettings.msgCall = data?.msgCall; this.localSettings.msgCall = data?.msgCall;
this.logger.verbose(`Settings msgCall: ${this.localSettings.msgCall}`);
this.localSettings.groupsIgnore = data?.groupsIgnore; this.localSettings.groupsIgnore = data?.groupsIgnore;
this.logger.verbose(`Settings groupsIgnore: ${this.localSettings.groupsIgnore}`);
this.localSettings.alwaysOnline = data?.alwaysOnline; this.localSettings.alwaysOnline = data?.alwaysOnline;
this.logger.verbose(`Settings alwaysOnline: ${this.localSettings.alwaysOnline}`);
this.localSettings.readMessages = data?.readMessages; this.localSettings.readMessages = data?.readMessages;
this.logger.verbose(`Settings readMessages: ${this.localSettings.readMessages}`);
this.localSettings.readStatus = data?.readStatus; this.localSettings.readStatus = data?.readStatus;
this.logger.verbose(`Settings readStatus: ${this.localSettings.readStatus}`);
this.localSettings.syncFullHistory = data?.syncFullHistory; this.localSettings.syncFullHistory = data?.syncFullHistory;
this.logger.verbose(`Settings syncFullHistory: ${this.localSettings.syncFullHistory}`);
this.logger.verbose('Settings loaded');
} }
public async setSettings(data: SettingsDto) { public async setSettings(data: SettingsDto) {
this.logger.verbose('Setting settings');
await this.prismaRepository.setting.upsert({ await this.prismaRepository.setting.upsert({
where: { where: {
instanceId: this.instanceId, 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); Object.assign(this.localSettings, data);
this.logger.verbose('Settings set');
} }
public async findSettings() { public async findSettings() {
this.logger.verbose('Finding settings');
const data = await this.prismaRepository.setting.findUnique({ const data = await this.prismaRepository.setting.findUnique({
where: { where: {
instanceId: this.instanceId, instanceId: this.instanceId,
@ -285,17 +232,9 @@ export class ChannelStartupService {
}); });
if (!data) { if (!data) {
this.logger.verbose('Settings not found');
return null; 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 { return {
rejectCall: data.rejectCall, rejectCall: data.rejectCall,
msgCall: data.msgCall, msgCall: data.msgCall,
@ -308,7 +247,6 @@ export class ChannelStartupService {
} }
public async loadWebhook() { public async loadWebhook() {
this.logger.verbose('Loading webhook');
const data = await this.prismaRepository.webhook.findUnique({ const data = await this.prismaRepository.webhook.findUnique({
where: { where: {
instanceId: this.instanceId, instanceId: this.instanceId,
@ -316,25 +254,13 @@ export class ChannelStartupService {
}); });
this.localWebhook.url = data?.url; this.localWebhook.url = data?.url;
this.logger.verbose(`Webhook url: ${this.localWebhook.url}`);
this.localWebhook.enabled = data?.enabled; this.localWebhook.enabled = data?.enabled;
this.logger.verbose(`Webhook enabled: ${this.localWebhook.enabled}`);
this.localWebhook.events = data?.events; this.localWebhook.events = data?.events;
this.logger.verbose(`Webhook events: ${this.localWebhook.events}`);
this.localWebhook.webhookByEvents = data?.webhookByEvents; this.localWebhook.webhookByEvents = data?.webhookByEvents;
this.logger.verbose(`Webhook by events: ${this.localWebhook.webhookByEvents}`);
this.localWebhook.webhookBase64 = data?.webhookBase64; this.localWebhook.webhookBase64 = data?.webhookBase64;
this.logger.verbose(`Webhook by webhookBase64: ${this.localWebhook.webhookBase64}`);
this.logger.verbose('Webhook loaded');
} }
public async setWebhook(data: WebhookDto) { public async setWebhook(data: WebhookDto) {
this.logger.verbose('Setting webhook');
await this.prismaRepository.webhook.create({ await this.prismaRepository.webhook.create({
data: { data: {
url: data.url, 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); Object.assign(this.localWebhook, data);
this.logger.verbose('Webhook set');
} }
public async findWebhook() { public async findWebhook() {
this.logger.verbose('Finding webhook');
const data = await this.prismaRepository.webhook.findUnique({ const data = await this.prismaRepository.webhook.findUnique({
where: { where: {
instanceId: this.instanceId, instanceId: this.instanceId,
@ -361,13 +283,9 @@ export class ChannelStartupService {
}); });
if (!data) { if (!data) {
this.logger.verbose('Webhook not found');
throw new NotFoundException('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; return data;
} }
@ -376,7 +294,6 @@ export class ChannelStartupService {
return; return;
} }
this.logger.verbose('Loading chatwoot');
const data = await this.prismaRepository.chatwoot.findUnique({ const data = await this.prismaRepository.chatwoot.findUnique({
where: { where: {
instanceId: this.instanceId, instanceId: this.instanceId,
@ -384,57 +301,26 @@ export class ChannelStartupService {
}); });
this.localChatwoot.enabled = data?.enabled; this.localChatwoot.enabled = data?.enabled;
this.logger.verbose(`Chatwoot enabled: ${this.localChatwoot.enabled}`);
this.localChatwoot.accountId = data?.accountId; this.localChatwoot.accountId = data?.accountId;
this.logger.verbose(`Chatwoot account id: ${this.localChatwoot.accountId}`);
this.localChatwoot.token = data?.token; this.localChatwoot.token = data?.token;
this.logger.verbose(`Chatwoot token: ${this.localChatwoot.token}`);
this.localChatwoot.url = data?.url; this.localChatwoot.url = data?.url;
this.logger.verbose(`Chatwoot url: ${this.localChatwoot.url}`);
this.localChatwoot.nameInbox = data?.nameInbox; this.localChatwoot.nameInbox = data?.nameInbox;
this.logger.verbose(`Chatwoot inbox name: ${this.localChatwoot.nameInbox}`);
this.localChatwoot.signMsg = data?.signMsg; this.localChatwoot.signMsg = data?.signMsg;
this.logger.verbose(`Chatwoot sign msg: ${this.localChatwoot.signMsg}`);
this.localChatwoot.signDelimiter = data?.signDelimiter; this.localChatwoot.signDelimiter = data?.signDelimiter;
this.logger.verbose(`Chatwoot sign delimiter: ${this.localChatwoot.signDelimiter}`);
this.localChatwoot.number = data?.number; this.localChatwoot.number = data?.number;
this.logger.verbose(`Chatwoot number: ${this.localChatwoot.number}`);
this.localChatwoot.reopenConversation = data?.reopenConversation; this.localChatwoot.reopenConversation = data?.reopenConversation;
this.logger.verbose(`Chatwoot reopen conversation: ${this.localChatwoot.reopenConversation}`);
this.localChatwoot.conversationPending = data?.conversationPending; this.localChatwoot.conversationPending = data?.conversationPending;
this.logger.verbose(`Chatwoot conversation pending: ${this.localChatwoot.conversationPending}`);
this.localChatwoot.mergeBrazilContacts = data?.mergeBrazilContacts; this.localChatwoot.mergeBrazilContacts = data?.mergeBrazilContacts;
this.logger.verbose(`Chatwoot merge brazil contacts: ${this.localChatwoot.mergeBrazilContacts}`);
this.localChatwoot.importContacts = data?.importContacts; this.localChatwoot.importContacts = data?.importContacts;
this.logger.verbose(`Chatwoot import contacts: ${this.localChatwoot.importContacts}`);
this.localChatwoot.importMessages = data?.importMessages; this.localChatwoot.importMessages = data?.importMessages;
this.logger.verbose(`Chatwoot import messages: ${this.localChatwoot.importMessages}`);
this.localChatwoot.daysLimitImportMessages = data?.daysLimitImportMessages; 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) { public async setChatwoot(data: ChatwootDto) {
if (!this.configService.get<Chatwoot>('CHATWOOT').ENABLED) { if (!this.configService.get<Chatwoot>('CHATWOOT').ENABLED) {
this.logger.verbose('Chatwoot is not enabled');
return; return;
} }
this.logger.verbose('Setting chatwoot');
await this.prismaRepository.chatwoot.create({ await this.prismaRepository.chatwoot.create({
data: { data: {
enabled: data.enabled, 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 }); Object.assign(this.localChatwoot, { ...data, signDelimiter: data.signMsg ? data.signDelimiter : null });
this.clearCacheChatwoot(); this.clearCacheChatwoot();
this.logger.verbose('Chatwoot set');
} }
public async findChatwoot() { public async findChatwoot() {
if (!this.configService.get<Chatwoot>('CHATWOOT').ENABLED) { if (!this.configService.get<Chatwoot>('CHATWOOT').ENABLED) {
this.logger.verbose('Chatwoot is not enabled');
return null; return null;
} }
this.logger.verbose('Finding chatwoot');
const data = await this.prismaRepository.chatwoot.findUnique({ const data = await this.prismaRepository.chatwoot.findUnique({
where: { where: {
instanceId: this.instanceId, instanceId: this.instanceId,
@ -488,23 +357,9 @@ export class ChannelStartupService {
}); });
if (!data) { if (!data) {
this.logger.verbose('Chatwoot not found');
return null; 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 { return {
enabled: data.enabled, enabled: data.enabled,
accountId: data.accountId, accountId: data.accountId,
@ -523,15 +378,12 @@ export class ChannelStartupService {
} }
public clearCacheChatwoot() { public clearCacheChatwoot() {
this.logger.verbose('Removing cache from chatwoot');
if (this.localChatwoot.enabled) { if (this.localChatwoot.enabled) {
this.chatwootService.getCache()?.deleteAll(this.instanceName); this.chatwootService.getCache()?.deleteAll(this.instanceName);
} }
} }
public async loadWebsocket() { public async loadWebsocket() {
this.logger.verbose('Loading websocket');
const data = await this.prismaRepository.websocket.findUnique({ const data = await this.prismaRepository.websocket.findUnique({
where: { where: {
instanceId: this.instanceId, instanceId: this.instanceId,
@ -539,16 +391,10 @@ export class ChannelStartupService {
}); });
this.localWebsocket.enabled = data?.enabled; this.localWebsocket.enabled = data?.enabled;
this.logger.verbose(`Websocket enabled: ${this.localWebsocket.enabled}`);
this.localWebsocket.events = data?.events; this.localWebsocket.events = data?.events;
this.logger.verbose(`Websocket events: ${this.localWebsocket.events}`);
this.logger.verbose('Websocket loaded');
} }
public async setWebsocket(data: WebsocketDto) { public async setWebsocket(data: WebsocketDto) {
this.logger.verbose('Setting websocket');
await this.prismaRepository.websocket.create({ await this.prismaRepository.websocket.create({
data: { data: {
enabled: data.enabled, enabled: data.enabled,
@ -557,13 +403,10 @@ export class ChannelStartupService {
}, },
}); });
this.logger.verbose(`Websocket events: ${data.events}`);
Object.assign(this.localWebsocket, data); Object.assign(this.localWebsocket, data);
this.logger.verbose('Websocket set');
} }
public async findWebsocket() { public async findWebsocket() {
this.logger.verbose('Finding websocket');
const data = await this.prismaRepository.websocket.findUnique({ const data = await this.prismaRepository.websocket.findUnique({
where: { where: {
instanceId: this.instanceId, instanceId: this.instanceId,
@ -571,16 +414,13 @@ export class ChannelStartupService {
}); });
if (!data) { if (!data) {
this.logger.verbose('Websocket not found');
throw new NotFoundException('Websocket not found'); throw new NotFoundException('Websocket not found');
} }
this.logger.verbose(`Websocket events: ${data.events}`);
return data; return data;
} }
public async loadRabbitmq() { public async loadRabbitmq() {
this.logger.verbose('Loading rabbitmq');
const data = await this.prismaRepository.rabbitmq.findUnique({ const data = await this.prismaRepository.rabbitmq.findUnique({
where: { where: {
instanceId: this.instanceId, instanceId: this.instanceId,
@ -588,16 +428,10 @@ export class ChannelStartupService {
}); });
this.localRabbitmq.enabled = data?.enabled; this.localRabbitmq.enabled = data?.enabled;
this.logger.verbose(`Rabbitmq enabled: ${this.localRabbitmq.enabled}`);
this.localRabbitmq.events = data?.events; this.localRabbitmq.events = data?.events;
this.logger.verbose(`Rabbitmq events: ${this.localRabbitmq.events}`);
this.logger.verbose('Rabbitmq loaded');
} }
public async setRabbitmq(data: RabbitmqDto) { public async setRabbitmq(data: RabbitmqDto) {
this.logger.verbose('Setting rabbitmq');
await this.prismaRepository.rabbitmq.create({ await this.prismaRepository.rabbitmq.create({
data: { data: {
enabled: data.enabled, enabled: data.enabled,
@ -606,13 +440,10 @@ export class ChannelStartupService {
}, },
}); });
this.logger.verbose(`Rabbitmq events: ${data.events}`);
Object.assign(this.localRabbitmq, data); Object.assign(this.localRabbitmq, data);
this.logger.verbose('Rabbitmq set');
} }
public async findRabbitmq() { public async findRabbitmq() {
this.logger.verbose('Finding rabbitmq');
const data = await this.prismaRepository.rabbitmq.findUnique({ const data = await this.prismaRepository.rabbitmq.findUnique({
where: { where: {
instanceId: this.instanceId, instanceId: this.instanceId,
@ -620,24 +451,19 @@ export class ChannelStartupService {
}); });
if (!data) { if (!data) {
this.logger.verbose('Rabbitmq not found');
throw new NotFoundException('Rabbitmq not found'); throw new NotFoundException('Rabbitmq not found');
} }
this.logger.verbose(`Rabbitmq events: ${data.events}`);
return data; return data;
} }
public async removeRabbitmqQueues() { public async removeRabbitmqQueues() {
this.logger.verbose('Removing rabbitmq');
if (this.localRabbitmq.enabled) { if (this.localRabbitmq.enabled) {
removeQueues(this.instanceName, this.localRabbitmq.events); removeQueues(this.instanceName, this.localRabbitmq.events);
} }
} }
public async loadSqs() { public async loadSqs() {
this.logger.verbose('Loading sqs');
const data = await this.prismaRepository.sqs.findUnique({ const data = await this.prismaRepository.sqs.findUnique({
where: { where: {
instanceId: this.instanceId, instanceId: this.instanceId,
@ -645,16 +471,10 @@ export class ChannelStartupService {
}); });
this.localSqs.enabled = data?.enabled; this.localSqs.enabled = data?.enabled;
this.logger.verbose(`Sqs enabled: ${this.localSqs.enabled}`);
this.localSqs.events = data?.events; this.localSqs.events = data?.events;
this.logger.verbose(`Sqs events: ${this.localSqs.events}`);
this.logger.verbose('Sqs loaded');
} }
public async setSqs(data: SqsDto) { public async setSqs(data: SqsDto) {
this.logger.verbose('Setting sqs');
await this.prismaRepository.sqs.create({ await this.prismaRepository.sqs.create({
data: { data: {
enabled: data.enabled, enabled: data.enabled,
@ -663,13 +483,10 @@ export class ChannelStartupService {
}, },
}); });
this.logger.verbose(`Sqs events: ${data.events}`);
Object.assign(this.localSqs, data); Object.assign(this.localSqs, data);
this.logger.verbose('Sqs set');
} }
public async findSqs() { public async findSqs() {
this.logger.verbose('Finding sqs');
const data = await this.prismaRepository.sqs.findUnique({ const data = await this.prismaRepository.sqs.findUnique({
where: { where: {
instanceId: this.instanceId, instanceId: this.instanceId,
@ -677,17 +494,13 @@ export class ChannelStartupService {
}); });
if (!data) { if (!data) {
this.logger.verbose('Sqs not found');
throw new NotFoundException('Sqs not found'); throw new NotFoundException('Sqs not found');
} }
this.logger.verbose(`Sqs events: ${data.events}`);
return data; return data;
} }
public async removeSqsQueues() { public async removeSqsQueues() {
this.logger.verbose('Removing sqs');
if (this.localSqs.enabled) { if (this.localSqs.enabled) {
removeQueuesSQS(this.instanceName, this.localSqs.events); removeQueuesSQS(this.instanceName, this.localSqs.events);
} }
@ -697,7 +510,6 @@ export class ChannelStartupService {
if (!this.configService.get<Typebot>('TYPEBOT').ENABLED) { if (!this.configService.get<Typebot>('TYPEBOT').ENABLED) {
return; return;
} }
this.logger.verbose('Loading typebot');
const data = await this.prismaRepository.typebot.findUnique({ const data = await this.prismaRepository.typebot.findUnique({
where: { where: {
instanceId: this.instanceId, instanceId: this.instanceId,
@ -708,40 +520,20 @@ export class ChannelStartupService {
}); });
this.localTypebot.enabled = data?.enabled; this.localTypebot.enabled = data?.enabled;
this.logger.verbose(`Typebot enabled: ${this.localTypebot.enabled}`);
this.localTypebot.url = data?.url; this.localTypebot.url = data?.url;
this.logger.verbose(`Typebot url: ${this.localTypebot.url}`);
this.localTypebot.typebot = data?.typebot; this.localTypebot.typebot = data?.typebot;
this.logger.verbose(`Typebot typebot: ${this.localTypebot.typebot}`);
this.localTypebot.expire = data?.expire; this.localTypebot.expire = data?.expire;
this.logger.verbose(`Typebot expire: ${this.localTypebot.expire}`);
this.localTypebot.keywordFinish = data?.keywordFinish; this.localTypebot.keywordFinish = data?.keywordFinish;
this.logger.verbose(`Typebot keywordFinish: ${this.localTypebot.keywordFinish}`);
this.localTypebot.delayMessage = data?.delayMessage; this.localTypebot.delayMessage = data?.delayMessage;
this.logger.verbose(`Typebot delayMessage: ${this.localTypebot.delayMessage}`);
this.localTypebot.unknownMessage = data?.unknownMessage; this.localTypebot.unknownMessage = data?.unknownMessage;
this.logger.verbose(`Typebot unknownMessage: ${this.localTypebot.unknownMessage}`);
this.localTypebot.listeningFromMe = data?.listeningFromMe; this.localTypebot.listeningFromMe = data?.listeningFromMe;
this.logger.verbose(`Typebot listeningFromMe: ${this.localTypebot.listeningFromMe}`);
this.localTypebot.sessions = data?.sessions; this.localTypebot.sessions = data?.sessions;
this.logger.verbose('Typebot loaded');
} }
public async setTypebot(data: TypebotDto) { public async setTypebot(data: TypebotDto) {
if (!this.configService.get<Typebot>('TYPEBOT').ENABLED) { if (!this.configService.get<Typebot>('TYPEBOT').ENABLED) {
this.logger.verbose('Typebot is not enabled');
return; return;
} }
this.logger.verbose('Setting typebot');
const typebot = await this.prismaRepository.typebot.create({ const typebot = await this.prismaRepository.typebot.create({
data: { 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); Object.assign(this.localTypebot, data);
this.logger.verbose('Typebot set');
} }
public async findTypebot() { public async findTypebot() {
if (!this.configService.get<Typebot>('TYPEBOT').ENABLED) { if (!this.configService.get<Typebot>('TYPEBOT').ENABLED) {
this.logger.verbose('Typebot is not enabled');
return; return;
} }
this.logger.verbose('Finding typebot');
const data = await this.prismaRepository.typebot.findUnique({ const data = await this.prismaRepository.typebot.findUnique({
where: { where: {
instanceId: this.instanceId, instanceId: this.instanceId,
@ -789,7 +572,6 @@ export class ChannelStartupService {
}); });
if (!data) { if (!data) {
this.logger.verbose('Typebot not found');
throw new NotFoundException('Typebot not found'); throw new NotFoundException('Typebot not found');
} }
@ -807,7 +589,6 @@ export class ChannelStartupService {
} }
public async loadProxy() { public async loadProxy() {
this.logger.verbose('Loading proxy');
const data = await this.prismaRepository.proxy.findUnique({ const data = await this.prismaRepository.proxy.findUnique({
where: { where: {
instanceId: this.instanceId, instanceId: this.instanceId,
@ -815,28 +596,14 @@ export class ChannelStartupService {
}); });
this.localProxy.enabled = data?.enabled; this.localProxy.enabled = data?.enabled;
this.logger.verbose(`Proxy enabled: ${this.localProxy.enabled}`);
this.localProxy.host = data?.host; this.localProxy.host = data?.host;
this.logger.verbose(`Proxy host: ${this.localProxy.host}`);
this.localProxy.port = data?.port; this.localProxy.port = data?.port;
this.logger.verbose(`Proxy port: ${this.localProxy.port}`);
this.localProxy.protocol = data?.protocol; this.localProxy.protocol = data?.protocol;
this.logger.verbose(`Proxy protocol: ${this.localProxy.protocol}`);
this.localProxy.username = data?.username; this.localProxy.username = data?.username;
this.logger.verbose(`Proxy username: ${this.localProxy.username}`);
this.localProxy.password = data?.password; this.localProxy.password = data?.password;
this.logger.verbose(`Proxy password: ${this.localProxy.password}`);
this.logger.verbose('Proxy loaded');
} }
public async setProxy(data: ProxyDto) { public async setProxy(data: ProxyDto) {
this.logger.verbose('Setting proxy');
await this.prismaRepository.proxy.create({ await this.prismaRepository.proxy.create({
data: { data: {
enabled: data.enabled, enabled: data.enabled,
@ -849,13 +616,10 @@ export class ChannelStartupService {
}, },
}); });
this.logger.verbose(`Proxy proxy: ${data.host}`);
Object.assign(this.localProxy, data); Object.assign(this.localProxy, data);
this.logger.verbose('Proxy set');
} }
public async findProxy() { public async findProxy() {
this.logger.verbose('Finding proxy');
const data = await this.prismaRepository.proxy.findUnique({ const data = await this.prismaRepository.proxy.findUnique({
where: { where: {
instanceId: this.instanceId, instanceId: this.instanceId,
@ -863,7 +627,6 @@ export class ChannelStartupService {
}); });
if (!data) { if (!data) {
this.logger.verbose('Proxy not found');
throw new NotFoundException('Proxy not found'); throw new NotFoundException('Proxy not found');
} }
@ -1098,7 +861,6 @@ export class ChannelStartupService {
} }
if (this.configService.get<Websocket>('WEBSOCKET')?.ENABLED) { if (this.configService.get<Websocket>('WEBSOCKET')?.ENABLED) {
this.logger.verbose('Sending data to websocket on channel: ' + this.instance.name);
const io = getIO(); const io = getIO();
const message = { const message = {
@ -1138,9 +900,6 @@ export class ChannelStartupService {
} }
if (this.localWebsocket.enabled && Array.isArray(websocketLocal) && websocketLocal.includes(we)) { 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); io.of(`/${this.instance.name}`).emit(event, message);
if (this.configService.get<Websocket>('WEBSOCKET')?.GLOBAL_EVENTS) { if (this.configService.get<Websocket>('WEBSOCKET')?.GLOBAL_EVENTS) {
@ -1172,7 +931,6 @@ export class ChannelStartupService {
if (local) { if (local) {
if (Array.isArray(webhookLocal) && webhookLocal.includes(we)) { if (Array.isArray(webhookLocal) && webhookLocal.includes(we)) {
this.logger.verbose('Sending data to webhook local');
let baseURL: string; let baseURL: string;
if (this.localWebhook.webhookByEvents) { if (this.localWebhook.webhookByEvents) {
@ -1240,7 +998,6 @@ export class ChannelStartupService {
if (webhookGlobal.GLOBAL?.ENABLED) { if (webhookGlobal.GLOBAL?.ENABLED) {
if (webhookGlobal.EVENTS[we]) { if (webhookGlobal.EVENTS[we]) {
this.logger.verbose('Sending data to webhook global');
const globalWebhook = this.configService.get<Webhook>('WEBHOOK').GLOBAL; const globalWebhook = this.configService.get<Webhook>('WEBHOOK').GLOBAL;
let globalURL; let globalURL;
@ -1311,11 +1068,9 @@ export class ChannelStartupService {
} }
public cleanStore() { public cleanStore() {
this.logger.verbose('Cronjob to clean store initialized');
const cleanStore = this.configService.get<CleanStoreConf>('CLEAN_STORE'); const cleanStore = this.configService.get<CleanStoreConf>('CLEAN_STORE');
const database = this.configService.get<Database>('DATABASE'); const database = this.configService.get<Database>('DATABASE');
if (cleanStore?.CLEANING_INTERVAL && !database.ENABLED) { if (cleanStore?.CLEANING_INTERVAL && !database.ENABLED) {
this.logger.verbose('Cronjob to clean store enabled');
setInterval(() => { setInterval(() => {
try { try {
for (const [key, value] of Object.entries(cleanStore)) { for (const [key, value] of Object.entries(cleanStore)) {
@ -1323,9 +1078,6 @@ export class ChannelStartupService {
execSync( execSync(
`rm -rf ${join(this.storePath, key.toLowerCase().replace('_', '-'), this.instance.name)}/*.json`, `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) { } catch (error) {
@ -1370,15 +1122,11 @@ export class ChannelStartupService {
} }
public createJid(number: string): string { 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')) { 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; return number;
} }
if (number.includes('@broadcast')) { if (number.includes('@broadcast')) {
this.logger.verbose('Number already contains @broadcast');
return number; return number;
} }
@ -1391,7 +1139,6 @@ export class ChannelStartupService {
.split('@')[0]; .split('@')[0];
if (number.includes('-') && number.length >= 24) { if (number.includes('-') && number.length >= 24) {
this.logger.verbose('Jid created is group: ' + `${number}@g.us`);
number = number.replace(/[^\d-]/g, ''); number = number.replace(/[^\d-]/g, '');
return `${number}@g.us`; return `${number}@g.us`;
} }
@ -1399,7 +1146,6 @@ export class ChannelStartupService {
number = number.replace(/\D/g, ''); number = number.replace(/\D/g, '');
if (number.length >= 18) { if (number.length >= 18) {
this.logger.verbose('Jid created is group: ' + `${number}@g.us`);
number = number.replace(/[^\d-]/g, ''); number = number.replace(/[^\d-]/g, '');
return `${number}@g.us`; return `${number}@g.us`;
} }
@ -1408,12 +1154,10 @@ export class ChannelStartupService {
number = this.formatBRNumber(number); number = this.formatBRNumber(number);
this.logger.verbose('Jid created is whatsapp: ' + `${number}@s.whatsapp.net`);
return `${number}@s.whatsapp.net`; return `${number}@s.whatsapp.net`;
} }
public async fetchContacts(query: any) { public async fetchContacts(query: any) {
this.logger.verbose('Fetching contacts');
if (query?.where) { if (query?.where) {
query.where.remoteJid = this.instance.name; query.where.remoteJid = this.instance.name;
if (query.where?.remoteJid) { if (query.where?.remoteJid) {
@ -1432,7 +1176,6 @@ export class ChannelStartupService {
} }
public async fetchMessages(query: any) { public async fetchMessages(query: any) {
this.logger.verbose('Fetching messages');
if (query?.where) { if (query?.where) {
if (query.where?.key?.remoteJid) { if (query.where?.key?.remoteJid) {
query.where.key.remoteJid = this.createJid(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) { public async fetchStatusMessage(query: any) {
this.logger.verbose('Fetching status messages');
if (query?.where) { if (query?.where) {
if (query.where?.remoteJid) { if (query.where?.remoteJid) {
query.where.remoteJid = this.createJid(query.where.remoteJid); query.where.remoteJid = this.createJid(query.where.remoteJid);
@ -1468,7 +1210,6 @@ export class ChannelStartupService {
} }
public async fetchChats() { public async fetchChats() {
this.logger.verbose('Fetching chats');
return await this.prismaRepository.chat.findMany({ where: { instanceId: this.instanceId } }); 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, private readonly providerFiles: ProviderFiles,
) { ) {
super(configService, eventEmitter, prismaRepository, chatwootCache); super(configService, eventEmitter, prismaRepository, chatwootCache);
this.logger.verbose('BusinessStartupService initialized');
this.cleanStore(); this.cleanStore();
} }
@ -49,7 +48,6 @@ export class BusinessStartupService extends ChannelStartupService {
public mobile: boolean; public mobile: boolean;
public get connectionStatus() { public get connectionStatus() {
this.logger.verbose('Getting connection status');
return this.stateConnection; return this.stateConnection;
} }
@ -58,8 +56,6 @@ export class BusinessStartupService extends ChannelStartupService {
} }
public get qrCode(): wa.QrCode { public get qrCode(): wa.QrCode {
this.logger.verbose('Getting qrcode');
return { return {
pairingCode: this.instance.qrcode?.pairingCode, pairingCode: this.instance.qrcode?.pairingCode,
code: this.instance.qrcode?.code, code: this.instance.qrcode?.code,
@ -69,7 +65,6 @@ export class BusinessStartupService extends ChannelStartupService {
} }
public async logoutInstance() { public async logoutInstance() {
this.logger.verbose('Logging out instance');
await this.closeClient(); await this.closeClient();
} }
@ -92,15 +87,12 @@ export class BusinessStartupService extends ChannelStartupService {
public async profilePicture(number: string) { public async profilePicture(number: string) {
const jid = this.createJid(number); const jid = this.createJid(number);
this.logger.verbose('Getting profile picture with jid: ' + jid);
try { try {
this.logger.verbose('Getting profile picture url');
return { return {
wuid: jid, wuid: jid,
profilePictureUrl: await this.client.profilePictureUrl(jid, 'image'), profilePictureUrl: await this.client.profilePictureUrl(jid, 'image'),
}; };
} catch (error) { } catch (error) {
this.logger.verbose('Profile picture not found');
return { return {
wuid: jid, wuid: jid,
profilePictureUrl: null, profilePictureUrl: null,
@ -121,7 +113,6 @@ export class BusinessStartupService extends ChannelStartupService {
} }
public async setWhatsappBusinessProfile(data: NumberBusiness): Promise<any> { public async setWhatsappBusinessProfile(data: NumberBusiness): Promise<any> {
this.logger.verbose('set profile');
const content = { const content = {
messaging_product: 'whatsapp', messaging_product: 'whatsapp',
about: data.about, about: data.about,
@ -146,14 +137,8 @@ export class BusinessStartupService extends ChannelStartupService {
this.loadSqs(); this.loadSqs();
this.loadTypebot(); this.loadTypebot();
this.logger.verbose('Creating socket');
this.logger.verbose('Socket created');
this.eventHandler(content); this.eventHandler(content);
this.logger.verbose('Socket event handler initialized');
this.phoneNumber = this.createJid( this.phoneNumber = this.createJid(
content.messages ? content.messages[0].from : content.statuses[0]?.recipient_id, content.messages ? content.messages[0].from : content.statuses[0]?.recipient_id,
); );
@ -229,7 +214,6 @@ export class BusinessStartupService extends ChannelStartupService {
let content: any = {}; let content: any = {};
const vcard = (contact: any) => { const vcard = (contact: any) => {
this.logger.verbose('Creating vcard');
let result = let result =
'BEGIN:VCARD\n' + 'BEGIN:VCARD\n' +
'VERSION:3.0\n' + 'VERSION:3.0\n' +
@ -237,22 +221,18 @@ export class BusinessStartupService extends ChannelStartupService {
`FN:${contact.name.formatted_name}\n`; `FN:${contact.name.formatted_name}\n`;
if (contact.org) { if (contact.org) {
this.logger.verbose('Organization defined');
result += `ORG:${contact.org.company};\n`; result += `ORG:${contact.org.company};\n`;
} }
if (contact.emails) { if (contact.emails) {
this.logger.verbose('Email defined');
result += `EMAIL:${contact.emails[0].email}\n`; result += `EMAIL:${contact.emails[0].email}\n`;
} }
if (contact.urls) { if (contact.urls) {
this.logger.verbose('Url defined');
result += `URL:${contact.urls[0].url}\n`; result += `URL:${contact.urls[0].url}\n`;
} }
if (!contact.phones[0]?.wa_id) { if (!contact.phones[0]?.wa_id) {
this.logger.verbose('Wuid defined');
contact.phones[0].wa_id = this.createJid(contact.phones[0].phone); 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' + 'item1.X-ABLabel:Celular\n' +
'END:VCARD'; 'END:VCARD';
this.logger.verbose('Vcard created');
return result; return result;
}; };
@ -405,8 +384,6 @@ export class BusinessStartupService extends ChannelStartupService {
this.logger.log(messageRaw); this.logger.log(messageRaw);
this.logger.verbose('Sending data to webhook in event MESSAGES_UPSERT');
this.sendDataWebhook(Events.MESSAGES_UPSERT, messageRaw); this.sendDataWebhook(Events.MESSAGES_UPSERT, messageRaw);
if (this.configService.get<Chatwoot>('CHATWOOT').ENABLED && this.localChatwoot.enabled) { 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({ await this.prismaRepository.message.create({
data: messageRaw, data: messageRaw,
}); });
this.logger.verbose('Verifying contact from message');
const contact = await this.prismaRepository.contact.findFirst({ const contact = await this.prismaRepository.contact.findFirst({
where: { instanceId: this.instanceId, remoteJid: key.remoteJid }, where: { instanceId: this.instanceId, remoteJid: key.remoteJid },
}); });
@ -460,12 +435,10 @@ export class BusinessStartupService extends ChannelStartupService {
}; };
if (contactRaw.remoteJid === 'status@broadcast') { if (contactRaw.remoteJid === 'status@broadcast') {
this.logger.verbose('Contact is status@broadcast');
return; return;
} }
if (contact) { if (contact) {
this.logger.verbose('Contact found in database');
const contactRaw: any = { const contactRaw: any = {
remoteJid: received.contacts[0].profile.phone, remoteJid: received.contacts[0].profile.phone,
pushName, pushName,
@ -473,7 +446,6 @@ export class BusinessStartupService extends ChannelStartupService {
instanceId: this.instanceId, instanceId: this.instanceId,
}; };
this.logger.verbose('Sending data to webhook in event CONTACTS_UPDATE');
this.sendDataWebhook(Events.CONTACTS_UPDATE, contactRaw); this.sendDataWebhook(Events.CONTACTS_UPDATE, contactRaw);
if (this.configService.get<Chatwoot>('CHATWOOT').ENABLED && this.localChatwoot.enabled) { 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({ await this.prismaRepository.contact.updateMany({
where: { remoteJid: contact.remoteJid }, where: { remoteJid: contact.remoteJid },
data: contactRaw, data: contactRaw,
@ -492,17 +463,12 @@ export class BusinessStartupService extends ChannelStartupService {
return; 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.sendDataWebhook(Events.CONTACTS_UPSERT, contactRaw);
this.logger.verbose('Inserting contact in database');
this.prismaRepository.contact.create({ this.prismaRepository.contact.create({
data: contactRaw, data: contactRaw,
}); });
} }
this.logger.verbose('Event received: messages.update');
if (received.statuses) { if (received.statuses) {
for await (const item of received.statuses) { for await (const item of received.statuses) {
const key = { const key = {
@ -511,12 +477,9 @@ export class BusinessStartupService extends ChannelStartupService {
fromMe: this.phoneNumber === received.metadata.phone_number_id, fromMe: this.phoneNumber === received.metadata.phone_number_id,
}; };
if (settings?.groups_ignore && key.remoteJid.includes('@g.us')) { if (settings?.groups_ignore && key.remoteJid.includes('@g.us')) {
this.logger.verbose('group ignored');
return; return;
} }
if (key.remoteJid !== 'status@broadcast' && !key?.remoteJid?.match(/(:\d+)/)) { if (key.remoteJid !== 'status@broadcast' && !key?.remoteJid?.match(/(:\d+)/)) {
this.logger.verbose('Message update is valid');
if (item.status === 'read' && !key.fromMe) return; if (item.status === 'read' && !key.fromMe) return;
const findMessage = await this.prismaRepository.message.findFirst({ const findMessage = await this.prismaRepository.message.findFirst({
@ -530,9 +493,6 @@ export class BusinessStartupService extends ChannelStartupService {
}); });
if (item.message === null && item.status === undefined) { 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); this.sendDataWebhook(Events.MESSAGES_DELETE, key);
const message: any = { const message: any = {
@ -546,9 +506,6 @@ export class BusinessStartupService extends ChannelStartupService {
instanceId: this.instanceId, instanceId: this.instanceId,
}; };
this.logger.verbose(message);
this.logger.verbose('Inserting message in database');
await this.prismaRepository.messageUpdate.create({ await this.prismaRepository.messageUpdate.create({
data: message, data: message,
}); });
@ -575,12 +532,8 @@ export class BusinessStartupService extends ChannelStartupService {
instanceId: this.instanceId, 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.sendDataWebhook(Events.MESSAGES_UPDATE, message);
this.logger.verbose('Inserting message in database');
await this.prismaRepository.messageUpdate.create({ await this.prismaRepository.messageUpdate.create({
data: message, data: message,
}); });
@ -661,16 +614,13 @@ export class BusinessStartupService extends ChannelStartupService {
} }
protected async eventHandler(content: any) { protected async eventHandler(content: any) {
this.logger.verbose('Initializing event handler');
const database = this.configService.get<Database>('DATABASE'); const database = this.configService.get<Database>('DATABASE');
const settings = await this.findSettings(); const settings = await this.findSettings();
this.logger.verbose('Listening event: messages.statuses');
this.messageHandle(content, database, settings); this.messageHandle(content, database, settings);
} }
protected async sendMessageWithTyping(number: string, message: any, options?: Options, isChatwoot = false) { protected async sendMessageWithTyping(number: string, message: any, options?: Options, isChatwoot = false) {
this.logger.verbose('Sending message with typing');
try { try {
let quoted: any; let quoted: any;
const linkPreview = options?.linkPreview != false ? undefined : false; const linkPreview = options?.linkPreview != false ? undefined : false;
@ -684,13 +634,11 @@ export class BusinessStartupService extends ChannelStartupService {
} }
quoted = msg; quoted = msg;
this.logger.verbose('Quoted message');
} }
let content: any; let content: any;
const messageSent = await (async () => { const messageSent = await (async () => {
if (message['reactionMessage']) { if (message['reactionMessage']) {
this.logger.verbose('Sending reaction');
content = { content = {
messaging_product: 'whatsapp', messaging_product: 'whatsapp',
recipient_type: 'individual', recipient_type: 'individual',
@ -705,7 +653,6 @@ export class BusinessStartupService extends ChannelStartupService {
return await this.post(content, 'messages'); return await this.post(content, 'messages');
} }
if (message['locationMessage']) { if (message['locationMessage']) {
this.logger.verbose('Sending message');
content = { content = {
messaging_product: 'whatsapp', messaging_product: 'whatsapp',
recipient_type: 'individual', recipient_type: 'individual',
@ -722,7 +669,6 @@ export class BusinessStartupService extends ChannelStartupService {
return await this.post(content, 'messages'); return await this.post(content, 'messages');
} }
if (message['contacts']) { if (message['contacts']) {
this.logger.verbose('Sending message');
content = { content = {
messaging_product: 'whatsapp', messaging_product: 'whatsapp',
recipient_type: 'individual', recipient_type: 'individual',
@ -735,7 +681,6 @@ export class BusinessStartupService extends ChannelStartupService {
return await this.post(content, 'messages'); return await this.post(content, 'messages');
} }
if (message['conversation']) { if (message['conversation']) {
this.logger.verbose('Sending message');
content = { content = {
messaging_product: 'whatsapp', messaging_product: 'whatsapp',
recipient_type: 'individual', recipient_type: 'individual',
@ -750,7 +695,6 @@ export class BusinessStartupService extends ChannelStartupService {
return await this.post(content, 'messages'); return await this.post(content, 'messages');
} }
if (message['media']) { if (message['media']) {
this.logger.verbose('Sending message');
content = { content = {
messaging_product: 'whatsapp', messaging_product: 'whatsapp',
recipient_type: 'individual', recipient_type: 'individual',
@ -766,7 +710,6 @@ export class BusinessStartupService extends ChannelStartupService {
return await this.post(content, 'messages'); return await this.post(content, 'messages');
} }
if (message['audio']) { if (message['audio']) {
this.logger.verbose('Sending message');
content = { content = {
messaging_product: 'whatsapp', messaging_product: 'whatsapp',
recipient_type: 'individual', recipient_type: 'individual',
@ -780,7 +723,6 @@ export class BusinessStartupService extends ChannelStartupService {
return await this.post(content, 'messages'); return await this.post(content, 'messages');
} }
if (message['buttons']) { if (message['buttons']) {
this.logger.verbose('Sending message');
content = { content = {
messaging_product: 'whatsapp', messaging_product: 'whatsapp',
recipient_type: 'individual', recipient_type: 'individual',
@ -805,7 +747,6 @@ export class BusinessStartupService extends ChannelStartupService {
return await this.post(content, 'messages'); return await this.post(content, 'messages');
} }
if (message['sections']) { if (message['sections']) {
this.logger.verbose('Sending message');
content = { content = {
messaging_product: 'whatsapp', messaging_product: 'whatsapp',
recipient_type: 'individual', recipient_type: 'individual',
@ -841,7 +782,6 @@ export class BusinessStartupService extends ChannelStartupService {
return await this.post(content, 'messages'); return await this.post(content, 'messages');
} }
if (message['template']) { if (message['template']) {
this.logger.verbose('Sending message');
content = { content = {
messaging_product: 'whatsapp', messaging_product: 'whatsapp',
recipient_type: 'individual', recipient_type: 'individual',
@ -880,14 +820,12 @@ export class BusinessStartupService extends ChannelStartupService {
this.logger.log(messageRaw); this.logger.log(messageRaw);
this.logger.verbose('Sending data to webhook in event SEND_MESSAGE');
this.sendDataWebhook(Events.SEND_MESSAGE, messageRaw); this.sendDataWebhook(Events.SEND_MESSAGE, messageRaw);
if (this.configService.get<Chatwoot>('CHATWOOT').ENABLED && this.localChatwoot.enabled && !isChatwoot) { if (this.configService.get<Chatwoot>('CHATWOOT').ENABLED && this.localChatwoot.enabled && !isChatwoot) {
this.chatwootService.eventWhatsapp(Events.SEND_MESSAGE, { instanceName: this.instance.name }, messageRaw); this.chatwootService.eventWhatsapp(Events.SEND_MESSAGE, { instanceName: this.instance.name }, messageRaw);
} }
this.logger.verbose('Inserting message in database');
await this.prismaRepository.message.create({ await this.prismaRepository.message.create({
data: messageRaw, data: messageRaw,
}); });
@ -901,7 +839,6 @@ export class BusinessStartupService extends ChannelStartupService {
// Send Message Controller // Send Message Controller
public async textMessage(data: SendTextDto, isChatwoot = false) { public async textMessage(data: SendTextDto, isChatwoot = false) {
this.logger.verbose('Sending text message');
const res = await this.sendMessageWithTyping( const res = await this.sendMessageWithTyping(
data.number, data.number,
{ {
@ -935,17 +872,10 @@ export class BusinessStartupService extends ChannelStartupService {
protected async prepareMediaMessage(mediaMessage: MediaMessage) { protected async prepareMediaMessage(mediaMessage: MediaMessage) {
try { try {
this.logger.verbose('Preparing media message');
const mediaType = mediaMessage.mediatype + 'Message';
this.logger.verbose('Media type: ' + mediaType);
if (mediaMessage.mediatype === 'document' && !mediaMessage.fileName) { 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 regex = new RegExp(/.*\/(.+?)\./);
const arrayMatch = regex.exec(mediaMessage.media); const arrayMatch = regex.exec(mediaMessage.media);
mediaMessage.fileName = arrayMatch[1]; mediaMessage.fileName = arrayMatch[1];
this.logger.verbose('File name: ' + mediaMessage.fileName);
} }
if (mediaMessage.mediatype === 'image' && !mediaMessage.fileName) { if (mediaMessage.mediatype === 'image' && !mediaMessage.fileName) {
@ -983,7 +913,6 @@ export class BusinessStartupService extends ChannelStartupService {
prepareMedia.mimetype = mimetype; prepareMedia.mimetype = mimetype;
this.logger.verbose('Generating wa message from content');
return prepareMedia; return prepareMedia;
} catch (error) { } catch (error) {
this.logger.error(error); this.logger.error(error);
@ -992,18 +921,14 @@ export class BusinessStartupService extends ChannelStartupService {
} }
public async mediaMessage(data: SendMediaDto, isChatwoot = false) { public async mediaMessage(data: SendMediaDto, isChatwoot = false) {
this.logger.verbose('Sending media message');
const message = await this.prepareMediaMessage(data.mediaMessage); const message = await this.prepareMediaMessage(data.mediaMessage);
return await this.sendMessageWithTyping(data.number, { ...message }, data?.options, isChatwoot); return await this.sendMessageWithTyping(data.number, { ...message }, data?.options, isChatwoot);
} }
public async processAudio(audio: string, number: string) { public async processAudio(audio: string, number: string) {
this.logger.verbose('Processing audio');
number = number.replace(/\D/g, ''); number = number.replace(/\D/g, '');
const hash = `${number}-${new Date().getTime()}`; const hash = `${number}-${new Date().getTime()}`;
this.logger.verbose('Hash to audio name: ' + hash);
let mimetype: string; let mimetype: string;
@ -1030,15 +955,12 @@ export class BusinessStartupService extends ChannelStartupService {
} }
public async audioWhatsapp(data: SendAudioDto, isChatwoot = false) { public async audioWhatsapp(data: SendAudioDto, isChatwoot = false) {
this.logger.verbose('Sending audio whatsapp');
const message = await this.processAudio(data.audioMessage.audio, data.number); const message = await this.processAudio(data.audioMessage.audio, data.number);
return await this.sendMessageWithTyping(data.number, { ...message }, data?.options, isChatwoot); return await this.sendMessageWithTyping(data.number, { ...message }, data?.options, isChatwoot);
} }
public async buttonMessage(data: SendButtonDto) { public async buttonMessage(data: SendButtonDto) {
this.logger.verbose('Sending button message');
const embeddedMedia: any = {}; const embeddedMedia: any = {};
let mediatype = 'TEXT'; let mediatype = 'TEXT';
@ -1079,7 +1001,6 @@ export class BusinessStartupService extends ChannelStartupService {
} }
public async locationMessage(data: SendLocationDto) { public async locationMessage(data: SendLocationDto) {
this.logger.verbose('Sending location message');
return await this.sendMessageWithTyping( return await this.sendMessageWithTyping(
data.number, data.number,
{ {
@ -1095,7 +1016,6 @@ export class BusinessStartupService extends ChannelStartupService {
} }
public async listMessage(data: SendListDto) { public async listMessage(data: SendListDto) {
this.logger.verbose('Sending list message');
const sectionsItems = { const sectionsItems = {
title: data.listMessage.sections.map((list) => list.title), title: data.listMessage.sections.map((list) => list.title),
}; };
@ -1129,7 +1049,6 @@ export class BusinessStartupService extends ChannelStartupService {
} }
public async templateMessage(data: SendTemplateDto, isChatwoot = false) { public async templateMessage(data: SendTemplateDto, isChatwoot = false) {
this.logger.verbose('Sending text message');
const res = await this.sendMessageWithTyping( const res = await this.sendMessageWithTyping(
data.number, data.number,
{ {
@ -1146,36 +1065,29 @@ export class BusinessStartupService extends ChannelStartupService {
} }
public async contactMessage(data: SendContactDto) { public async contactMessage(data: SendContactDto) {
this.logger.verbose('Sending contact message');
const message: any = {}; const message: any = {};
const vcard = (contact: ContactMessage) => { 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`; let result = 'BEGIN:VCARD\n' + 'VERSION:3.0\n' + `N:${contact.fullName}\n` + `FN:${contact.fullName}\n`;
if (contact.organization) { if (contact.organization) {
this.logger.verbose('Organization defined');
result += `ORG:${contact.organization};\n`; result += `ORG:${contact.organization};\n`;
} }
if (contact.email) { if (contact.email) {
this.logger.verbose('Email defined');
result += `EMAIL:${contact.email}\n`; result += `EMAIL:${contact.email}\n`;
} }
if (contact.url) { if (contact.url) {
this.logger.verbose('Url defined');
result += `URL:${contact.url}\n`; result += `URL:${contact.url}\n`;
} }
if (!contact.wuid) { if (!contact.wuid) {
this.logger.verbose('Wuid defined');
contact.wuid = this.createJid(contact.phoneNumber); contact.wuid = this.createJid(contact.phoneNumber);
} }
result += `item1.TEL;waid=${contact.wuid}:${contact.phoneNumber}\n` + 'item1.X-ABLabel:Celular\n' + 'END:VCARD'; result += `item1.TEL;waid=${contact.wuid}:${contact.phoneNumber}\n` + 'item1.X-ABLabel:Celular\n' + 'END:VCARD';
this.logger.verbose('Vcard created');
return result; return result;
}; };
@ -1214,7 +1126,6 @@ export class BusinessStartupService extends ChannelStartupService {
} }
public async reactionMessage(data: SendReactionDto) { public async reactionMessage(data: SendReactionDto) {
this.logger.verbose('Sending reaction message');
return await this.sendMessageWithTyping(data.reactionMessage.key.remoteJid, { return await this.sendMessageWithTyping(data.reactionMessage.key.remoteJid, {
reactionMessage: { reactionMessage: {
key: data.reactionMessage.key, key: data.reactionMessage.key,
@ -1226,11 +1137,9 @@ export class BusinessStartupService extends ChannelStartupService {
public async getBase64FromMediaMessage(data: any) { public async getBase64FromMediaMessage(data: any) {
try { try {
const msg = data.message; const msg = data.message;
this.logger.verbose('Getting base64 from media message');
const messageType = msg.messageType + 'Message'; const messageType = msg.messageType + 'Message';
const mediaMessage = msg.message[messageType]; const mediaMessage = msg.message[messageType];
this.logger.verbose('Media message downloaded');
return { return {
mediaType: msg.messageType, mediaType: msg.messageType,
fileName: mediaMessage?.fileName, fileName: mediaMessage?.fileName,

View File

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

View File

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

View File

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

View File

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

View File

@ -41,10 +41,8 @@ class Redis {
}); });
try { try {
this.logger.verbose('connecting new redis client');
this.client.connect(); this.client.connect();
this.connected = true; this.connected = true;
this.logger.verbose('connected to new redis client');
} catch (e) { } catch (e) {
this.connected = false; this.connected = false;
this.logger.error('redis connect exception caught: ' + e); this.logger.error('redis connect exception caught: ' + e);

View File

@ -12,8 +12,6 @@ export const prismaServer = (() => {
logger.verbose('connecting'); logger.verbose('connecting');
const db = new PrismaClient(); const db = new PrismaClient();
logger.verbose('connected in ' + db.$connect);
process.on('beforeExit', () => { process.on('beforeExit', () => {
logger.verbose('instance destroyed'); logger.verbose('instance destroyed');
db.$disconnect(); db.$disconnect();