Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(engine): baileys media sends (image/video/audio/document/sticker)
rmyndharis62d144011ee2
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.tsindex c087d1f45..02301915b 100644--- a/src/engine/adapters/baileys.adapter.spec.ts+++ b/src/engine/adapters/baileys.adapter.spec.ts@@ -1,5 +1,9 @@import { EventEmitter } from 'events';+jest.mock('../../common/media/load-remote-media', () => ({+ loadRemoteMediaBuffer: jest.fn(),+}));+// A fake Baileys socket: an event emitter wearing the methods the adapter calls.class FakeSock extends EventEmitter {public ev = {@@ -39,6 +43,7 @@ import { BaileysAdapter } from './baileys.adapter';import { EngineStatus, EngineEventCallbacks } from '../interfaces/whatsapp-engine.interface';import { EngineNotReadyError } from '../../common/errors/engine-not-ready.error';import { EngineNotSupportedError } from '../../common/errors/engine-not-supported.error';+import { loadRemoteMediaBuffer } from '../../common/media/load-remote-media';const newAdapter = (): BaileysAdapter => new BaileysAdapter({ sessionId: 'sess-1', authDir: './data/baileys' });@@ -142,9 +147,6 @@ describe('BaileysAdapter capability gating', () => {const adapter = newAdapter();await expect(adapter.getGroups()).rejects.toBeInstanceOf(EngineNotSupportedError);await expect(adapter.getChats()).rejects.toBeInstanceOf(EngineNotSupportedError);- await expect(adapter.sendImageMessage('x', { mimetype: 'image/png', data: 'AAA' })).rejects.toBeInstanceOf(- EngineNotSupportedError,- );});});@@ -270,3 +272,85 @@ describe('BaileysAdapter inbound fan-out', () => {expect(onMessageAck).toHaveBeenCalledWith('OUT1', 'delivered');});});++describe('BaileysAdapter media sends', () => {+ beforeEach(() => {+ fakeSock.user = { id: '628999:[email protected]', name: 'Me' };+ jest.clearAllMocks();+ fakeSock.sendMessage.mockResolvedValue({ key: { id: 'M1' }, messageTimestamp: 1700000005 });+ });++ const ready = async (): Promise<BaileysAdapter> => {+ const adapter = newAdapter();+ await adapter.initialize({});+ fakeSock.fire('connection.update', { connection: 'open' });+ return adapter;+ };++ it('sendImageMessage sends a Buffer image with caption + mimetype', async () => {+ const adapter = await ready();+ const buf = Buffer.from([1, 2, 3]);+ const res = await adapter.sendImageMessage('[email protected]', {+ mimetype: 'image/png',+ data: buf,+ caption: 'hi',+ });+ expect(fakeSock.sendMessage).toHaveBeenCalledWith('[email protected]', {+ image: buf,+ caption: 'hi',+ mimetype: 'image/png',+ });+ expect(res).toEqual({ id: 'M1', timestamp: 1700000005 });+ });++ it('resolves a base64 data string to a Buffer (no URL fetch)', async () => {+ const adapter = await ready();+ await adapter.sendDocumentMessage('[email protected]', {+ mimetype: 'application/pdf',+ data: Buffer.from('PDFDATA').toString('base64'),+ filename: 'doc.pdf',+ });+ expect(loadRemoteMediaBuffer).not.toHaveBeenCalled();+ expect(fakeSock.sendMessage).toHaveBeenCalledWith('[email protected]', {+ document: Buffer.from('PDFDATA'),+ mimetype: 'application/pdf',+ fileName: 'doc.pdf',+ });+ });++ it('fetches a URL data string through the SSRF-guarded loader', async () => {+ (loadRemoteMediaBuffer as jest.Mock).mockResolvedValue({ data: Buffer.from([9]), mimetype: 'video/mp4' });+ const adapter = await ready();+ await adapter.sendVideoMessage('[email protected]', { mimetype: '', data: 'https://cdn.example/v.mp4' });+ expect(loadRemoteMediaBuffer).toHaveBeenCalledWith('https://cdn.example/v.mp4');+ expect(fakeSock.sendMessage).toHaveBeenCalledWith('[email protected]', {+ video: Buffer.from([9]),+ caption: undefined,+ mimetype: 'video/mp4',+ });+ });++ it('sendAudioMessage sets ptt:false', async () => {+ const adapter = await ready();+ await adapter.sendAudioMessage('[email protected]', { mimetype: 'audio/mp4', data: Buffer.from([1]) });+ expect(fakeSock.sendMessage).toHaveBeenCalledWith('[email protected]', {+ audio: Buffer.from([1]),+ mimetype: 'audio/mp4',+ ptt: false,+ });+ });++ it('sendStickerMessage sends the sticker buffer', async () => {+ const adapter = await ready();+ await adapter.sendStickerMessage('[email protected]', { mimetype: 'image/webp', data: Buffer.from([7]) });+ expect(fakeSock.sendMessage).toHaveBeenCalledWith('[email protected]', { sticker: Buffer.from([7]) });+ });++ it('media sends reject with EngineNotReadyError before the connection is open', async () => {+ const adapter = newAdapter();+ await adapter.initialize({});+ await expect(+ adapter.sendImageMessage('x', { mimetype: 'image/png', data: Buffer.from([1]) }),+ ).rejects.toBeInstanceOf(EngineNotReadyError);+ });+});diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.tsindex 0082eeec5..29152e38c 100644--- a/src/engine/adapters/baileys.adapter.ts+++ b/src/engine/adapters/baileys.adapter.ts@@ -5,7 +5,7 @@ import makeWASocket, {getContentType,useMultiFileAuthState,} from '@whiskeysockets/baileys';-import type { WAMessage, WASocket } from '@whiskeysockets/baileys';+import type { AnyMessageContent, WAMessage, WASocket } from '@whiskeysockets/baileys';import { buildIncomingMessageFromBaileys, mapBaileysStatus } from './baileys-message-mapper';import type { ILogger } from '@whiskeysockets/baileys/lib/Utils/logger.js';import {@@ -34,6 +34,7 @@ import {ChatSummary,TextStatusOptions,} from '../interfaces/whatsapp-engine.interface';+import { loadRemoteMediaBuffer } from '../../common/media/load-remote-media';import { EngineNotReadyError } from '../../common/errors/engine-not-ready.error';import { EngineNotSupportedError } from '../../common/errors/engine-not-supported.error';import { createLogger } from '../../common/services/logger.service';@@ -249,30 +250,45 @@ export class BaileysAdapter implements IWhatsAppEngine {await this.sock!.sendPresenceUpdate(presence, chatId);}- // ----- Gated: not supported by this minimal slice (no store) ------ /* eslint-disable @typescript-eslint/no-unused-vars */+ async sendImageMessage(chatId: string, media: MediaInput): Promise<MessageResult> {+ this.ensureReady();+ const { data, mimetype } = await this.resolveMediaBuffer(media);+ return this.sendContent(chatId, { image: data, caption: media.caption, mimetype });+ }- sendImageMessage(_chatId: string, _media: MediaInput): Promise<MessageResult> {- return this.unsupported('sendImageMessage');+ async sendVideoMessage(chatId: string, media: MediaInput): Promise<MessageResult> {+ this.ensureReady();+ const { data, mimetype } = await this.resolveMediaBuffer(media);+ return this.sendContent(chatId, { video: data, caption: media.caption, mimetype });}- sendVideoMessage(_chatId: string, _media: MediaInput): Promise<MessageResult> {- return this.unsupported('sendVideoMessage');++ async sendAudioMessage(chatId: string, media: MediaInput): Promise<MessageResult> {+ this.ensureReady();+ const { data, mimetype } = await this.resolveMediaBuffer(media);+ return this.sendContent(chatId, { audio: data, mimetype, ptt: false });}- sendAudioMessage(_chatId: string, _media: MediaInput): Promise<MessageResult> {- return this.unsupported('sendAudioMessage');++ async sendDocumentMessage(chatId: string, media: MediaInput): Promise<MessageResult> {+ this.ensureReady();+ const { data, mimetype } = await this.resolveMediaBuffer(media);+ return this.sendContent(chatId, { document: data, mimetype, fileName: media.filename ?? 'file' });}- sendDocumentMessage(_chatId: string, _media: MediaInput): Promise<MessageResult> {- return this.unsupported('sendDocumentMessage');++ async sendStickerMessage(chatId: string, media: MediaInput): Promise<MessageResult> {+ this.ensureReady();+ const { data } = await this.resolveMediaBuffer(media);+ return this.sendContent(chatId, { sticker: data });}++ // ----- Gated: not supported by this minimal slice (no store) -----+ /* eslint-disable @typescript-eslint/no-unused-vars */+sendLocationMessage(_chatId: string, _location: LocationInput): Promise<MessageResult> {return this.unsupported('sendLocationMessage');}sendContactMessage(_chatId: string, _contact: ContactCard): Promise<MessageResult> {return this.unsupported('sendContactMessage');}- sendStickerMessage(_chatId: string, _media: MediaInput): Promise<MessageResult> {- return this.unsupported('sendStickerMessage');- }replyToMessage(_chatId: string, _quotedMsgId: string, _text: string): Promise<MessageResult> {return this.unsupported('replyToMessage');}@@ -481,6 +497,25 @@ export class BaileysAdapter implements IWhatsAppEngine {return typeof ts === 'number' ? ts : ts.toNumber();}+ /** Resolve a MediaInput's data (Buffer | base64 string | http(s) URL) to bytes + mimetype. */+ private async resolveMediaBuffer(media: MediaInput): Promise<{ data: Buffer; mimetype: string }> {+ if (Buffer.isBuffer(media.data)) {+ return { data: media.data, mimetype: media.mimetype };+ }+ if (/^https?:\/\//i.test(media.data)) {+ const fetched = await loadRemoteMediaBuffer(media.data);+ // Caller's declared mimetype wins; fall back to the response content-type.+ return { data: fetched.data, mimetype: media.mimetype || fetched.mimetype };+ }+ return { data: Buffer.from(media.data, 'base64'), mimetype: media.mimetype };+ }++ /** Send a Baileys content object and shape the result like the other sends. */+ private async sendContent(chatId: string, content: AnyMessageContent): Promise<MessageResult> {+ const sent = await this.sock!.sendMessage(chatId, content);+ return { id: sent?.key?.id ?? '', timestamp: this.toUnixSeconds(sent?.messageTimestamp) };+ }+private unsupported(method: string): Promise<any> {return Promise.reject(new EngineNotSupportedError(method));}