Skip to content

Commit

Permalink
Refactor JID creation and fetch chats
Browse files Browse the repository at this point in the history
- Introduced a new utility function `createJid` to standardize JID creation across the application, replacing the previous method in `ChannelStartupService`.
- Updated multiple services to utilize the new `createJid` function for improved consistency and maintainability.
- Added a `cleanMessageData` method in `ChannelStartupService` to sanitize message objects before processing.
- Updated CHANGELOG to reflect the refactor on chat fetching logic and the introduction of the new JID utility.
  • Loading branch information
DavidsonGomes committed Jan 22, 2025
1 parent b0219e5 commit ab5eb80
Show file tree
Hide file tree
Showing 6 changed files with 262 additions and 176 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

* Correction of webhook global
* Fixed send audio with whatsapp cloud api
* Refactor on fetch chats

# 2.2.0 (2024-10-18 10:00)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { ChannelStartupService } from '@api/services/channel.service';
import { Events, wa } from '@api/types/wa.types';
import { Chatwoot, ConfigService, Openai } from '@config/env.config';
import { BadRequestException, InternalServerErrorException } from '@exceptions';
import { createJid } from '@utils/createJid';
import { status } from '@utils/renderStatus';
import { isURL } from 'class-validator';
import EventEmitter2 from 'eventemitter2';
Expand Down Expand Up @@ -57,7 +58,7 @@ export class EvolutionStartupService extends ChannelStartupService {
}

