Skip to content

Commit

Permalink
feat: update Baileys library and add fake call feature
Browse files Browse the repository at this point in the history
Updated the Baileys library reference in package.json and refactored imports across multiple files to use the new library. Added a new feature to handle fake calls in sendMessage.controller.ts and related DTOs. This change improves the integration with the Baileys library and introduces the ability to simulate calls, enhancing the testing capabilities. Main files modified: package.json, instance.controller.ts, sendMessage.controller.ts, chat.dto.ts, instance.dto.ts, sendMessage.dto.ts, chatwoot.service.ts, chatwoot-import-helper.ts, sendMessage.router.ts, cache.service.ts, channel.service.ts, whatsapp.baileys.service.ts, whatsapp.business.service.ts, wa.types.ts, rediscache.ts, use-multi-file-auth-state-prisma.ts, use-multi-file-auth-state-provider-files.ts, use-multi-file-auth-state-redis-db.ts, message.schema.ts.
  • Loading branch information
DavidsonGomes committed Jun 14, 2024
1 parent 61d6ddf commit 7dfc09f
Show file tree
Hide file tree
Showing 19 changed files with 91 additions and 46 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,9 @@
"@hapi/boom": "^10.0.1",
"@prisma/client": "^5.15.0",
"@sentry/node": "^7.59.2",
"@whiskeysockets/baileys": "6.7.5",
"amqplib": "^0.10.3",
"axios": "^1.6.5",
"baileys": "github:bobslavtriev/Baileys",
"class-validator": "^0.14.1",
"compression": "^1.7.4",
"cors": "^2.8.5",
Expand Down
2 changes: 1 addition & 1 deletion src/api/controllers/instance.controller.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { JsonValue } from '@prisma/client/runtime/library';
import { delay } from '@whiskeysockets/baileys';
import { delay } from 'baileys';
import { isArray, isURL } from 'class-validator';
import EventEmitter2 from 'eventemitter2';
import { v4 } from 'uuid';
Expand Down
5 changes: 5 additions & 0 deletions src/api/controllers/sendMessage.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { isBase64, isURL } from 'class-validator';
import { BadRequestException } from '../../exceptions';
import { InstanceDto } from '../dto/instance.dto';
import {
FakeCallDto,
SendAudioDto,
SendButtonDto,
SendContactDto,
Expand Down Expand Up @@ -84,4 +85,8 @@ export class SendMessageController {
public async sendStatus({ instanceName }: InstanceDto, data: SendStatusDto) {
return await this.waMonitor.waInstances[instanceName].statusMessage(data);
}

public async fakeCall({ instanceName }: InstanceDto, data: FakeCallDto) {
return await this.waMonitor.waInstances[instanceName].fakeCall(data);
}
}
2 changes: 1 addition & 1 deletion src/api/dto/chat.dto.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { proto, WAPresence, WAPrivacyOnlineValue, WAPrivacyValue, WAReadReceiptsValue } from '@whiskeysockets/baileys';
import { proto, WAPresence, WAPrivacyOnlineValue, WAPrivacyValue, WAReadReceiptsValue } from 'baileys';

export class OnWhatsAppDto {
constructor(
Expand Down
2 changes: 1 addition & 1 deletion src/api/dto/instance.dto.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { WAPresence } from '@whiskeysockets/baileys';
import { WAPresence } from 'baileys';

export class InstanceDto {
instanceName: string;
Expand Down
7 changes: 6 additions & 1 deletion src/api/dto/sendMessage.dto.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { proto, WAPresence } from '@whiskeysockets/baileys';
import { proto, WAPresence } from 'baileys';

export class Quoted {
key: proto.IMessageKey;
Expand Down Expand Up @@ -131,6 +131,11 @@ export class SendListDto extends Metadata {
sections: Section[];
}

export class FakeCallDto extends Metadata {
number: string;
delay: number;
}

export class ContactMessage {
fullName: string;
wuid: string;
Expand Down
2 changes: 1 addition & 1 deletion src/api/integrations/chatwoot/services/chatwoot.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ import ChatwootClient, {
} from '@figuro/chatwoot-sdk';
import { request as chatwootRequest } from '@figuro/chatwoot-sdk/dist/core/request';
import { Chatwoot as ChatwootModel, Contact as ContactModel, Message as MessageModel } from '@prisma/client';
import { proto } from '@whiskeysockets/baileys';
import axios from 'axios';
import { proto } from 'baileys';
import FormData from 'form-data';
import { createReadStream, unlinkSync, writeFileSync } from 'fs';
import Jimp from 'jimp';
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { inbox } from '@figuro/chatwoot-sdk';
import { Chatwoot as ChatwootModel, Contact, Message } from '@prisma/client';
import { proto } from '@whiskeysockets/baileys';
import { proto } from 'baileys';

import { InstanceDto } from '../../../../api/dto/instance.dto';
import { Chatwoot, configService } from '../../../../config/env.config';
Expand Down
12 changes: 12 additions & 0 deletions src/api/routes/sendMessage.router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { RequestHandler, Router } from 'express';
import {
audioMessageSchema,
contactMessageSchema,
fakeCallSchema,
listMessageSchema,
locationMessageSchema,
mediaMessageSchema,
Expand All @@ -15,6 +16,7 @@ import {
} from '../../validate/validate.schema';
import { RouterBroker } from '../abstract/abstract.router';
import {
FakeCallDto,
SendAudioDto,
SendContactDto,
SendListDto,
Expand Down Expand Up @@ -143,6 +145,16 @@ export class MessageRouter extends RouterBroker {
execute: (instance, data) => sendMessageController.sendList(instance, data),
});

return res.status(HttpStatus.CREATED).json(response);
})
.post(this.routerPath('fakeCall'), ...guards, async (req, res) => {
const response = await this.dataValidate<FakeCallDto>({
request: req,
schema: fakeCallSchema,
ClassRef: FakeCallDto,
execute: (instance, data) => sendMessageController.fakeCall(instance, data),
});

return res.status(HttpStatus.CREATED).json(response);
});
// .post(this.routerPath('sendButtons'), ...guards, async (req, res) => {
Expand Down
2 changes: 1 addition & 1 deletion src/api/services/cache.service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { BufferJSON } from '@whiskeysockets/baileys';
import { BufferJSON } from 'baileys';

import { Logger } from '../../config/logger.config';
import { ICache } from '../abstract/abstract.cache';
Expand Down
2 changes: 1 addition & 1 deletion src/api/services/channel.service.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Contact, Message } from '@prisma/client';
import { WASocket } from '@whiskeysockets/baileys';
import axios from 'axios';
import { WASocket } from 'baileys';
import { isURL } from 'class-validator';
import EventEmitter2 from 'eventemitter2';
import { join } from 'path';
Expand Down
58 changes: 39 additions & 19 deletions src/api/services/channels/whatsapp.baileys.service.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import ffmpegPath from '@ffmpeg-installer/ffmpeg';
import { Boom } from '@hapi/boom';
import { Instance } from '@prisma/client';
import axios from 'axios';
import makeWASocket, {
AnyMessageContent,
BufferedEventData,
Expand All @@ -20,6 +21,7 @@ import makeWASocket, {
GroupMetadata,
isJidBroadcast,
isJidGroup,
isJidNewsletter,
isJidUser,
makeCacheableSignalKeyStore,
MessageUpsertType,
Expand All @@ -34,10 +36,9 @@ import makeWASocket, {
WAMessageUpdate,
WAPresence,
WASocket,
} from '@whiskeysockets/baileys';
import { Label } from '@whiskeysockets/baileys/lib/Types/Label';
import { LabelAssociation } from '@whiskeysockets/baileys/lib/Types/LabelAssociation';
import axios from 'axios';
} from 'baileys';
import { Label } from 'baileys/lib/Types/Label';
import { LabelAssociation } from 'baileys/lib/Types/LabelAssociation';
import { isBase64, isURL } from 'class-validator';
import { randomBytes } from 'crypto';
import EventEmitter2 from 'eventemitter2';
Expand Down Expand Up @@ -108,6 +109,7 @@ import { InstanceDto, SetPresenceDto } from '../../dto/instance.dto';
import { HandleLabelDto, LabelDto } from '../../dto/label.dto';
import {
ContactMessage,
FakeCallDto,
MediaMessage,
Options,
SendAudioDto,
Expand Down Expand Up @@ -244,7 +246,7 @@ export class BaileysStartupService extends ChannelStartupService {
public async getProfileStatus() {
const status = await this.client.fetchStatus(this.instance.wuid);

return status.status;
return status[0]?.status;
}

public get profilePictureUrl() {
Expand Down Expand Up @@ -588,7 +590,7 @@ export class BaileysStartupService extends ChannelStartupService {
shouldIgnoreJid: (jid) => {
const isGroupJid = this.localSettings.groupsIgnore && isJidGroup(jid);
const isBroadcast = !this.localSettings.readStatus && isJidBroadcast(jid);
const isNewsletter = jid.includes('newsletter');
const isNewsletter = isJidNewsletter(jid);

return isGroupJid || isBroadcast || isNewsletter;
},
Expand All @@ -601,6 +603,7 @@ export class BaileysStartupService extends ChannelStartupService {
},
userDevicesCache: this.userDevicesCache,
transactionOpts: { maxCommitRetries: 5, delayBetweenTriesMs: 2500 },
cachedGroupMetadata: this.getGroupMetadataCache,
patchMessageBeforeSending(message) {
if (
message.deviceSentMessage?.message?.listMessage?.listType ===
Expand Down Expand Up @@ -1626,7 +1629,7 @@ export class BaileysStartupService extends ChannelStartupService {
try {
return {
wuid: jid,
status: (await this.client.fetchStatus(jid))?.status,
status: (await this.client.fetchStatus(jid))[0]?.status,
};
} catch (error) {
return {
Expand Down Expand Up @@ -1822,11 +1825,11 @@ export class BaileysStartupService extends ChannelStartupService {
} as unknown as AnyMessageContent,
{
...option,
cachedGroupMetadata:
useCachedGroupMetadata:
!this.configService.get<CacheConf>('CACHE').REDIS.ENABLED &&
!this.configService.get<CacheConf>('CACHE').LOCAL.ENABLED
? null
: this.getGroupMetadataCache,
? false
: true,
} as unknown as MiscMessageGenerationOptions,
);
}
Expand All @@ -1841,11 +1844,11 @@ export class BaileysStartupService extends ChannelStartupService {
} as unknown as AnyMessageContent,
{
...option,
cachedGroupMetadata:
useCachedGroupMetadata:
!this.configService.get<CacheConf>('CACHE').REDIS.ENABLED &&
!this.configService.get<CacheConf>('CACHE').LOCAL.ENABLED
? null
: this.getGroupMetadataCache,
? false
: true,
} as unknown as MiscMessageGenerationOptions,
);
}
Expand All @@ -1862,11 +1865,11 @@ export class BaileysStartupService extends ChannelStartupService {
},
{
...option,
cachedGroupMetadata:
useCachedGroupMetadata:
!this.configService.get<CacheConf>('CACHE').REDIS.ENABLED &&
!this.configService.get<CacheConf>('CACHE').LOCAL.ENABLED
? null
: this.getGroupMetadataCache,
? false
: true,
} as unknown as MiscMessageGenerationOptions,
);
}
Expand All @@ -1888,11 +1891,11 @@ export class BaileysStartupService extends ChannelStartupService {
message as unknown as AnyMessageContent,
{
...option,
cachedGroupMetadata:
useCachedGroupMetadata:
!this.configService.get<CacheConf>('CACHE').REDIS.ENABLED &&
!this.configService.get<CacheConf>('CACHE').LOCAL.ENABLED
? null
: this.getGroupMetadataCache,
? false
: true,
} as unknown as MiscMessageGenerationOptions,
);
})();
Expand Down Expand Up @@ -3437,4 +3440,21 @@ export class BaileysStartupService extends ChannelStartupService {
public async templateMessage() {
throw new Error('Method not available in the Baileys service');
}

public async fakeCall(data: FakeCallDto) {
try {
const number = this.createJid(data.number);
const mdDelay = data.delay ?? 0;

const call = await this.client.offerCall(number);

await delay(mdDelay);

await this.client.rejectCall(call.callId, call.toJid);

return call;
} catch (error) {
throw new BadRequestException('Error making fake call', error.toString());
}
}
}
3 changes: 3 additions & 0 deletions src/api/services/channels/whatsapp.business.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1351,4 +1351,7 @@ export class BusinessStartupService extends ChannelStartupService {
public async receiveMobileCode() {
throw new BadRequestException('Method not available on WhatsApp Business API');
}
public async fakeCall() {
throw new BadRequestException('Method not available on WhatsApp Business API');
}
}
2 changes: 1 addition & 1 deletion src/api/types/wa.types.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/* eslint-disable @typescript-eslint/no-namespace */
import { JsonValue } from '@prisma/client/runtime/library';
import { AuthenticationState, WAConnectionState } from '@whiskeysockets/baileys';
import { AuthenticationState, WAConnectionState } from 'baileys';

export enum Events {
APPLICATION_STARTUP = 'application.startup',
Expand Down
2 changes: 1 addition & 1 deletion src/cache/rediscache.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { BufferJSON } from '@whiskeysockets/baileys';
import { BufferJSON } from 'baileys';
import { RedisClientType } from 'redis';

import { ICache } from '../api/abstract/abstract.cache';
Expand Down
2 changes: 1 addition & 1 deletion src/utils/use-multi-file-auth-state-prisma.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { BufferJSON, initAuthCreds, WAProto as proto } from '@whiskeysockets/baileys';
import { BufferJSON, initAuthCreds, WAProto as proto } from 'baileys';
import fs from 'fs/promises';
import path from 'path';

Expand Down
9 changes: 1 addition & 8 deletions src/utils/use-multi-file-auth-state-provider-files.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,14 +34,7 @@
* └──────────────────────────────────────────────────────────────────────────────┘
*/

import {
AuthenticationCreds,
AuthenticationState,
BufferJSON,
initAuthCreds,
proto,
SignalDataTypeMap,
} from '@whiskeysockets/baileys';
import { AuthenticationCreds, AuthenticationState, BufferJSON, initAuthCreds, proto, SignalDataTypeMap } from 'baileys';
import { isNotEmpty } from 'class-validator';

import { ProviderFiles } from '../api/provider/sessions';
Expand Down
8 changes: 1 addition & 7 deletions src/utils/use-multi-file-auth-state-redis-db.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,4 @@
import {
AuthenticationCreds,
AuthenticationState,
initAuthCreds,
proto,
SignalDataTypeMap,
} from '@whiskeysockets/baileys';
import { AuthenticationCreds, AuthenticationState, initAuthCreds, proto, SignalDataTypeMap } from 'baileys';

import { CacheService } from '../api/services/cache.service';
import { Logger } from '../config/logger.config';
Expand Down
13 changes: 13 additions & 0 deletions src/validate/message.schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -358,3 +358,16 @@ export const listMessageSchema: JSONSchema7 = {
},
required: ['number', 'title', 'footerText', 'buttonText', 'sections'],
};

export const fakeCallSchema: JSONSchema7 = {
$id: v4(),
type: 'object',
properties: {
number: { ...numberDefinition },
delay: {
type: 'integer',
description: 'Enter a value in milliseconds',
},
},
required: ['number', 'delay'],
};

0 comments on commit 7dfc09f

Please sign in to comment.