This commit is contained in:
Alan Mosko 2023-07-26 11:08:14 -03:00
parent 5482601b41
commit ddc75d710f
21 changed files with 5975 additions and 6309 deletions

View File

@ -81,6 +81,7 @@
"@types/express": "^4.17.17",
"@types/js-yaml": "^4.0.5",
"@types/jsonwebtoken": "^8.5.9",
"@types/mime-types": "^2.1.1",
"@types/node": "^18.15.11",
"@types/qrcode": "^1.5.0",
"@types/qrcode-terminal": "^0.12.0",

View File

@ -1,7 +1,7 @@
import { isBooleanString } from 'class-validator';
import { readFileSync } from 'fs';
import { load } from 'js-yaml';
import { join } from 'path';
import { isBooleanString } from 'class-validator';
export type HttpServer = { TYPE: 'http' | 'https'; PORT: number; URL: string };
@ -14,15 +14,7 @@ export type Cors = {
export type LogBaileys = 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace';
export type LogLevel =
| 'ERROR'
| 'WARN'
| 'DEBUG'
| 'INFO'
| 'LOG'
| 'VERBOSE'
| 'DARK'
| 'WEBHOOKS';
export type LogLevel = 'ERROR' | 'WARN' | 'DEBUG' | 'INFO' | 'LOG' | 'VERBOSE' | 'DARK' | 'WEBHOOKS';
export type Log = {
LEVEL: LogLevel[];
@ -156,9 +148,7 @@ export class ConfigService {
}
private envYaml(): Env {
return load(
readFileSync(join(process.cwd(), 'src', 'env.yml'), { encoding: 'utf-8' }),
) as Env;
return load(readFileSync(join(process.cwd(), 'src', 'env.yml'), { encoding: 'utf-8' })) as Env;
}
private envProcess(): Env {
@ -244,8 +234,7 @@ export class ConfigService {
CONNECTION_UPDATE: process.env?.WEBHOOK_EVENTS_CONNECTION_UPDATE === 'true',
GROUPS_UPSERT: process.env?.WEBHOOK_EVENTS_GROUPS_UPSERT === 'true',
GROUP_UPDATE: process.env?.WEBHOOK_EVENTS_GROUPS_UPDATE === 'true',
GROUP_PARTICIPANTS_UPDATE:
process.env?.WEBHOOK_EVENTS_GROUP_PARTICIPANTS_UPDATE === 'true',
GROUP_PARTICIPANTS_UPDATE: process.env?.WEBHOOK_EVENTS_GROUP_PARTICIPANTS_UPDATE === 'true',
CALL: process.env?.WEBHOOK_EVENTS_CALL === 'true',
NEW_JWT_TOKEN: process.env?.WEBHOOK_EVENTS_NEW_JWT_TOKEN === 'true',
},
@ -262,8 +251,7 @@ export class ConfigService {
API_KEY: {
KEY: process.env.AUTHENTICATION_API_KEY,
},
EXPOSE_IN_FETCH_INSTANCES:
process.env?.AUTHENTICATION_EXPOSE_IN_FETCH_INSTANCES === 'true',
EXPOSE_IN_FETCH_INSTANCES: process.env?.AUTHENTICATION_EXPOSE_IN_FETCH_INSTANCES === 'true',
JWT: {
EXPIRIN_IN: Number.isInteger(process.env?.AUTHENTICATION_JWT_EXPIRIN_IN)
? Number.parseInt(process.env.AUTHENTICATION_JWT_EXPIRIN_IN)

View File

@ -877,23 +877,8 @@ export const chatwootSchema: JSONSchema7 = {
reopen_conversation: { type: 'boolean', enum: [true, false] },
conversation_pending: { type: 'boolean', enum: [true, false] },
},
required: [
'enabled',
'account_id',
'token',
'url',
'sign_msg',
'reopen_conversation',
'conversation_pending',
],
...isNotEmpty(
'account_id',
'token',
'url',
'sign_msg',
'reopen_conversation',
'conversation_pending',
),
required: ['enabled', 'account_id', 'token', 'url', 'sign_msg', 'reopen_conversation', 'conversation_pending'],
...isNotEmpty('account_id', 'token', 'url', 'sign_msg', 'reopen_conversation', 'conversation_pending'),
};
export const settingsSchema: JSONSchema7 = {
@ -907,18 +892,6 @@ export const settingsSchema: JSONSchema7 = {
read_messages: { type: 'boolean', enum: [true, false] },
read_status: { type: 'boolean', enum: [true, false] },
},
required: [
'reject_call',
'groups_ignore',
'always_online',
'read_messages',
'read_status',
],
...isNotEmpty(
'reject_call',
'groups_ignore',
'always_online',
'read_messages',
'read_status',
),
required: ['reject_call', 'groups_ignore', 'always_online', 'read_messages', 'read_status'],
...isNotEmpty('reject_call', 'groups_ignore', 'always_online', 'read_messages', 'read_status'),
};

View File

@ -1,24 +1,20 @@
import { isURL } from 'class-validator';
import { BadRequestException } from '../../exceptions';
import { InstanceDto } from '../dto/instance.dto';
import { ChatwootDto } from '../dto/chatwoot.dto';
import { ChatwootService } from '../services/chatwoot.service';
import { Logger } from '../../config/logger.config';
import { waMonitor } from '../whatsapp.module';
import { ConfigService, HttpServer } from '../../config/env.config';
import { Logger } from '../../config/logger.config';
import { BadRequestException } from '../../exceptions';
import { ChatwootDto } from '../dto/chatwoot.dto';
import { InstanceDto } from '../dto/instance.dto';
import { ChatwootService } from '../services/chatwoot.service';
import { waMonitor } from '../whatsapp.module';
const logger = new Logger('ChatwootController');
export class ChatwootController {
constructor(
private readonly chatwootService: ChatwootService,
private readonly configService: ConfigService,
) {}
constructor(private readonly chatwootService: ChatwootService, private readonly configService: ConfigService) {}
public async createChatwoot(instance: InstanceDto, data: ChatwootDto) {
logger.verbose(
'requested createChatwoot from ' + instance.instanceName + ' instance',
);
logger.verbose('requested createChatwoot from ' + instance.instanceName + ' instance');
if (data.enabled) {
if (!isURL(data.url, { require_tld: false })) {
@ -89,9 +85,7 @@ export class ChatwootController {
}
public async receiveWebhook(instance: InstanceDto, data: any) {
logger.verbose(
'requested receiveWebhook from ' + instance.instanceName + ' instance',
);
logger.verbose('requested receiveWebhook from ' + instance.instanceName + ' instance');
const chatwootService = new ChatwootService(waMonitor, this.configService);
return chatwootService.receiveWebhook(instance, data);

View File

@ -1,19 +1,20 @@
import { delay } from '@whiskeysockets/baileys';
import { isURL } from 'class-validator';
import EventEmitter2 from 'eventemitter2';
import { Auth, ConfigService, HttpServer } from '../../config/env.config';
import { ConfigService, HttpServer } from '../../config/env.config';
import { Logger } from '../../config/logger.config';
import { RedisCache } from '../../db/redis.client';
import { BadRequestException, InternalServerErrorException } from '../../exceptions';
import { InstanceDto } from '../dto/instance.dto';
import { RepositoryBroker } from '../repository/repository.manager';
import { AuthService, OldToken } from '../services/auth.service';
import { WAMonitoringService } from '../services/monitor.service';
import { WAStartupService } from '../services/whatsapp.service';
import { WebhookService } from '../services/webhook.service';
import { ChatwootService } from '../services/chatwoot.service';
import { Logger } from '../../config/logger.config';
import { wa } from '../types/wa.types';
import { RedisCache } from '../../db/redis.client';
import { isURL } from 'class-validator';
import { WAMonitoringService } from '../services/monitor.service';
import { SettingsService } from '../services/settings.service';
import { WebhookService } from '../services/webhook.service';
import { WAStartupService } from '../services/whatsapp.service';
import { wa } from '../types/wa.types';
export class InstanceController {
constructor(
@ -55,21 +56,14 @@ export class InstanceController {
this.logger.verbose('requested createInstance from ' + instanceName + ' instance');
if (instanceName !== instanceName.toLowerCase().replace(/[^a-z0-9]/g, '')) {
throw new BadRequestException(
'The instance name must be lowercase and without special characters',
);
throw new BadRequestException('The instance name must be lowercase and without special characters');
}
this.logger.verbose('checking duplicate token');
await this.authService.checkDuplicateToken(token);
this.logger.verbose('creating instance');
const instance = new WAStartupService(
this.configService,
this.eventEmitter,
this.repository,
this.cache,
);
const instance = new WAStartupService(this.configService, this.eventEmitter, this.repository, this.cache);
instance.instanceName = instanceName
.toLowerCase()
.replace(/[^a-z0-9]/g, '')
@ -175,17 +169,11 @@ export class InstanceController {
throw new BadRequestException('sign_msg is required');
}
if (
chatwoot_reopen_conversation !== true &&
chatwoot_reopen_conversation !== false
) {
if (chatwoot_reopen_conversation !== true && chatwoot_reopen_conversation !== false) {
throw new BadRequestException('reopen_conversation is required');
}
if (
chatwoot_conversation_pending !== true &&
chatwoot_conversation_pending !== false
) {
if (chatwoot_conversation_pending !== true && chatwoot_conversation_pending !== false) {
throw new BadRequestException('conversation_pending is required');
}
@ -246,9 +234,7 @@ export class InstanceController {
public async connectToWhatsapp({ instanceName, number = null }: InstanceDto) {
try {
this.logger.verbose(
'requested connectToWhatsapp from ' + instanceName + ' instance',
);
this.logger.verbose('requested connectToWhatsapp from ' + instanceName + ' instance');
const instance = this.waMonitor.waInstances[instanceName];
const state = instance?.connectionStatus?.state;
@ -321,16 +307,12 @@ export class InstanceController {
const { instance } = await this.connectionState({ instanceName });
if (instance.state === 'close') {
throw new BadRequestException(
'The "' + instanceName + '" instance is not connected',
);
throw new BadRequestException('The "' + instanceName + '" instance is not connected');
}
try {
this.logger.verbose('logging out instance: ' + instanceName);
await this.waMonitor.waInstances[instanceName]?.client?.logout(
'Log out instance: ' + instanceName,
);
await this.waMonitor.waInstances[instanceName]?.client?.logout('Log out instance: ' + instanceName);
this.logger.verbose('close connection instance: ' + instanceName);
this.waMonitor.waInstances[instanceName]?.client?.ws?.close();
@ -346,9 +328,7 @@ export class InstanceController {
const { instance } = await this.connectionState({ instanceName });
if (instance.state === 'open') {
throw new BadRequestException(
'The "' + instanceName + '" instance needs to be disconnected',
);
throw new BadRequestException('The "' + instanceName + '" instance needs to be disconnected');
}
try {
if (instance.state === 'connecting') {

View File

@ -1,9 +1,10 @@
import { isURL } from 'class-validator';
import { BadRequestException } from '../../exceptions';
// import { isURL } from 'class-validator';
import { Logger } from '../../config/logger.config';
// import { BadRequestException } from '../../exceptions';
import { InstanceDto } from '../dto/instance.dto';
import { SettingsDto } from '../dto/settings.dto';
import { SettingsService } from '../services/settings.service';
import { Logger } from '../../config/logger.config';
const logger = new Logger('SettingsController');
@ -11,9 +12,7 @@ export class SettingsController {
constructor(private readonly settingsService: SettingsService) {}
public async createSettings(instance: InstanceDto, data: SettingsDto) {
logger.verbose(
'requested createSettings from ' + instance.instanceName + ' instance',
);
logger.verbose('requested createSettings from ' + instance.instanceName + ' instance');
return this.settingsService.create(instance, data);
}

View File

@ -1,16 +1,7 @@
import {
WAPrivacyOnlineValue,
WAPrivacyValue,
WAReadReceiptsValue,
proto,
} from '@whiskeysockets/baileys';
import { proto, WAPrivacyOnlineValue, WAPrivacyValue, WAReadReceiptsValue } from '@whiskeysockets/baileys';
export class OnWhatsAppDto {
constructor(
public readonly jid: string,
public readonly exists: boolean,
public readonly name?: string,
) {}
constructor(public readonly jid: string, public readonly exists: boolean, public readonly name?: string) {}
}
export class getBase64FromMediaMessageDto {

View File

@ -1,4 +1,5 @@
import { Schema } from 'mongoose';
import { dbserver } from '../../db/db.connect';
export class ChatwootRaw {
@ -25,9 +26,5 @@ const chatwootSchema = new Schema<ChatwootRaw>({
number: { type: String, required: true },
});
export const ChatwootModel = dbserver?.model(
ChatwootRaw.name,
chatwootSchema,
'chatwoot',
);
export const ChatwootModel = dbserver?.model(ChatwootRaw.name, chatwootSchema, 'chatwoot');
export type IChatwootModel = typeof ChatwootModel;

View File

@ -1,4 +1,5 @@
import { Schema } from 'mongoose';
import { dbserver } from '../../db/db.connect';
export class SettingsRaw {
@ -21,9 +22,5 @@ const settingsSchema = new Schema<SettingsRaw>({
read_status: { type: Boolean, required: true },
});
export const SettingsModel = dbserver?.model(
SettingsRaw.name,
settingsSchema,
'settings',
);
export const SettingsModel = dbserver?.model(SettingsRaw.name, settingsSchema, 'settings');
export type ISettingsModel = typeof SettingsModel;

View File

@ -1,17 +1,17 @@
import { MessageRepository } from './message.repository';
import { ChatRepository } from './chat.repository';
import { ContactRepository } from './contact.repository';
import { MessageUpRepository } from './messageUp.repository';
import { MongoClient } from 'mongodb';
import { WebhookRepository } from './webhook.repository';
import { ChatwootRepository } from './chatwoot.repository';
import { SettingsRepository } from './settings.repository';
import { AuthRepository } from './auth.repository';
import { Auth, ConfigService, Database } from '../../config/env.config';
import { join } from 'path';
import fs from 'fs';
import { MongoClient } from 'mongodb';
import { join } from 'path';
import { Auth, ConfigService, Database } from '../../config/env.config';
import { Logger } from '../../config/logger.config';
import { AuthRepository } from './auth.repository';
import { ChatRepository } from './chat.repository';
import { ChatwootRepository } from './chatwoot.repository';
import { ContactRepository } from './contact.repository';
import { MessageRepository } from './message.repository';
import { MessageUpRepository } from './messageUp.repository';
import { SettingsRepository } from './settings.repository';
import { WebhookRepository } from './webhook.repository';
export class RepositoryBroker {
constructor(
public readonly message: MessageRepository,
@ -43,11 +43,7 @@ export class RepositoryBroker {
this.logger.verbose('creating store path: ' + storePath);
try {
const authDir = join(
storePath,
'auth',
this.configService.get<Auth>('AUTHENTICATION').TYPE,
);
const authDir = join(storePath, 'auth', this.configService.get<Auth>('AUTHENTICATION').TYPE);
const chatsDir = join(storePath, 'chats');
const contactsDir = join(storePath, 'contacts');
const messagesDir = join(storePath, 'messages');
@ -97,6 +93,7 @@ export class RepositoryBroker {
this.logger.error(error);
}
} else {
try {
const storePath = join(process.cwd(), 'store');
this.logger.verbose('creating store path: ' + storePath);
@ -112,7 +109,6 @@ export class RepositoryBroker {
this.logger.verbose('creating temp dir: ' + tempDir);
fs.mkdirSync(tempDir, { recursive: true });
}
try {
} catch (error) {
this.logger.error(error);
}

View File

@ -5,7 +5,7 @@ import { chatwootSchema, instanceNameSchema } from '../../validate/validate.sche
import { RouterBroker } from '../abstract/abstract.router';
import { ChatwootDto } from '../dto/chatwoot.dto';
import { InstanceDto } from '../dto/instance.dto';
import { ChatwootService } from '../services/chatwoot.service';
// import { ChatwootService } from '../services/chatwoot.service';
import { chatwootController } from '../whatsapp.module';
import { HttpStatus } from './index.router';

View File

@ -5,7 +5,7 @@ import { instanceNameSchema, settingsSchema } from '../../validate/validate.sche
import { RouterBroker } from '../abstract/abstract.router';
import { InstanceDto } from '../dto/instance.dto';
import { SettingsDto } from '../dto/settings.dto';
import { SettingsService } from '../services/settings.service';
// import { SettingsService } from '../services/settings.service';
import { settingsController } from '../whatsapp.module';
import { HttpStatus } from './index.router';

View File

@ -1,19 +1,18 @@
import { InstanceDto } from '../dto/instance.dto';
import path from 'path';
import { ChatwootDto } from '../dto/chatwoot.dto';
import { WAMonitoringService } from './monitor.service';
import { Logger } from '../../config/logger.config';
import ChatwootClient from '@figuro/chatwoot-sdk';
import { createReadStream, readFileSync, unlinkSync, writeFileSync } from 'fs';
import axios from 'axios';
import FormData from 'form-data';
import { SendTextDto } from '../dto/sendMessage.dto';
import { createReadStream, readFileSync, unlinkSync, writeFileSync } from 'fs';
import mimeTypes from 'mime-types';
import { SendAudioDto } from '../dto/sendMessage.dto';
import { SendMediaDto } from '../dto/sendMessage.dto';
import { ROOT_DIR } from '../../config/path.config';
// import { type } from 'os';
import path from 'path';
import { ConfigService, HttpServer } from '../../config/env.config';
import { type } from 'os';
import { Logger } from '../../config/logger.config';
import { ROOT_DIR } from '../../config/path.config';
import { ChatwootDto } from '../dto/chatwoot.dto';
import { InstanceDto } from '../dto/instance.dto';
import { SendAudioDto, SendMediaDto, SendTextDto } from '../dto/sendMessage.dto';
import { WAMonitoringService } from './monitor.service';
export class ChatwootService {
private messageCacheFile: string;
@ -23,10 +22,7 @@ export class ChatwootService {
private provider: any;
constructor(
private readonly waMonitor: WAMonitoringService,
private readonly configService: ConfigService,
) {
constructor(private readonly waMonitor: WAMonitoringService, private readonly configService: ConfigService) {
this.messageCache = new Set();
}
@ -57,9 +53,7 @@ export class ChatwootService {
private async getProvider(instance: InstanceDto) {
this.logger.verbose('get provider to instance: ' + instance.instanceName);
try {
const provider = await this.waMonitor.waInstances[
instance.instanceName
].findChatwoot();
const provider = await this.waMonitor.waInstances[instance.instanceName].findChatwoot();
if (!provider) {
this.logger.warn('provider not found');
@ -172,9 +166,7 @@ export class ChatwootService {
});
this.logger.verbose('check duplicate inbox');
const checkDuplicate = findInbox.payload
.map((inbox) => inbox.name)
.includes(inboxName);
const checkDuplicate = findInbox.payload.map((inbox) => inbox.name).includes(inboxName);
let inboxId: number;
@ -214,13 +206,7 @@ export class ChatwootService {
this.logger.verbose('find contact in chatwoot and create if not exists');
const contact =
(await this.findContact(instance, '123456')) ||
((await this.createContact(
instance,
'123456',
inboxId,
false,
'EvolutionAPI',
)) as any);
((await this.createContact(instance, '123456', inboxId, false, 'EvolutionAPI')) as any);
if (!contact) {
this.logger.warn('contact not found');
@ -425,23 +411,18 @@ export class ChatwootService {
if (isGroup) {
this.logger.verbose('get group name');
const group = await this.waMonitor.waInstances[
instance.instanceName
].client.groupMetadata(chatId);
const group = await this.waMonitor.waInstances[instance.instanceName].client.groupMetadata(chatId);
nameContact = `${group.subject} (GROUP)`;
this.logger.verbose('find or create participant in chatwoot');
const picture_url = await this.waMonitor.waInstances[
instance.instanceName
].profilePicture(body.key.participant.split('@')[0]);
const findParticipant = await this.findContact(
instance,
const picture_url = await this.waMonitor.waInstances[instance.instanceName].profilePicture(
body.key.participant.split('@')[0],
);
const findParticipant = await this.findContact(instance, body.key.participant.split('@')[0]);
if (findParticipant) {
if (!findParticipant.name || findParticipant.name === chatId) {
await this.updateContact(instance, findParticipant.id, {
@ -463,9 +444,7 @@ export class ChatwootService {
this.logger.verbose('find or create contact in chatwoot');
const picture_url = await this.waMonitor.waInstances[
instance.instanceName
].profilePicture(chatId);
const picture_url = await this.waMonitor.waInstances[instance.instanceName].profilePicture(chatId);
const findContact = await this.findContact(instance, chatId);
@ -510,8 +489,7 @@ export class ChatwootService {
return null;
}
const contactId =
contact?.payload?.id || contact?.payload?.contact?.id || contact?.id;
const contactId = contact?.payload?.id || contact?.payload?.contact?.id || contact?.id;
if (!body.key.fromMe && contact.name === chatId && nameContact !== chatId) {
this.logger.verbose('update contact name in chatwoot');
@ -534,9 +512,7 @@ export class ChatwootService {
);
} else {
conversation = contactConversations.payload.find(
(conversation) =>
conversation.status !== 'resolved' &&
conversation.inbox_id == filterInbox.id,
(conversation) => conversation.status !== 'resolved' && conversation.inbox_id == filterInbox.id,
);
}
this.logger.verbose('return conversation if exists');
@ -595,9 +571,7 @@ export class ChatwootService {
}
this.logger.verbose('find inbox by name');
const findByName = inbox.payload.find(
(inbox) => inbox.name === instance.instanceName,
);
const findByName = inbox.payload.find((inbox) => inbox.name === instance.instanceName);
if (!findByName) {
this.logger.warn('inbox not found');
@ -699,8 +673,7 @@ export class ChatwootService {
this.logger.verbose('find conversation by contact id');
const conversation = findConversation.data.payload.find(
(conversation) =>
conversation?.meta?.sender?.id === contact.id && conversation.status === 'open',
(conversation) => conversation?.meta?.sender?.id === contact.id && conversation.status === 'open',
);
if (!conversation) {
@ -820,8 +793,7 @@ export class ChatwootService {
this.logger.verbose('find conversation by contact id');
const conversation = findConversation.data.payload.find(
(conversation) =>
conversation?.meta?.sender?.id === contact.id && conversation.status === 'open',
(conversation) => conversation?.meta?.sender?.id === contact.id && conversation.status === 'open',
);
if (!conversation) {
@ -871,12 +843,7 @@ export class ChatwootService {
}
}
public async sendAttachment(
waInstance: any,
number: string,
media: any,
caption?: string,
) {
public async sendAttachment(waInstance: any, number: string, media: any, caption?: string) {
this.logger.verbose('send attachment to instance: ' + waInstance.instanceName);
try {
@ -957,9 +924,7 @@ export class ChatwootService {
public async receiveWebhook(instance: InstanceDto, body: any) {
try {
this.logger.verbose(
'receive webhook to chatwoot instance: ' + instance.instanceName,
);
this.logger.verbose('receive webhook to chatwoot instance: ' + instance.instanceName);
const client = await this.clientCw(instance);
if (!client) {
@ -1008,11 +973,7 @@ export class ChatwootService {
if (!state) {
this.logger.verbose('state not found');
await this.createBotMessage(
instance,
`⚠️ ${body.inbox.name} instance not found.`,
'incoming',
);
await this.createBotMessage(instance, `⚠️ ${body.inbox.name} instance not found.`, 'incoming');
}
if (state) {
@ -1070,19 +1031,10 @@ export class ChatwootService {
}
}
if (
body.message_type === 'outgoing' &&
body?.conversation?.messages?.length &&
chatId !== '123456'
) {
if (body.message_type === 'outgoing' && body?.conversation?.messages?.length && chatId !== '123456') {
this.logger.verbose('check if is group');
this.messageCacheFile = path.join(
ROOT_DIR,
'store',
'chatwoot',
`${instance.instanceName}_cache.txt`,
);
this.messageCacheFile = path.join(ROOT_DIR, 'store', 'chatwoot', `${instance.instanceName}_cache.txt`);
this.logger.verbose('cache file path: ' + this.messageCacheFile);
this.messageCache = this.loadMessageCache();
@ -1103,9 +1055,7 @@ export class ChatwootService {
if (senderName === null || senderName === undefined) {
formatText = messageReceived;
} else {
formatText = this.provider.sign_msg
? `*${senderName}:*\n\n${messageReceived}`
: messageReceived;
formatText = this.provider.sign_msg ? `*${senderName}:*\n\n${messageReceived}` : messageReceived;
}
for (const message of body.conversation.messages) {
@ -1119,12 +1069,7 @@ export class ChatwootService {
formatText = null;
}
await this.sendAttachment(
waInstance,
chatId,
attachment.data_url,
formatText,
);
await this.sendAttachment(waInstance, chatId, attachment.data_url, formatText);
}
} else {
this.logger.verbose('message is text');
@ -1203,8 +1148,7 @@ export class ChatwootService {
messageContextInfo: msg.messageContextInfo?.stanzaId,
stickerMessage: undefined,
documentMessage: msg.documentMessage?.caption,
documentWithCaptionMessage:
msg.documentWithCaptionMessage?.message?.documentMessage?.caption,
documentWithCaptionMessage: msg.documentWithCaptionMessage?.message?.documentMessage?.caption,
audioMessage: msg.audioMessage?.caption,
contactMessage: msg.contactMessage?.vcard,
contactsArrayMessage: msg.contactsArrayMessage,
@ -1405,12 +1349,7 @@ export class ChatwootService {
}
this.logger.verbose('send data to chatwoot');
const send = await this.sendData(
getConversion,
fileName,
messageType,
content,
);
const send = await this.sendData(getConversion, fileName, messageType, content);
if (!send) {
this.logger.warn('message not sent');
@ -1436,12 +1375,7 @@ export class ChatwootService {
this.logger.verbose('message is not group');
this.logger.verbose('send data to chatwoot');
const send = await this.sendData(
getConversion,
fileName,
messageType,
bodyMessage,
);
const send = await this.sendData(getConversion, fileName, messageType, bodyMessage);
if (!send) {
this.logger.warn('message not sent');
@ -1482,12 +1416,7 @@ export class ChatwootService {
}
this.logger.verbose('send data to chatwoot');
const send = await this.createMessage(
instance,
getConversion,
content,
messageType,
);
const send = await this.createMessage(instance, getConversion, content, messageType);
if (!send) {
this.logger.warn('message not sent');
@ -1513,12 +1442,7 @@ export class ChatwootService {
this.logger.verbose('message is not group');
this.logger.verbose('send data to chatwoot');
const send = await this.createMessage(
instance,
getConversion,
bodyMessage,
messageType,
);
const send = await this.createMessage(instance, getConversion, bodyMessage, messageType);
if (!send) {
this.logger.warn('message not sent');
@ -1580,16 +1504,9 @@ export class ChatwootService {
return await this.createBotMessage(instance, erroQRcode, 'incoming');
} else {
this.logger.verbose('qrcode success');
const fileData = Buffer.from(
body?.qrcode.base64.replace('data:image/png;base64,', ''),
'base64',
);
const fileData = Buffer.from(body?.qrcode.base64.replace('data:image/png;base64,', ''), 'base64');
const fileName = `${path.join(
waInstance?.storePath,
'temp',
`${`${instance}.png`}`,
)}`;
const fileName = `${path.join(waInstance?.storePath, 'temp', `${`${instance}.png`}`)}`;
this.logger.verbose('temp file name: ' + fileName);
@ -1597,12 +1514,7 @@ export class ChatwootService {
writeFileSync(fileName, fileData, 'utf8');
this.logger.verbose('send qrcode to chatwoot');
await this.createBotQr(
instance,
'QRCode successfully generated!',
'incoming',
fileName,
);
await this.createBotQr(instance, 'QRCode successfully generated!', 'incoming', fileName);
let msgQrCode = `⚡️ QRCode successfully generated!\n\nScan this QR code within the next 40 seconds.`;
@ -1649,6 +1561,7 @@ export class ChatwootService {
requestData['number'] = number;
}
// eslint-disable-next-line
const config = {
method: 'post',
maxBodyLength: Infinity,

View File

@ -2,7 +2,6 @@ import { execSync } from 'child_process';
import EventEmitter2 from 'eventemitter2';
import { opendirSync, readdirSync, rmSync } from 'fs';
import { Db } from 'mongodb';
import mongoose from 'mongoose';
import { join } from 'path';
import { Auth, ConfigService, Database, DelInstance, HttpServer, Redis } from '../../config/env.config';

View File

@ -1,9 +1,10 @@
import ffmpegPath from '@ffmpeg-installer/ffmpeg';
import { Boom } from '@hapi/boom';
import makeWASocket, {
AnyMessageContent,
BufferedEventData,
BufferJSON,
CacheStore,
makeCacheableSignalKeyStore,
Chat,
ConnectionState,
Contact,
@ -12,11 +13,13 @@ import makeWASocket, {
downloadMediaMessage,
fetchLatestBaileysVersion,
generateWAMessageFromContent,
getAggregateVotesInPollMessage,
getContentType,
getDevice,
GroupMetadata,
isJidGroup,
isJidUser,
makeCacheableSignalKeyStore,
MessageUpsertType,
MiscMessageGenerationOptions,
ParticipantAction,
@ -29,8 +32,23 @@ import makeWASocket, {
WAMessage,
WAMessageUpdate,
WASocket,
getAggregateVotesInPollMessage,
} from '@whiskeysockets/baileys';
import axios from 'axios';
import { exec, execSync } from 'child_process';
import { arrayUnique, isBase64, isURL } from 'class-validator';
import EventEmitter2 from 'eventemitter2';
import fs, { existsSync, readFileSync } from 'fs';
import Long from 'long';
import NodeCache from 'node-cache';
import { getMIMEType } from 'node-mime-types';
import { release } from 'os';
import { join } from 'path';
import P from 'pino';
import qrcode, { QRCodeToDataURLOptions } from 'qrcode';
import qrcodeTerminal from 'qrcode-terminal';
import sharp from 'sharp';
import { v4 } from 'uuid';
import {
Auth,
CleanStoreConf,
@ -38,31 +56,41 @@ import {
ConfigSessionPhone,
Database,
HttpServer,
Log,
QrCode,
Redis,
Webhook,
} from '../../config/env.config';
import fs from 'fs';
import { Logger } from '../../config/logger.config';
import { INSTANCE_DIR, ROOT_DIR } from '../../config/path.config';
import { existsSync, readFileSync } from 'fs';
import { join } from 'path';
import axios from 'axios';
import { v4 } from 'uuid';
import qrcode, { QRCodeToDataURLOptions } from 'qrcode';
import qrcodeTerminal from 'qrcode-terminal';
import { Events, TypeMediaMessage, wa, MessageSubtype } from '../types/wa.types';
import { Boom } from '@hapi/boom';
import EventEmitter2 from 'eventemitter2';
import { release } from 'os';
import P from 'pino';
import { execSync, exec } from 'child_process';
import ffmpegPath from '@ffmpeg-installer/ffmpeg';
import { RepositoryBroker } from '../repository/repository.manager';
import { MessageRaw, MessageUpdateRaw } from '../models/message.model';
import { ContactRaw } from '../models/contact.model';
import { ChatRaw } from '../models/chat.model';
import { getMIMEType } from 'node-mime-types';
import { dbserver } from '../../db/db.connect';
import { RedisCache } from '../../db/redis.client';
import { BadRequestException, InternalServerErrorException, NotFoundException } from '../../exceptions';
import { useMultiFileAuthStateDb } from '../../utils/use-multi-file-auth-state-db';
import { useMultiFileAuthStateRedisDb } from '../../utils/use-multi-file-auth-state-redis-db';
import {
ArchiveChatDto,
DeleteMessage,
getBase64FromMediaMessageDto,
NumberBusiness,
OnWhatsAppDto,
PrivacySettingDto,
ReadMessageDto,
WhatsAppNumberDto,
} from '../dto/chat.dto';
import {
CreateGroupDto,
GetParticipant,
GroupDescriptionDto,
GroupInvite,
GroupJid,
GroupPictureDto,
GroupSendInvite,
GroupSubjectDto,
GroupToggleEphemeralDto,
GroupUpdateParticipantDto,
GroupUpdateSettingDto,
} from '../dto/group.dto';
import {
ContactMessage,
MediaMessage,
@ -73,58 +101,26 @@ import {
SendListDto,
SendLocationDto,
SendMediaDto,
SendReactionDto,
SendTextDto,
SendPollDto,
SendStickerDto,
SendReactionDto,
SendStatusDto,
SendStickerDto,
SendTextDto,
StatusMessage,
} from '../dto/sendMessage.dto';
import { arrayUnique, isBase64, isURL } from 'class-validator';
import {
ArchiveChatDto,
DeleteMessage,
NumberBusiness,
OnWhatsAppDto,
PrivacySettingDto,
ReadMessageDto,
WhatsAppNumberDto,
getBase64FromMediaMessageDto,
} from '../dto/chat.dto';
import { MessageQuery } from '../repository/message.repository';
import { ContactQuery } from '../repository/contact.repository';
import {
BadRequestException,
InternalServerErrorException,
NotFoundException,
} from '../../exceptions';
import {
CreateGroupDto,
GroupInvite,
GroupJid,
GroupPictureDto,
GroupUpdateParticipantDto,
GroupUpdateSettingDto,
GroupToggleEphemeralDto,
GroupSubjectDto,
GroupDescriptionDto,
GroupSendInvite,
GetParticipant,
} from '../dto/group.dto';
import { MessageUpQuery } from '../repository/messageUp.repository';
import { useMultiFileAuthStateDb } from '../../utils/use-multi-file-auth-state-db';
import Long from 'long';
import { WebhookRaw } from '../models/webhook.model';
import { ChatwootRaw } from '../models/chatwoot.model';
import { SettingsRaw } from '../models';
import { dbserver } from '../../db/db.connect';
import NodeCache from 'node-cache';
import { useMultiFileAuthStateRedisDb } from '../../utils/use-multi-file-auth-state-redis-db';
import sharp from 'sharp';
import { RedisCache } from '../../db/redis.client';
import { Log } from '../../config/env.config';
import { ChatwootService } from './chatwoot.service';
import { ChatRaw } from '../models/chat.model';
import { ChatwootRaw } from '../models/chatwoot.model';
import { ContactRaw } from '../models/contact.model';
import { MessageRaw, MessageUpdateRaw } from '../models/message.model';
import { WebhookRaw } from '../models/webhook.model';
import { ContactQuery } from '../repository/contact.repository';
import { MessageQuery } from '../repository/message.repository';
import { MessageUpQuery } from '../repository/messageUp.repository';
import { RepositoryBroker } from '../repository/repository.manager';
import { Events, MessageSubtype, TypeMediaMessage, wa } from '../types/wa.types';
import { waMonitor } from '../whatsapp.module';
import { ChatwootService } from './chatwoot.service';
export class WAStartupService {
constructor(
@ -201,10 +197,7 @@ export class WAStartupService {
this.logger.verbose('Database enabled, trying to get from database');
const collection = dbserver
.getClient()
.db(
this.configService.get<Database>('DATABASE').CONNECTION.DB_PREFIX_NAME +
'-instances',
)
.db(this.configService.get<Database>('DATABASE').CONNECTION.DB_PREFIX_NAME + '-instances')
.collection(this.instanceName);
const data = await collection.findOne({ _id: 'creds' });
if (data) {
@ -316,14 +309,10 @@ export class WAStartupService {
this.logger.verbose(`Chatwoot number: ${this.localChatwoot.number}`);
this.localChatwoot.reopen_conversation = data?.reopen_conversation;
this.logger.verbose(
`Chatwoot reopen conversation: ${this.localChatwoot.reopen_conversation}`,
);
this.logger.verbose(`Chatwoot reopen conversation: ${this.localChatwoot.reopen_conversation}`);
this.localChatwoot.conversation_pending = data?.conversation_pending;
this.logger.verbose(
`Chatwoot conversation pending: ${this.localChatwoot.conversation_pending}`,
);
this.logger.verbose(`Chatwoot conversation pending: ${this.localChatwoot.conversation_pending}`);
this.logger.verbose('Chatwoot loaded');
}
@ -424,11 +413,10 @@ export class WAStartupService {
const webhookGlobal = this.configService.get<Webhook>('WEBHOOK');
const webhookLocal = this.localWebhook.events;
const serverUrl = this.configService.get<HttpServer>('SERVER').URL;
const we = event.replace(/[\.-]/gm, '_').toUpperCase();
const we = event.replace(/[.-]/gm, '_').toUpperCase();
const transformedWe = we.replace(/_/gm, '-').toLowerCase();
const expose =
this.configService.get<Auth>('AUTHENTICATION').EXPOSE_IN_FETCH_INSTANCES;
const expose = this.configService.get<Auth>('AUTHENTICATION').EXPOSE_IN_FETCH_INSTANCES;
const tokenStore = await this.repository.auth.find(this.instanceName);
const instanceApikey = tokenStore?.apikey || 'Apikey not found';
@ -437,7 +425,7 @@ export class WAStartupService {
if (local) {
if (Array.isArray(webhookLocal) && webhookLocal.includes(we)) {
this.logger.verbose('Sending data to webhook local');
let baseURL;
let baseURL: string;
if (this.localWebhook.webhook_by_events) {
baseURL = `${this.localWebhook.url}/${transformedWe}`;
@ -566,11 +554,7 @@ export class WAStartupService {
}
}
private async connectionUpdate({
qr,
connection,
lastDisconnect,
}: Partial<ConnectionState>) {
private async connectionUpdate({ qr, connection, lastDisconnect }: Partial<ConnectionState>) {
this.logger.verbose('Connection update');
if (qr) {
this.logger.verbose('QR code found');
@ -637,9 +621,7 @@ export class WAStartupService {
if (this.phoneNumber) {
await delay(2000);
this.instance.qrcode.pairingCode = await this.client.requestPairingCode(
this.phoneNumber,
);
this.instance.qrcode.pairingCode = await this.client.requestPairingCode(this.phoneNumber);
} else {
this.instance.qrcode.pairingCode = null;
}
@ -704,8 +686,7 @@ export class WAStartupService {
if (connection === 'close') {
this.logger.verbose('Connection closed');
const shouldReconnect =
(lastDisconnect.error as Boom)?.output?.statusCode !== DisconnectReason.loggedOut;
const shouldReconnect = (lastDisconnect.error as Boom)?.output?.statusCode !== DisconnectReason.loggedOut;
if (shouldReconnect) {
this.logger.verbose('Reconnecting to whatsapp');
await this.connectToWhatsapp();
@ -739,9 +720,7 @@ export class WAStartupService {
if (connection === 'open') {
this.logger.verbose('Connection opened');
this.instance.wuid = this.client.user.id.replace(/:\d+/, '');
this.instance.profilePictureUrl = (
await this.profilePicture(this.instance.wuid)
).profilePictureUrl;
this.instance.profilePictureUrl = (await this.profilePicture(this.instance.wuid)).profilePictureUrl;
this.logger.info(
`
@ -774,8 +753,7 @@ export class WAStartupService {
}
if (webMessageInfo[0].message?.pollCreationMessage) {
this.logger.verbose('Returning poll message');
const messageSecretBase64 =
webMessageInfo[0].message?.messageContextInfo?.messageSecret;
const messageSecretBase64 = webMessageInfo[0].message?.messageContextInfo?.messageSecret;
if (typeof messageSecretBase64 === 'string') {
const messageSecret = Buffer.from(messageSecretBase64, 'base64');
@ -824,7 +802,9 @@ export class WAStartupService {
);
}
}
} catch (error) {}
} catch (error) {
this.logger.error(error);
}
}, (cleanStore?.CLEANING_INTERVAL ?? 3600) * 1000);
}
}
@ -867,10 +847,7 @@ export class WAStartupService {
const socketConfig: UserFacingSocketConfig = {
auth: {
creds: this.instance.authState.state.creds,
keys: makeCacheableSignalKeyStore(
this.instance.authState.state.keys,
P({ level: 'error' }),
),
keys: makeCacheableSignalKeyStore(this.instance.authState.state.keys, P({ level: 'error' })),
},
logger: P({ level: this.logBaileys }),
printQRInTerminal: false,
@ -882,18 +859,13 @@ export class WAStartupService {
defaultQueryTimeoutMs: undefined,
emitOwnEvents: false,
msgRetryCounterCache: this.msgRetryCounterCache,
getMessage: async (key) =>
(await this.getMessage(key)) as Promise<proto.IMessage>,
getMessage: async (key) => (await this.getMessage(key)) as Promise<proto.IMessage>,
generateHighQualityLinkPreview: true,
syncFullHistory: true,
userDevicesCache: this.userDevicesCache,
transactionOpts: { maxCommitRetries: 1, delayBetweenTriesMs: 10 },
patchMessageBeforeSending: (message) => {
const requiresPatch = !!(
message.buttonsMessage ||
message.listMessage ||
message.templateMessage
);
const requiresPatch = !!(message.buttonsMessage || message.listMessage || message.templateMessage);
if (requiresPatch) {
message = {
viewOnceMessageV2: {
@ -956,11 +928,7 @@ export class WAStartupService {
await this.sendDataWebhook(Events.CHATS_UPSERT, chatsRaw);
this.logger.verbose('Inserting chats in database');
await this.repository.chat.insert(
chatsRaw,
this.instance.name,
database.SAVE_DATA.CHATS,
);
await this.repository.chat.insert(chatsRaw, this.instance.name, database.SAVE_DATA.CHATS);
},
'chats.update': async (
@ -1025,11 +993,7 @@ export class WAStartupService {
await this.sendDataWebhook(Events.CONTACTS_UPSERT, contactsRaw);
this.logger.verbose('Inserting contacts in database');
await this.repository.contact.insert(
contactsRaw,
this.instance.name,
database.SAVE_DATA.CONTACTS,
);
await this.repository.contact.insert(contactsRaw, this.instance.name, database.SAVE_DATA.CONTACTS);
},
'contacts.update': async (contacts: Partial<Contact>[], database: Database) => {
@ -1050,11 +1014,7 @@ export class WAStartupService {
await this.sendDataWebhook(Events.CONTACTS_UPDATE, contactsRaw);
this.logger.verbose('Updating contacts in database');
await this.repository.contact.update(
contactsRaw,
this.instance.name,
database.SAVE_DATA.CONTACTS,
);
await this.repository.contact.update(contactsRaw, this.instance.name, database.SAVE_DATA.CONTACTS);
},
};
@ -1087,11 +1047,7 @@ export class WAStartupService {
await this.sendDataWebhook(Events.CHATS_SET, chatsRaw);
this.logger.verbose('Inserting chats in database');
await this.repository.chat.insert(
chatsRaw,
this.instance.name,
database.SAVE_DATA.CHATS,
);
await this.repository.chat.insert(chatsRaw, this.instance.name, database.SAVE_DATA.CHATS);
}
const messagesRaw: MessageRaw[] = [];
@ -1102,11 +1058,7 @@ export class WAStartupService {
if (!m.message) {
continue;
}
if (
messagesRepository.find(
(mr) => mr.owner === this.instance.name && mr.key.id === m.key.id,
)
) {
if (messagesRepository.find((mr) => mr.owner === this.instance.name && mr.key.id === m.key.id)) {
continue;
}
@ -1145,11 +1097,7 @@ export class WAStartupService {
this.logger.verbose('Event received: messages.upsert');
const received = messages[0];
if (
type !== 'notify' ||
received.message?.protocolMessage ||
received.message?.pollUpdateMessage
) {
if (type !== 'notify' || received.message?.protocolMessage || received.message?.pollUpdateMessage) {
this.logger.verbose('message rejected');
return;
}
@ -1195,11 +1143,7 @@ export class WAStartupService {
}
this.logger.verbose('Inserting message in database');
await this.repository.message.insert(
[messageRaw],
this.instance.name,
database.SAVE_DATA.NEW_MESSAGE,
);
await this.repository.message.insert([messageRaw], this.instance.name, database.SAVE_DATA.NEW_MESSAGE);
this.logger.verbose('Verifying contact from message');
const contact = await this.repository.contact.find({
@ -1209,8 +1153,7 @@ export class WAStartupService {
const contactRaw: ContactRaw = {
id: received.key.remoteJid,
pushName: received.pushName,
profilePictureUrl: (await this.profilePicture(received.key.remoteJid))
.profilePictureUrl,
profilePictureUrl: (await this.profilePicture(received.key.remoteJid)).profilePictureUrl,
owner: this.instance.name,
};
@ -1224,8 +1167,7 @@ export class WAStartupService {
const contactRaw: ContactRaw = {
id: received.key.remoteJid,
pushName: contact[0].pushName,
profilePictureUrl: (await this.profilePicture(received.key.remoteJid))
.profilePictureUrl,
profilePictureUrl: (await this.profilePicture(received.key.remoteJid)).profilePictureUrl,
owner: this.instance.name,
};
@ -1241,11 +1183,7 @@ export class WAStartupService {
}
this.logger.verbose('Updating contact in database');
await this.repository.contact.update(
[contactRaw],
this.instance.name,
database.SAVE_DATA.CONTACTS,
);
await this.repository.contact.update([contactRaw], this.instance.name, database.SAVE_DATA.CONTACTS);
return;
}
@ -1255,18 +1193,10 @@ export class WAStartupService {
await this.sendDataWebhook(Events.CONTACTS_UPSERT, contactRaw);
this.logger.verbose('Inserting contact in database');
await this.repository.contact.insert(
[contactRaw],
this.instance.name,
database.SAVE_DATA.CONTACTS,
);
await this.repository.contact.insert([contactRaw], this.instance.name, database.SAVE_DATA.CONTACTS);
},
'messages.update': async (
args: WAMessageUpdate[],
database: Database,
settings: SettingsRaw,
) => {
'messages.update': async (args: WAMessageUpdate[], database: Database, settings: SettingsRaw) => {
this.logger.verbose('Event received: messages.update');
const status: Record<number, wa.StatusMessage> = {
0: 'ERROR',
@ -1555,7 +1485,7 @@ export class WAStartupService {
.replace(/\+/g, '')
.replace(/\(/g, '')
.replace(/\)/g, '')
.split(/\:/)[0]
.split(':')[0]
.split('@')[0];
if (number.includes('-') && number.length >= 24) {
@ -1620,7 +1550,6 @@ export class WAStartupService {
this.logger.verbose('Getting profile with jid: ' + jid);
try {
this.logger.verbose('Getting profile info');
const info = await waMonitor.instanceInfo(instanceName);
const business = await this.fetchBusinessProfile(jid);
if (number) {
@ -1667,11 +1596,7 @@ export class WAStartupService {
}
}
private async sendMessageWithTyping<T = proto.IMessage>(
number: string,
message: T,
options?: Options,
) {
private async sendMessageWithTyping<T = proto.IMessage>(number: string, message: T, options?: Options) {
this.logger.verbose('Sending message with typing');
const numberWA = await this.whatsappNumber({ numbers: [number] });
@ -1691,9 +1616,7 @@ export class WAStartupService {
this.logger.verbose('Subscribing to presence');
await this.client.sendPresenceUpdate(options?.presence ?? 'composing', sender);
this.logger.verbose(
'Sending presence update: ' + options?.presence ?? 'composing',
);
this.logger.verbose('Sending presence update: ' + options?.presence ?? 'composing');
await delay(options.delay);
this.logger.verbose('Set delay: ' + options.delay);
@ -1709,9 +1632,7 @@ export class WAStartupService {
if (options?.quoted) {
const m = options?.quoted;
const msg = m?.message
? m
: ((await this.getMessage(m.key, true)) as proto.IWebMessageInfo);
const msg = m?.message ? m : ((await this.getMessage(m.key, true)) as proto.IWebMessageInfo);
if (!msg) {
throw 'Message not found';
@ -1912,9 +1833,7 @@ export class WAStartupService {
}
this.logger.verbose('Getting contacts with push name');
status.statusJidList = contacts
.filter((contact) => contact.pushName)
.map((contact) => contact.id);
status.statusJidList = contacts.filter((contact) => contact.pushName).map((contact) => contact.id);
this.logger.verbose(status.statusJidList);
}
@ -2031,9 +1950,7 @@ export class WAStartupService {
this.logger.verbose('Media type: ' + mediaType);
if (mediaMessage.mediatype === 'document' && !mediaMessage.fileName) {
this.logger.verbose(
'If media type is document and file name is not defined then',
);
this.logger.verbose('If media type is document and file name is not defined then');
const regex = new RegExp(/.*\/(.+?)\./);
const arrayMatch = regex.exec(mediaMessage.media);
mediaMessage.fileName = arrayMatch[1];
@ -2146,11 +2063,7 @@ export class WAStartupService {
this.logger.verbose('Sending media message');
const generate = await this.prepareMediaMessage(data.mediaMessage);
return await this.sendMessageWithTyping(
data.number,
{ ...generate.message },
data?.options,
);
return await this.sendMessageWithTyping(data.number, { ...generate.message }, data?.options);
}
private async processAudio(audio: string, number: string) {
@ -2195,9 +2108,7 @@ export class WAStartupService {
this.logger.verbose('Converting audio to mp4');
return new Promise((resolve, reject) => {
exec(
`${ffmpegPath.path} -i ${tempAudioPath} -vn -ab 128k -ar 44100 -f ipod ${outputAudio} -y`,
(error, _stdout, _stderr) => {
exec(`${ffmpegPath.path} -i ${tempAudioPath} -vn -ab 128k -ar 44100 -f ipod ${outputAudio} -y`, (error) => {
fs.unlinkSync(tempAudioPath);
this.logger.verbose('Temp audio deleted');
@ -2205,8 +2116,7 @@ export class WAStartupService {
this.logger.verbose('Audio converted to mp4');
resolve(outputAudio);
},
);
});
});
}
@ -2272,10 +2182,7 @@ export class WAStartupService {
};
if (!arrayUnique(btnItems.text) || !arrayUnique(btnItems.ids)) {
throw new BadRequestException(
'Button texts cannot be repeated',
'Button IDs cannot be repeated.',
);
throw new BadRequestException('Button texts cannot be repeated', 'Button IDs cannot be repeated.');
}
return await this.sendMessageWithTyping(
@ -2342,11 +2249,7 @@ export class WAStartupService {
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) {
this.logger.verbose('Organization defined');
@ -2369,9 +2272,7 @@ export class WAStartupService {
}
result +=
`item1.TEL;waid=${contact.wuid}:${contact.phoneNumber}\n` +
'item1.X-ABLabel:Celular\n' +
'END:VCARD';
`item1.TEL;waid=${contact.wuid}:${contact.phoneNumber}\n` + 'item1.X-ABLabel:Celular\n' + 'END:VCARD';
this.logger.verbose('Vcard created');
return result;
@ -2461,8 +2362,7 @@ export class WAStartupService {
public async archiveChat(data: ArchiveChatDto) {
this.logger.verbose('Archiving chat');
try {
data.lastMessage.messageTimestamp =
data.lastMessage?.messageTimestamp ?? Date.now();
data.lastMessage.messageTimestamp = data.lastMessage?.messageTimestamp ?? Date.now();
await this.client.chatModify(
{
archive: data.archive,
@ -2478,10 +2378,7 @@ export class WAStartupService {
} catch (error) {
throw new InternalServerErrorException({
archived: false,
message: [
'An error occurred while archiving the chat. Open a calling.',
error.toString(),
],
message: ['An error occurred while archiving the chat. Open a calling.', error.toString()],
});
}
}
@ -2491,10 +2388,7 @@ export class WAStartupService {
try {
return await this.client.sendMessage(del.remoteJid, { delete: del });
} catch (error) {
throw new InternalServerErrorException(
'Error while deleting message for everyone',
error?.toString(),
);
throw new InternalServerErrorException('Error while deleting message for everyone', error?.toString());
}
}
@ -2504,9 +2398,7 @@ export class WAStartupService {
const m = data?.message;
const convertToMp4 = data?.convertToMp4 ?? false;
const msg = m?.message
? m
: ((await this.getMessage(m.key, true)) as proto.IWebMessageInfo);
const msg = m?.message ? m : ((await this.getMessage(m.key, true)) as proto.IWebMessageInfo);
if (!msg) {
throw 'Message not found';
@ -2696,10 +2588,7 @@ export class WAStartupService {
},
};
} catch (error) {
throw new InternalServerErrorException(
'Error updating privacy settings',
error.toString(),
);
throw new InternalServerErrorException('Error updating privacy settings', error.toString());
}
}
@ -2727,10 +2616,7 @@ export class WAStartupService {
...profile,
};
} catch (error) {
throw new InternalServerErrorException(
'Error updating profile name',
error.toString(),
);
throw new InternalServerErrorException('Error updating profile name', error.toString());
}
}
@ -2741,10 +2627,7 @@ export class WAStartupService {
return { update: 'success' };
} catch (error) {
throw new InternalServerErrorException(
'Error updating profile name',
error.toString(),
);
throw new InternalServerErrorException('Error updating profile name', error.toString());
}
}
@ -2755,10 +2638,7 @@ export class WAStartupService {
return { update: 'success' };
} catch (error) {
throw new InternalServerErrorException(
'Error updating profile status',
error.toString(),
);
throw new InternalServerErrorException('Error updating profile status', error.toString());
}
}
@ -2787,10 +2667,7 @@ export class WAStartupService {
return { update: 'success' };
} catch (error) {
throw new InternalServerErrorException(
'Error updating profile picture',
error.toString(),
);
throw new InternalServerErrorException('Error updating profile picture', error.toString());
}
}
@ -2801,10 +2678,7 @@ export class WAStartupService {
return { update: 'success' };
} catch (error) {
throw new InternalServerErrorException(
'Error removing profile picture',
error.toString(),
);
throw new InternalServerErrorException('Error removing profile picture', error.toString());
}
}
@ -2865,10 +2739,7 @@ export class WAStartupService {
return { update: 'success' };
} catch (error) {
throw new InternalServerErrorException(
'Error update group picture',
error.toString(),
);
throw new InternalServerErrorException('Error update group picture', error.toString());
}
}
@ -2879,10 +2750,7 @@ export class WAStartupService {
return { update: 'success' };
} catch (error) {
throw new InternalServerErrorException(
'Error updating group subject',
error.toString(),
);
throw new InternalServerErrorException('Error updating group subject', error.toString());
}
}
@ -2893,10 +2761,7 @@ export class WAStartupService {
return { update: 'success' };
} catch (error) {
throw new InternalServerErrorException(
'Error updating group description',
error.toString(),
);
throw new InternalServerErrorException('Error updating group description', error.toString());
}
}
@ -3032,10 +2897,7 @@ export class WAStartupService {
public async updateGSetting(update: GroupUpdateSettingDto) {
this.logger.verbose('Updating setting for group: ' + update.groupJid);
try {
const updateSetting = await this.client.groupSettingUpdate(
update.groupJid,
update.action,
);
const updateSetting = await this.client.groupSettingUpdate(update.groupJid, update.action);
return { updateSetting: updateSetting };
} catch (error) {
throw new BadRequestException('Error updating setting', error.toString());
@ -3045,10 +2907,7 @@ export class WAStartupService {
public async toggleEphemeral(update: GroupToggleEphemeralDto) {
this.logger.verbose('Toggling ephemeral for group: ' + update.groupJid);
try {
const toggleEphemeral = await this.client.groupToggleEphemeral(
update.groupJid,
update.expiration,
);
await this.client.groupToggleEphemeral(update.groupJid, update.expiration);
return { success: true };
} catch (error) {
throw new BadRequestException('Error updating setting', error.toString());

View File

@ -76,23 +76,10 @@ export declare namespace wa {
statusReason?: number;
};
export type StatusMessage =
| 'ERROR'
| 'PENDING'
| 'SERVER_ACK'
| 'DELIVERY_ACK'
| 'READ'
| 'DELETED'
| 'PLAYED';
export type StatusMessage = 'ERROR' | 'PENDING' | 'SERVER_ACK' | 'DELIVERY_ACK' | 'READ' | 'DELETED' | 'PLAYED';
}
export const TypeMediaMessage = [
'imageMessage',
'documentMessage',
'audioMessage',
'videoMessage',
'stickerMessage',
];
export const TypeMediaMessage = ['imageMessage', 'documentMessage', 'audioMessage', 'videoMessage', 'stickerMessage'];
export const MessageSubtype = [
'ephemeralMessage',

View File

@ -1,43 +1,40 @@
import { Auth, configService } from '../config/env.config';
import { Logger } from '../config/logger.config';
import { configService } from '../config/env.config';
import { eventEmitter } from '../config/event.config';
import { MessageRepository } from './repository/message.repository';
import { WAMonitoringService } from './services/monitor.service';
import { ChatRepository } from './repository/chat.repository';
import { ContactRepository } from './repository/contact.repository';
import { MessageUpRepository } from './repository/messageUp.repository';
import { Logger } from '../config/logger.config';
import { dbserver } from '../db/db.connect';
import { RedisCache } from '../db/redis.client';
import { ChatController } from './controllers/chat.controller';
import { ChatwootController } from './controllers/chatwoot.controller';
import { GroupController } from './controllers/group.controller';
import { InstanceController } from './controllers/instance.controller';
import { SendMessageController } from './controllers/sendMessage.controller';
import { AuthService } from './services/auth.service';
import { GroupController } from './controllers/group.controller';
import { SettingsController } from './controllers/settings.controller';
import { ViewsController } from './controllers/views.controller';
import { WebhookService } from './services/webhook.service';
import { WebhookController } from './controllers/webhook.controller';
import { ChatwootService } from './services/chatwoot.service';
import { ChatwootController } from './controllers/chatwoot.controller';
import { RepositoryBroker } from './repository/repository.manager';
import {
AuthModel,
ChatModel,
ChatwootModel,
ContactModel,
MessageModel,
MessageUpModel,
ChatwootModel,
WebhookModel,
SettingsModel,
WebhookModel,
} from './models';
import { dbserver } from '../db/db.connect';
import { WebhookRepository } from './repository/webhook.repository';
import { ChatwootRepository } from './repository/chatwoot.repository';
import { AuthRepository } from './repository/auth.repository';
import { WAStartupService } from './services/whatsapp.service';
import { delay } from '@whiskeysockets/baileys';
import { Events } from './types/wa.types';
import { RedisCache } from '../db/redis.client';
import { ChatRepository } from './repository/chat.repository';
import { ChatwootRepository } from './repository/chatwoot.repository';
import { ContactRepository } from './repository/contact.repository';
import { MessageRepository } from './repository/message.repository';
import { MessageUpRepository } from './repository/messageUp.repository';
import { RepositoryBroker } from './repository/repository.manager';
import { SettingsRepository } from './repository/settings.repository';
import { WebhookRepository } from './repository/webhook.repository';
import { AuthService } from './services/auth.service';
import { ChatwootService } from './services/chatwoot.service';
import { WAMonitoringService } from './services/monitor.service';
import { SettingsService } from './services/settings.service';
import { SettingsController } from './controllers/settings.controller';
import { WebhookService } from './services/webhook.service';
const logger = new Logger('WA MODULE');
@ -65,12 +62,7 @@ export const repository = new RepositoryBroker(
export const cache = new RedisCache();
export const waMonitor = new WAMonitoringService(
eventEmitter,
configService,
repository,
cache,
);
export const waMonitor = new WAMonitoringService(eventEmitter, configService, repository, cache);
const authService = new AuthService(configService, waMonitor, repository);