public async profilePicture(number: string) {
const jid = this.createJid(number);
const jid = createJid(number);

return {
wuid: jid,
Expand Down
13 changes: 6 additions & 7 deletions src/api/integrations/channel/meta/whatsapp.business.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import { ChannelStartupService } from '@api/services/channel.service';
import { Events, wa } from '@api/types/wa.types';
import { Chatwoot, ConfigService, Database, Openai, S3, WaBusiness } from '@config/env.config';
import { BadRequestException, InternalServerErrorException } from '@exceptions';
import { createJid } from '@utils/createJid';
import { status } from '@utils/renderStatus';
import axios from 'axios';
import { arrayUnique, isURL } from 'class-validator';
Expand Down Expand Up @@ -88,7 +89,7 @@ export class BusinessStartupService extends ChannelStartupService {
}

public async profilePicture(number: string) {
const jid = this.createJid(number);
const jid = createJid(number);

return {
wuid: jid,
Expand Down Expand Up @@ -132,9 +133,7 @@ export class BusinessStartupService extends ChannelStartupService {

this.eventHandler(content);

this.phoneNumber = this.createJid(
content.messages ? content.messages[0].from : content.statuses[0]?.recipient_id,
);
this.phoneNumber = createJid(content.messages ? content.messages[0].from : content.statuses[0]?.recipient_id);
} catch (error) {
this.logger.error(error);
throw new InternalServerErrorException(error?.toString());
Expand Down Expand Up @@ -231,7 +230,7 @@ export class BusinessStartupService extends ChannelStartupService {
}

if (!contact.phones[0]?.wa_id) {
contact.phones[0].wa_id = this.createJid(contact.phones[0].phone);
contact.phones[0].wa_id = createJid(contact.phones[0].phone);
}

result +=
Expand Down Expand Up @@ -915,7 +914,7 @@ export class BusinessStartupService extends ChannelStartupService {
}

const messageRaw: any = {
key: { fromMe: true, id: messageSent?.messages[0]?.id, remoteJid: this.createJid(number) },
key: { fromMe: true, id: messageSent?.messages[0]?.id, remoteJid: createJid(number) },
message: this.convertMessageToRaw(message, content),
messageType: this.renderMessageType(content.type),
messageTimestamp: (messageSent?.messages[0]?.timestamp as number) || Math.round(new Date().getTime() / 1000),
Expand Down Expand Up @@ -1274,7 +1273,7 @@ export class BusinessStartupService extends ChannelStartupService {
}

if (!contact.wuid) {
contact.wuid = this.createJid(contact.phoneNumber);
contact.wuid = createJid(contact.phoneNumber);
}

result += `item1.TEL;waid=${contact.wuid}:${contact.phoneNumber}\n` + 'item1.X-ABLabel:Celular\n' + 'END:VCARD';
Expand Down
75 changes: 42 additions & 33 deletions src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ import ffmpegPath from '@ffmpeg-installer/ffmpeg';
import { Boom } from '@hapi/boom';
import { createId as cuid } from '@paralleldrive/cuid2';
import { Instance } from '@prisma/client';
import { createJid } from '@utils/createJid';
import { makeProxyAgent } from '@utils/makeProxyAgent';
import { getOnWhatsappCache, saveOnWhatsappCache } from '@utils/onWhatsappCache';
import { status } from '@utils/renderStatus';
Expand Down Expand Up @@ -1323,17 +1324,21 @@ export class BaileysStartupService extends ChannelStartupService {

if (this.localWebhook.enabled) {
if (isMedia && this.localWebhook.webhookBase64) {
const buffer = await downloadMediaMessage(
{ key: received.key, message: received?.message },
'buffer',
{},
{
logger: P({ level: 'error' }) as any,
reuploadRequest: this.client.updateMediaMessage,
},
);
try {
const buffer = await downloadMediaMessage(
{ key: received.key, message: received?.message },
'buffer',
{},
{
logger: P({ level: 'error' }) as any,
reuploadRequest: this.client.updateMediaMessage,
},
);

messageRaw.message.base64 = buffer ? buffer.toString('base64') : undefined;
messageRaw.message.base64 = buffer ? buffer.toString('base64') : undefined;
} catch (error) {
this.logger.error(['Error converting media to base64', error?.message]);
}
}
}

Expand Down Expand Up @@ -1809,7 +1814,7 @@ export class BaileysStartupService extends ChannelStartupService {
}

public async profilePicture(number: string) {
const jid = this.createJid(number);
const jid = createJid(number);

try {
const profilePictureUrl = await this.client.profilePictureUrl(jid, 'image');
Expand All @@ -1827,7 +1832,7 @@ export class BaileysStartupService extends ChannelStartupService {
}

public async getStatus(number: string) {
const jid = this.createJid(number);
const jid = createJid(number);

try {
return {
Expand All @@ -1843,7 +1848,7 @@ export class BaileysStartupService extends ChannelStartupService {
}

public async fetchProfile(instanceName: string, number?: string) {
const jid = number ? this.createJid(number) : this.client?.user?.id;
const jid = number ? createJid(number) : this.client?.user?.id;

const onWhatsapp = (await this.whatsappNumber({ numbers: [jid] }))?.shift();

Expand Down Expand Up @@ -1899,7 +1904,7 @@ export class BaileysStartupService extends ChannelStartupService {
}

public async offerCall({ number, isVideo, callDuration }: OfferCallDto) {
const jid = this.createJid(number);
const jid = createJid(number);

try {
const call = await this.client.offerCall(jid, isVideo);
Expand Down Expand Up @@ -2170,7 +2175,7 @@ export class BaileysStartupService extends ChannelStartupService {
mentions = group.participants.map((participant) => participant.id);
} else if (options?.mentioned?.length) {
mentions = options.mentioned.map((mention) => {
const jid = this.createJid(mention);
const jid = createJid(mention);
if (isJidGroup(jid)) {
return null;
}
Expand Down Expand Up @@ -2292,17 +2297,21 @@ export class BaileysStartupService extends ChannelStartupService {

if (this.localWebhook.enabled) {
if (isMedia && this.localWebhook.webhookBase64) {
const buffer = await downloadMediaMessage(
{ key: messageRaw.key, message: messageRaw?.message },
'buffer',
{},
{
logger: P({ level: 'error' }) as any,
reuploadRequest: this.client.updateMediaMessage,
},
);
try {
const buffer = await downloadMediaMessage(
{ key: messageRaw.key, message: messageRaw?.message },
'buffer',
{},
{
logger: P({ level: 'error' }) as any,
reuploadRequest: this.client.updateMediaMessage,
},
);

messageRaw.message.base64 = buffer ? buffer.toString('base64') : undefined;
messageRaw.message.base64 = buffer ? buffer.toString('base64') : undefined;
} catch (error) {
this.logger.error(['Error converting media to base64', error?.message]);
}
}
}

Expand Down Expand Up @@ -3240,7 +3249,7 @@ export class BaileysStartupService extends ChannelStartupService {
}

if (!contact.wuid) {
contact.wuid = this.createJid(contact.phoneNumber);
contact.wuid = createJid(contact.phoneNumber);
}

result += `item1.TEL;waid=${contact.wuid}:${contact.phoneNumber}\n` + 'item1.X-ABLabel:Celular\n' + 'END:VCARD';
Expand Down Expand Up @@ -3290,7 +3299,7 @@ export class BaileysStartupService extends ChannelStartupService {
};

data.numbers.forEach((number) => {
const jid = this.createJid(number);
const jid = createJid(number);

if (isJidGroup(jid)) {
jids.groups.push({ number, jid });
Expand Down Expand Up @@ -3483,7 +3492,7 @@ export class BaileysStartupService extends ChannelStartupService {
archive: data.archive,
lastMessages: [last_message],
},
this.createJid(number),
createJid(number),
);

return {
Expand Down Expand Up @@ -3520,7 +3529,7 @@ export class BaileysStartupService extends ChannelStartupService {
markRead: false,
lastMessages: [last_message],
},
this.createJid(number),
createJid(number),
);

return {
Expand Down Expand Up @@ -3725,7 +3734,7 @@ export class BaileysStartupService extends ChannelStartupService {

public async fetchBusinessProfile(number: string): Promise<NumberBusiness> {
try {
const jid = number ? this.createJid(number) : this.instance.wuid;
const jid = number ? createJid(number) : this.instance.wuid;

const profile = await this.client.getBusinessProfile(jid);

Expand Down Expand Up @@ -3873,7 +3882,7 @@ export class BaileysStartupService extends ChannelStartupService {
}

public async updateMessage(data: UpdateMessageDto) {
const jid = this.createJid(data.number);
const jid = createJid(data.number);

const options = await this.formatUpdateMessage(data);

Expand Down Expand Up @@ -4163,7 +4172,7 @@ export class BaileysStartupService extends ChannelStartupService {

const inviteUrl = inviteCode.inviteUrl;

const numbers = id.numbers.map((number) => this.createJid(number));
const numbers = id.numbers.map((number) => createJid(number));
const description = id.description ?? '';

const msg = `${description}\n\n${inviteUrl}`;
Expand Down Expand Up @@ -4234,7 +4243,7 @@ export class BaileysStartupService extends ChannelStartupService {

public async updateGParticipant(update: GroupUpdateParticipantDto) {
try {
const participants = update.participants.map((p) => this.createJid(p));
const participants = update.participants.map((p) => createJid(p));
const updateParticipants = await this.client.groupParticipantsUpdate(
update.groupJid,
participants,
Expand Down
Loading

0 comments on commit ab5eb80

Please sign in to comment.