From 39178b534a39c50c31bc097ba2b897250ebf25d0 Mon Sep 17 00:00:00 2001 From: Francis Breit Date: Mon, 2 Oct 2023 11:05:03 -0300 Subject: [PATCH] Update whatsapp.service.ts --- src/whatsapp/services/whatsapp.service.ts | 104 +++++++++++++++++----- 1 file changed, 81 insertions(+), 23 deletions(-) diff --git a/src/whatsapp/services/whatsapp.service.ts b/src/whatsapp/services/whatsapp.service.ts index 1c48edae..fa516a0a 100644 --- a/src/whatsapp/services/whatsapp.service.ts +++ b/src/whatsapp/services/whatsapp.service.ts @@ -40,7 +40,6 @@ 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'; @@ -66,7 +65,7 @@ import { import { Logger } from '../../config/logger.config'; import { INSTANCE_DIR, ROOT_DIR } from '../../config/path.config'; import { BadRequestException, InternalServerErrorException, NotFoundException } from '../../exceptions'; -import { getAMQP } from '../../libs/amqp.server'; +import { getAMQP, removeQueues } from '../../libs/amqp.server'; import { dbserver } from '../../libs/db.connect'; import { RedisCache } from '../../libs/redis.client'; import { getIO } from '../../libs/socket.server'; @@ -495,6 +494,14 @@ export class WAStartupService { return data; } + public async removeRabbitmqQueues() { + this.logger.verbose('Removing rabbitmq'); + + if (this.localRabbitmq.enabled) { + removeQueues(this.instanceName, this.localRabbitmq.events); + } + } + private async loadTypebot() { this.logger.verbose('Loading typebot'); const data = await this.repository.typebot.find(this.instanceName); @@ -1240,6 +1247,74 @@ export class WAStartupService { } } + public async reloadConnection(): Promise { + try { + this.instance.authState = await this.defineAuthState(); + + const { version } = await fetchLatestBaileysVersion(); + const session = this.configService.get('CONFIG_SESSION_PHONE'); + const browser: WABrowserDescription = [session.CLIENT, session.NAME, release()]; + + let options; + + if (this.localProxy.enabled) { + this.logger.verbose('Proxy enabled'); + options = { + agent: new ProxyAgent(this.localProxy.proxy as any), + fetchAgent: new ProxyAgent(this.localProxy.proxy as any), + }; + } + + const socketConfig: UserFacingSocketConfig = { + ...options, + auth: { + creds: this.instance.authState.state.creds, + keys: makeCacheableSignalKeyStore(this.instance.authState.state.keys, P({ level: 'error' })), + }, + logger: P({ level: this.logBaileys }), + printQRInTerminal: false, + browser, + version, + markOnlineOnConnect: this.localSettings.always_online, + connectTimeoutMs: 60_000, + qrTimeout: 40_000, + defaultQueryTimeoutMs: undefined, + emitOwnEvents: false, + msgRetryCounterCache: this.msgRetryCounterCache, + getMessage: async (key) => (await this.getMessage(key)) as Promise, + generateHighQualityLinkPreview: true, + syncFullHistory: true, + userDevicesCache: this.userDevicesCache, + transactionOpts: { maxCommitRetries: 1, delayBetweenTriesMs: 10 }, + patchMessageBeforeSending: (message) => { + const requiresPatch = !!(message.buttonsMessage || message.listMessage || message.templateMessage); + if (requiresPatch) { + message = { + viewOnceMessageV2: { + message: { + messageContextInfo: { + deviceListMetadataVersion: 2, + deviceListMetadata: {}, + }, + ...message, + }, + }, + }; + } + + return message; + }, + }; + + this.client = makeWASocket(socketConfig); + + return this.client; + } catch (error) { + this.logger.error(error); + throw new InternalServerErrorException(error?.toString()); + } + } + private readonly chatHandle = { 'chats.upsert': async (chats: Chat[], database: Database) => { this.logger.verbose('Event received: chats.upsert'); @@ -2308,36 +2383,18 @@ export class WAStartupService { mediaMessage.fileName = arrayMatch[1]; this.logger.verbose('File name: ' + mediaMessage.fileName); } + let mimetype: string; if (mediaMessage.mediatype === 'image' && !mediaMessage.fileName) { - mediaMessage.fileName = 'image.png'; + mediaMessage.fileName = 'image.png'; + mimetype = 'image/png'; } if (mediaMessage.mediatype === 'video' && !mediaMessage.fileName) { mediaMessage.fileName = 'video.mp4'; - } - - - let mimetype: string; - - // novo critério para adotar mimetype quando nao está presente na url e no filename - inicio - if (isURL(mediaMessage.media) || mediaMessage.fileName) { - if (isURL(mediaMessage.media)) { - mimetype = getMIMEType(mediaMessage.media); - } else { - mimetype = getMIMEType(mediaMessage.fileName); - } - } else { - if (mediaMessage.mediatype === 'image') { - mimetype = 'image/png'; - } - if (mediaMessage.mediatype === 'video') { mimetype = 'video/mp4'; - } } - // novo critério para adotar mimetype quando nao está presente na url e no filename - fim - this.logger.verbose('Mimetype: ' + mimetype); prepareMedia[mediaType].caption = mediaMessage?.caption; @@ -2713,6 +2770,7 @@ export class WAStartupService { public async markMessageAsRead(data: ReadMessageDto) { this.logger.verbose('Marking message as read'); + try { const keys: proto.IMessageKey[] = []; data.read_messages.forEach((read) => {