Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(engine): baileys inbound media/location/quoted + revoke + reaction + status filter
rmyndharis1821f93b6771
diff --git a/src/engine/adapters/baileys-message-mapper.ts b/src/engine/adapters/baileys-message-mapper.tsindex 3fab3473a..c954532b9 100644--- a/src/engine/adapters/baileys-message-mapper.ts+++ b/src/engine/adapters/baileys-message-mapper.ts@@ -77,6 +77,12 @@ export interface BaileysIncomingFields {pushName?: string;/** The account's own normalized JID, for from/to on outgoing messages. */selfJid?: string;+ /** Pre-extracted media: mimetype + base64 data (+ optional filename). Populated by the adapter. */+ media?: IncomingMessage['media'];+ /** Pre-extracted location. Populated by the adapter for `locationMessage`. */+ location?: IncomingMessage['location'];+ /** Pre-extracted quoted message context. Populated by the adapter when `contextInfo` is present. */+ quotedMessage?: IncomingMessage['quotedMessage'];}/**@@ -117,5 +123,17 @@ export function buildIncomingMessageFromBaileys(fields: BaileysIncomingFields):incoming.contact = { pushName: fields.pushName };}+ if (fields.media) {+ incoming.media = fields.media;+ }++ if (fields.location) {+ incoming.location = fields.location;+ }++ if (fields.quotedMessage) {+ incoming.quotedMessage = fields.quotedMessage;+ }+return incoming;}diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.tsindex cc397000b..514eb90f6 100644--- a/src/engine/adapters/baileys.adapter.spec.ts+++ b/src/engine/adapters/baileys.adapter.spec.ts@@ -49,7 +49,15 @@ jest.mock('@whiskeysockets/baileys', () => ({useMultiFileAuthState: jest.fn().mockResolvedValue({ state: { creds: {}, keys: {} }, saveCreds }),fetchLatestBaileysVersion: jest.fn().mockResolvedValue({ version: [2, 3000, 0] }),getContentType: jest.fn(() => 'conversation'),+ downloadMediaMessage: jest.fn().mockResolvedValue(Buffer.from('IMGDATA')),DisconnectReason: { loggedOut: 401, restartRequired: 515 },+ proto: {+ Message: {+ ProtocolMessage: {+ Type: { REVOKE: 0 },+ },+ },+ },}));import { BaileysAdapter } from './baileys.adapter';@@ -298,6 +306,7 @@ describe('BaileysAdapter inbound fan-out', () => {},],});+ await new Promise(r => setImmediate(r));expect(onMessage).toHaveBeenCalledTimes(1);// eslint-disable-next-line @typescript-eslint/no-unsafe-member-accessconst msg = onMessage.mock.calls[0][0] as { id: string; body: string; type: string; fromMe: boolean };@@ -319,6 +328,7 @@ describe('BaileysAdapter inbound fan-out', () => {},],});+ await new Promise(r => setImmediate(r));expect(onMessageCreate).toHaveBeenCalledTimes(1);expect(onMessage).not.toHaveBeenCalled();});@@ -343,6 +353,231 @@ describe('BaileysAdapter inbound fan-out', () => {fakeSock.fire('messages.update', [{ key: { id: 'OUT1' }, update: { status: 3 } }]);expect(onMessageAck).toHaveBeenCalledWith('OUT1', 'delivered');});++ it('inbound image: downloads media and exposes base64 + caption as body', async () => {+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion+ const baileys = jest.requireMock('@whiskeysockets/baileys') as {+ getContentType: jest.Mock;+ downloadMediaMessage: jest.Mock;+ };+ baileys.getContentType.mockReturnValue('imageMessage');+ const imgBuf = Buffer.from('PNGBYTES');+ baileys.downloadMediaMessage.mockResolvedValue(imgBuf);++ const onMessage = jest.fn();+ const adapter = newAdapter();+ await adapter.initialize({ onMessage });+ fakeSock.fire('messages.upsert', {+ type: 'notify',+ messages: [+ {+ key: { remoteJid: '[email protected]', fromMe: false, id: 'IMG1' },+ message: { imageMessage: { mimetype: 'image/png', caption: 'look at this' } },+ messageTimestamp: 1700000020,+ },+ ],+ });+ await new Promise(r => setImmediate(r));+ expect(onMessage).toHaveBeenCalledTimes(1);+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access+ const msg = onMessage.mock.calls[0][0] as {+ id: string;+ body: string;+ type: string;+ media: { mimetype: string; data: string };+ };+ expect(msg.type).toBe('image');+ expect(msg.body).toBe('look at this');+ expect(msg.media).toEqual({ mimetype: 'image/png', data: imgBuf.toString('base64') });+ });++ it('inbound location: populates the location field with coordinates', async () => {+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion+ const baileys = jest.requireMock('@whiskeysockets/baileys') as { getContentType: jest.Mock };+ baileys.getContentType.mockReturnValue('locationMessage');++ const onMessage = jest.fn();+ const adapter = newAdapter();+ await adapter.initialize({ onMessage });+ fakeSock.fire('messages.upsert', {+ type: 'notify',+ messages: [+ {+ key: { remoteJid: '[email protected]', fromMe: false, id: 'LOC1' },+ message: {+ locationMessage: {+ degreesLatitude: 1.23,+ degreesLongitude: 4.56,+ name: 'Office',+ address: '1 Main St',+ },+ },+ messageTimestamp: 1700000021,+ },+ ],+ });+ await new Promise(r => setImmediate(r));+ expect(onMessage).toHaveBeenCalledTimes(1);+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access+ const msg = onMessage.mock.calls[0][0] as {+ type: string;+ location: { latitude: number; longitude: number; description?: string; address?: string };+ };+ expect(msg.type).toBe('location');+ expect(msg.location).toEqual({ latitude: 1.23, longitude: 4.56, description: 'Office', address: '1 Main St' });+ });++ it('inbound quoted reply: populates quotedMessage', async () => {+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion+ const baileys = jest.requireMock('@whiskeysockets/baileys') as { getContentType: jest.Mock };+ baileys.getContentType.mockReturnValue('extendedTextMessage');++ const onMessage = jest.fn();+ const adapter = newAdapter();+ await adapter.initialize({ onMessage });+ fakeSock.fire('messages.upsert', {+ type: 'notify',+ messages: [+ {+ key: { remoteJid: '[email protected]', fromMe: false, id: 'REPLY1' },+ message: {+ extendedTextMessage: {+ text: 'reply text',+ contextInfo: {+ stanzaId: 'QUOTED_ID',+ quotedMessage: { conversation: 'original message' },+ },+ },+ },+ messageTimestamp: 1700000022,+ },+ ],+ });+ await new Promise(r => setImmediate(r));+ expect(onMessage).toHaveBeenCalledTimes(1);+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access+ const msg = onMessage.mock.calls[0][0] as {+ body: string;+ quotedMessage: { id: string; body: string };+ };+ expect(msg.body).toBe('reply text');+ expect(msg.quotedMessage).toEqual({ id: 'QUOTED_ID', body: 'original message' });+ });++ it('REVOKE protocolMessage: fires onMessageRevoked and NOT onMessage', async () => {+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion+ const baileys = jest.requireMock('@whiskeysockets/baileys') as { getContentType: jest.Mock };+ baileys.getContentType.mockReturnValue('protocolMessage');++ const onMessage = jest.fn();+ const onMessageRevoked = jest.fn();+ const adapter = newAdapter();+ await adapter.initialize({ onMessage, onMessageRevoked });+ fakeSock.fire('messages.upsert', {+ type: 'notify',+ messages: [+ {+ key: { remoteJid: '[email protected]', fromMe: false, id: 'PROTO1' },+ message: {+ protocolMessage: {+ key: { id: 'ORIGINAL_ID' },+ type: 0, // REVOKE+ },+ },+ messageTimestamp: 1700000023,+ },+ ],+ });+ await new Promise(r => setImmediate(r));+ expect(onMessage).not.toHaveBeenCalled();+ expect(onMessageRevoked).toHaveBeenCalledTimes(1);+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access+ const revoked = onMessageRevoked.mock.calls[0][0] as {+ id: string;+ chatId: string;+ type: string;+ body: string;+ };+ expect(revoked.id).toBe('ORIGINAL_ID');+ expect(revoked.chatId).toBe('[email protected]');+ expect(revoked.type).toBe('revoked');+ expect(revoked.body).toBe('');+ });++ it('reactionMessage: fires onMessageReaction and NOT onMessage', async () => {+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion+ const baileys = jest.requireMock('@whiskeysockets/baileys') as { getContentType: jest.Mock };+ baileys.getContentType.mockReturnValue('reactionMessage');++ const onMessage = jest.fn();+ const onMessageReaction = jest.fn();+ const adapter = newAdapter();+ await adapter.initialize({ onMessage, onMessageReaction });+ fakeSock.fire('messages.upsert', {+ type: 'notify',+ messages: [+ {+ key: {+ remoteJid: '[email protected]',+ fromMe: false,+ id: 'REACT1',+ participant: '[email protected]',+ },+ message: {+ reactionMessage: {+ key: { id: 'TARGET_MSG_ID' },+ text: 'π',+ },+ },+ messageTimestamp: 1700000024,+ },+ ],+ });+ await new Promise(r => setImmediate(r));+ expect(onMessage).not.toHaveBeenCalled();+ expect(onMessageReaction).toHaveBeenCalledTimes(1);+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access+ const event = onMessageReaction.mock.calls[0][0] as {+ messageId: string;+ chatId: string;+ reaction: string;+ senderId: string;+ };+ expect(event.messageId).toBe('TARGET_MSG_ID');+ expect(event.chatId).toBe('[email protected]');+ expect(event.reaction).toBe('π');+ expect(event.senderId).toBe('[email protected]');+ });++ it('media download failure: logs the error and emits the message without media (no throw)', async () => {+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion+ const baileys = jest.requireMock('@whiskeysockets/baileys') as {+ getContentType: jest.Mock;+ downloadMediaMessage: jest.Mock;+ };+ baileys.getContentType.mockReturnValue('imageMessage');+ baileys.downloadMediaMessage.mockRejectedValue(new Error('download failed'));++ const onMessage = jest.fn();+ const adapter = newAdapter();+ await adapter.initialize({ onMessage });+ fakeSock.fire('messages.upsert', {+ type: 'notify',+ messages: [+ {+ key: { remoteJid: '[email protected]', fromMe: false, id: 'IMGFAIL' },+ message: { imageMessage: { mimetype: 'image/jpeg', caption: 'broken' } },+ messageTimestamp: 1700000025,+ },+ ],+ });+ await new Promise(r => setImmediate(r));+ // message is still emitted, just without media+ expect(onMessage).toHaveBeenCalledTimes(1);+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access+ const msg = onMessage.mock.calls[0][0] as { media?: unknown };+ expect(msg.media).toBeUndefined();+ });});describe('BaileysAdapter media sends', () => {@@ -520,6 +755,7 @@ describe('BaileysAdapter store-backed ops', () => {{ key: { remoteJid: '[email protected]', fromMe: false, id: 'IN9' }, message: { conversation: 'hi' } },],});+ await new Promise(r => setImmediate(r));// eslint-disable-next-line @typescript-eslint/no-unsafe-assignmentconst inboundMatcher = expect.objectContaining({ key: expect.objectContaining({ id: 'IN9' }) });expect(fakeStore.put).toHaveBeenCalledWith('sess-1', inboundMatcher);@@ -692,6 +928,7 @@ describe('BaileysAdapter contact + chat reads', () => {},],});+ await new Promise(r => setImmediate(r));const chats = await adapter.getChats();expect(chats[0]).toEqual({id: '[email protected]',@@ -744,6 +981,7 @@ describe('BaileysAdapter sendSeen + deleteChat', () => {},],});+ await new Promise(r => setImmediate(r)); // let async processInboundMessage completereturn adapter;};diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.tsindex 57c24e6fc..81f946de7 100644--- a/src/engine/adapters/baileys.adapter.ts+++ b/src/engine/adapters/baileys.adapter.ts@@ -25,6 +25,8 @@ import {PaginatedProducts,Product,ProductQueryOptions,+ ReactionEvent,+ RevokedMessage,Status,StatusResult,ChatSummary,@@ -582,19 +584,63 @@ export class BaileysAdapter implements IWhatsAppEngine {if (!msg.message || !msg.key?.remoteJid) {continue; // protocol/empty messages carry no neutral content}- const incoming = this.mapMessage(msg);- if (msg.key.fromMe === true) {- this.callbacks.onMessageCreate?.(incoming);- } else {- this.callbacks.onMessage?.(incoming);+ void this.processInboundMessage(msg);+ }+ }++ private async processInboundMessage(msg: WAMessage): Promise<void> {+ const b = await this.loadLib();+ const remoteJid = msg.key.remoteJid!;+ const contentType = b.getContentType(msg.message ?? undefined);++ // --- protocolMessage REVOKE: don't emit onMessage ---+ if (contentType === 'protocolMessage') {+ const pm = msg.message?.protocolMessage;+ if (pm?.type === b.proto.Message.ProtocolMessage.Type.REVOKE) {+ const from = msg.key.fromMe === true ? this.normalizedSelfJid() : remoteJid;+ const to = msg.key.fromMe === true ? remoteJid : this.normalizedSelfJid();+ const revoked: RevokedMessage = {+ id: pm.key?.id ?? '',+ chatId: remoteJid,+ from,+ to,+ type: 'revoked',+ body: '',+ timestamp: this.toUnixSeconds(msg.messageTimestamp),+ };+ this.callbacks.onMessageRevoked?.(revoked);+ return;}- void this.config.messageStore?.put(this.config.sessionId, msg).catch(err =>- this.logger.warn('Failed to persist message to store', {- error: err instanceof Error ? err.message : String(err),- }),- );- this.sessionStore.recordMessage(msg);+ // Other protocol messages (ephemeral, history sync, etc.) β skip silently.+ return;+ }++ // --- reactionMessage: don't emit onMessage ---+ if (contentType === 'reactionMessage') {+ const rm = msg.message?.reactionMessage;+ const event: ReactionEvent = {+ messageId: rm?.key?.id ?? '',+ chatId: remoteJid,+ reaction: rm?.text ?? '',+ senderId: msg.key.participant ?? remoteJid,+ };+ this.callbacks.onMessageReaction?.(event);+ return;+ }++ // --- Normal message: enrich + emit ---+ const incoming = await this.mapMessage(msg, contentType);+ if (msg.key.fromMe === true) {+ this.callbacks.onMessageCreate?.(incoming);+ } else {+ this.callbacks.onMessage?.(incoming);}+ void this.config.messageStore?.put(this.config.sessionId, msg).catch(err =>+ this.logger.warn('Failed to persist message to store', {+ error: err instanceof Error ? err.message : String(err),+ }),+ );+ this.sessionStore.recordMessage(msg);}private handleMessagesUpdate(@@ -608,10 +654,99 @@ export class BaileysAdapter implements IWhatsAppEngine {}}- private mapMessage(msg: WAMessage): IncomingMessage {+ private async mapMessage(msg: WAMessage, contentType: string | undefined): Promise<IncomingMessage> {+ const b = await this.loadLib();const content = msg.message ?? {};- const contentType = this.lib?.getContentType(msg.message ?? undefined);- const body = content.conversation ?? content.extendedTextMessage?.text ?? '';++ // Body: text first, then media caption as fallback.+ const body =+ content.conversation ??+ content.extendedTextMessage?.text ??+ content.imageMessage?.caption ??+ content.videoMessage?.caption ??+ content.documentMessage?.caption ??+ '';++ // --- location ---+ // ILocationMessage has name/address; ILiveLocationMessage does not β use the static variant only.+ let location: IncomingMessage['location'];+ if (contentType === 'locationMessage' || contentType === 'liveLocationMessage') {+ const lm = content.locationMessage ?? content.liveLocationMessage;+ if (lm) {+ const staticLm = content.locationMessage; // only ILocationMessage has name/address+ location = {+ latitude: lm.degreesLatitude ?? 0,+ longitude: lm.degreesLongitude ?? 0,+ description: staticLm?.name ?? undefined,+ address: staticLm?.address ?? undefined,+ };+ }+ }++ // --- media (image / video / audio / document / sticker) ---+ let media: IncomingMessage['media'];+ const isMediaType =+ contentType === 'imageMessage' ||+ contentType === 'videoMessage' ||+ contentType === 'audioMessage' ||+ contentType === 'documentMessage' ||+ contentType === 'documentWithCaptionMessage' ||+ contentType === 'stickerMessage';+ if (isMediaType) {+ try {+ const buf = await b.downloadMediaMessage(+ msg,+ 'buffer',+ {},+ {+ logger: createSilentLogger(),+ reuploadRequest: this.sock!.updateMediaMessage,+ },+ );+ const subMessage =+ content.imageMessage ??+ content.videoMessage ??+ content.audioMessage ??+ content.documentMessage ??+ content.stickerMessage;+ const mimetype = subMessage?.mimetype ?? '';+ const filename = content.documentMessage?.fileName ?? undefined;+ media = { mimetype, data: buf.toString('base64'), filename };+ } catch (err) {+ this.logger.debug('Failed to download inbound media; emitting message without media', {+ error: err instanceof Error ? err.message : String(err),+ msgId: msg.key.id,+ });+ }+ }++ // --- quoted message ---+ let quotedMessage: IncomingMessage['quotedMessage'];+ const subForContext =+ content.extendedTextMessage ??+ content.imageMessage ??+ content.videoMessage ??+ content.audioMessage ??+ content.documentMessage ??+ content.stickerMessage ??+ content.locationMessage;+ const contextInfo = (+ subForContext as+ | { contextInfo?: { stanzaId?: string | null; quotedMessage?: Record<string, unknown> | null } }+ | undefined+ )?.contextInfo;+ if (contextInfo?.quotedMessage && contextInfo.stanzaId) {+ const qm = contextInfo.quotedMessage as Record<string, { text?: string; caption?: string } | undefined>;+ const qBody =+ (qm.conversation as unknown as string) ??+ qm.extendedTextMessage?.text ??+ qm.imageMessage?.caption ??+ qm.videoMessage?.caption ??+ qm.documentMessage?.caption ??+ '';+ quotedMessage = { id: contextInfo.stanzaId, body: qBody };+ }+return buildIncomingMessageFromBaileys({id: msg.key.id ?? '',remoteJid: msg.key.remoteJid!,@@ -623,6 +758,9 @@ export class BaileysAdapter implements IWhatsAppEngine {timestamp: this.toUnixSeconds(msg.messageTimestamp),pushName: msg.pushName ?? undefined,selfJid: this.normalizedSelfJid(),+ media,+ location,+ quotedMessage,});}diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex 921bb9998..3201ca078 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -557,6 +557,24 @@ describe('SessionService', () => {expect(dispatchedEvents('message.sent')).toHaveLength(0);});+ it('does not dispatch message.received for a status/story broadcast via onMessage (isStatusBroadcast)', async () => {+ const callbacks = await startAndCaptureCallbacks();++ // Engine delivers a status@broadcast inbound β engine-neutral guard must drop it.+ callbacks.onMessage!(+ makeMessage({+ from: 'status@broadcast',+ to: '[email protected]',+ chatId: 'status@broadcast',+ fromMe: false,+ isStatusBroadcast: true,+ }),+ );+ await flush();++ expect(dispatchedEvents('message.received')).toHaveLength(0);+ });+// The default hookManager mock returns an empty `data: {}`; echo the message through so the// engine-set fields (isLidSender) survive the hook and reach the inline-resolution branch.const echoHook = () =>diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.tsindex a93f98be6..476d0a14c 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -393,6 +393,11 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat});},onMessage: (message): void => {+ // Status/Story posts arrive via the inbound path for some engines; don't persist or webhook them.+ // Mirrors the isStatusBroadcast guard in onMessageCreate below.+ if (message.isStatusBroadcast) {+ return;+ }this.logger.debug(`Message received from ${message.from}`, {sessionId: id,messageId: message.id,