Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(engine): announce only text and caption edits on whatsapp-web.js
Yudhi Armyndharis7715cbcc9f5a
diff --git a/src/engine/adapters/inbound-hold.spec.ts b/src/engine/adapters/inbound-hold.spec.tsindex 16126a27a..8804612fb 100644--- a/src/engine/adapters/inbound-hold.spec.ts+++ b/src/engine/adapters/inbound-hold.spec.ts@@ -1624,7 +1624,14 @@ describe('whatsapp-web.js inbound messages held for storage', () => {} else {client.emit('message_edit',- { id: { _serialized: 't2' }, from: '[email protected]', to: '[email protected]', type: 'chat', fromMe: false },+ {+ id: { _serialized: 't2' },+ from: '[email protected]',+ to: '[email protected]',+ body: 'corrected',+ type: 'chat',+ fromMe: false,+ },'corrected',);}diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.tsindex 9118220db..812fff64a 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts@@ -4131,6 +4131,30 @@ describe('WhatsAppWebJsAdapter message_edit', () => {return { onMessageEdited, client };};+ // The client emits `new Message(client, model)` with the model serialized inside WhatsApp Web's change:body or+ // change:caption handler, so it holds the values after the change (Client.js, onEditMessageEvent). Built here+ // with the real structure, whose `body` is the caption of a message with a file and the body attribute otherwise.+ const WwebjsMessage = jest.requireActual<{ Message: new (client: unknown, data: object) => unknown }>(+ 'whatsapp-web.js',+ ).Message;+ const changed = (client: EventEmitter, model: Record<string, unknown>, newBody: unknown, prevBody: unknown): void => {+ client.emit(+ 'message_edit',+ new WwebjsMessage(client, {+ id: { id: 'EDIT1', remote: '[email protected]', fromMe: false, _serialized: '[email protected]_EDIT1' },+ from: '[email protected]',+ to: '[email protected]',+ t: 1700000080,+ ...model,+ }),+ newBody,+ prevBody,+ );+ };+ const editedBodies = (onMessageEdited: jest.Mock): string[] =>+ (onMessageEdited.mock.calls as Array<[EditedMessage]>).map(([edit]) => edit.body);+ const THUMB = '/9j/4AAQSkZJRgABAQAAAQABAAD';+it('emits onMessageEdited with the new body and mapped fields', () => {const { onMessageEdited, client } = wireEditHandler();const now = jest.spyOn(Date, 'now').mockReturnValue(1700000089123);@@ -4138,18 +4162,16 @@ describe('WhatsAppWebJsAdapter message_edit', () => {try {client.emit('message_edit',- {- id: { _serialized: 'MSG_EDIT_1' },+ new WwebjsMessage(client, {+ id: { id: 'MSG_EDIT_1', remote: '[email protected]', fromMe: false, _serialized: 'MSG_EDIT_1' },from: '[email protected]',to: '[email protected]',author: '[email protected]',- body: 'Old text',+ body: 'Edited new text',type: 'chat',- fromMe: false,- hasMedia: false,- mentionedIds: ['[email protected]'],- timestamp: 1700000080,- },+ mentionedJidList: ['[email protected]'],+ t: 1700000080,+ }),'Edited new text','Old text',);@@ -4175,6 +4197,56 @@ describe('WhatsAppWebJsAdapter message_edit', () => {timestamp: 1700000089,});});++ it('emits the new caption of a media message whose caption changed', () => {+ const { onMessageEdited, client } = wireEditHandler();+ changed(+ client,+ { type: 'image', body: THUMB, caption: 'new caption', directPath: '/v/t62/1', mimetype: 'image/jpeg' },+ 'new caption',+ 'old caption',+ );++ expect(editedBodies(onMessageEdited)).toEqual(['new caption']);+ const [[edit]] = onMessageEdited.mock.calls as Array<[EditedMessage]>;+ expect(edit).toEqual(expect.objectContaining({ type: 'image', hasMedia: true }));+ });++ it.each([+ ['the thumbnail of a captioned image', { type: 'image', caption: 'cap', directPath: '/v/t62/1' }],+ [+ 'the thumbnail of a forwarded video',+ { type: 'video', caption: 'cap', directPath: '/v/t62/2', isForwarded: true },+ ],+ ['the thumbnail of an image without a caption', { type: 'image', directPath: '/v/t62/3' }],+ ])('emits nothing when only %s changed', (_what, model) => {+ const { onMessageEdited, client } = wireEditHandler();+ changed(client, { ...model, body: `${THUMB}new` }, `${THUMB}new`, `${THUMB}old`);++ expect(onMessageEdited).not.toHaveBeenCalled();+ });++ it('emits nothing for a changed location preview, which no user edits', () => {+ const { onMessageEdited, client } = wireEditHandler();+ changed(client, { type: 'location', body: `${THUMB}new`, lat: 1, lng: 2 }, `${THUMB}new`, `${THUMB}old`);++ expect(onMessageEdited).not.toHaveBeenCalled();+ });++ it('emits nothing for a changed caption attribute of a text message, which shows its body', () => {+ const { onMessageEdited, client } = wireEditHandler();+ changed(client, { type: 'chat', body: 'hello', caption: 'stray' }, 'stray', undefined);++ expect(onMessageEdited).not.toHaveBeenCalled();+ });++ it('emits nothing for a media message WhatsApp Web holds no file for, whose body attribute is its thumbnail', () => {+ const { onMessageEdited, client } = wireEditHandler();+ changed(client, { type: 'image', body: `${THUMB}new`, caption: 'cap' }, `${THUMB}new`, `${THUMB}old`);+ changed(client, { type: 'image', body: THUMB, caption: 'new caption' }, 'new caption', 'cap');++ expect(onMessageEdited).not.toHaveBeenCalled();+ });});describe('WhatsAppWebJsAdapter group notifications (group_join / group_leave / group_update)', () => {diff --git a/src/engine/adapters/wwebjs-message-changes.spec.ts b/src/engine/adapters/wwebjs-message-changes.spec.tsindex 198955847..59221f88c 100644--- a/src/engine/adapters/wwebjs-message-changes.spec.ts+++ b/src/engine/adapters/wwebjs-message-changes.spec.ts@@ -75,20 +75,33 @@ const incoming = (hasQuotedMsg: false,});-const editEvent = (client: EventEmitter, id: string, body: string, opts: { media?: boolean; fromMe?: boolean } = {}) =>+/**+ * A `message_edit` as whatsapp-web.js raises it: the message as it is after the change, whose `body` is its text+ * (the caption of a media message), and the new value of the attribute that changed, which is that text unless+ * `attribute` says otherwise (the thumbnail a media message keeps in its body attribute).+ */+const editEvent = (+ client: EventEmitter,+ id: string,+ body: string,+ opts: { media?: boolean; fromMe?: boolean; attribute?: string } = {},+) =>client.emit('message_edit',{id: { _serialized: id },from: opts.fromMe ? SELF : CHAT,to: opts.fromMe ? CHAT : SELF,+ body,type: opts.media ? 'image' : 'chat',fromMe: Boolean(opts.fromMe),hasMedia: Boolean(opts.media),},- body,+ opts.attribute ?? body,);+const THUMBNAIL = '/9j/4AAQSkZJRgABAQAAAQABAAD';+const revokeEvent = (client: EventEmitter, id: string, opts: { fromMe?: boolean } = {}) =>client.emit('message_revoke_everyone',@@ -280,6 +293,46 @@ describe.each([expect(events('message.received').map(m => m.body)).toEqual(['new cap']);});+ it('keeps the caption of a message whose thumbnail changed during the media download, and announces no edit', async () => {+ const media = download();+ client.emit('message', incoming('M', 'cap', { page: media.page }));+ await flush();+ editEvent(client, 'M', 'cap', { media: true, attribute: THUMBNAIL });+ await flush();+ media.finish();+ await flush();++ expect(rows).toEqual([+ expect.objectContaining({+ waMessageId: 'M',+ body: 'cap',+ metadata: { media: expect.objectContaining({ mimetype: 'image/png' }) as unknown },+ }),+ ]);+ expect(hooked).toEqual(['cap']);+ expect(events('message.received').map(m => m.body)).toEqual(['cap']);+ expect(events('message.edited')).toEqual([]);+ });++ it('keeps the stored caption of a message whose thumbnail changed, and announces no edit', async () => {+ client.emit(+ 'message',+ incoming('M', 'cap', { page: jest.fn().mockResolvedValue({ mimetype: 'image/png', data: 'QUJD' }) }),+ );+ await flush();+ expect(rows).toEqual([expect.objectContaining({ waMessageId: 'M', body: 'cap' })]);+ editEvent(client, 'M', 'cap', { media: true, attribute: THUMBNAIL });+ await flush();++ expect(rows).toEqual([+ expect.objectContaining({+ body: 'cap',+ metadata: { media: expect.objectContaining({ mimetype: 'image/png' }) as unknown },+ }),+ ]);+ expect(events('message.edited')).toEqual([]);+ });+it('applies the edits of one message in the order they arrived', async () => {const contact = deferred<null>();client.emit('message', incoming('A', 'orig', { contact: contact.promise }));diff --git a/src/engine/adapters/wwebjs-message-events.ts b/src/engine/adapters/wwebjs-message-events.tsindex 568c57ae3..9115503d6 100644--- a/src/engine/adapters/wwebjs-message-events.ts+++ b/src/engine/adapters/wwebjs-message-events.ts@@ -309,6 +309,16 @@ export function registerWwebjsMessageEvents(client: Client, host: WwebjsEngineHoclient.on('message_edit', (message, newBody) => {try {+ // Raised for any change of a message's body or caption attribute, with `message` read after it. Users edit+ // only texts and captions, and `message.body` is the text shown: for a message with a file its caption, as+ // the body attribute holds a thumbnail WhatsApp Web may replace. Any other change is no edit.+ if ((message.type !== MessageTypes.TEXT && !message.hasMedia) || String(newBody ?? '') !== message.body) {+ host.logger.debug('Ignoring a message_edit that is no edit of a text or caption', {+ msgId: message.id?._serialized,+ type: message.type,+ });+ return;+ }// whatsapp-web.js keeps `message.timestamp` at the ORIGINAL creation time. Consumers need// occurrence time for ordering multiple edits, so stamp the edit at receipt and project the// otherwise-normal message fields through the same adapter mapper used by inbound messages.@@ -317,7 +327,7 @@ export function registerWwebjsMessageEvents(client: Client, host: WwebjsEngineHoid: message.id,from: message.from,to: message.to,- body: String(newBody),+ body: message.body,type: message.type,timestamp: editTimestamp,fromMe: message.fromMe,