Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(engine): retry a wwjs profile picture by the contact's LID
Yudhi Armyndharis187a9ba12486
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.tsindex 02d91d9e7..7e30aef41 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts@@ -43,6 +43,7 @@ import { RecipientUnreachableError } from '../../common/errors/recipient-unreachimport { EditedMessage, EngineStatus, GroupEvent, IncomingCallEvent } from '../interfaces/whatsapp-engine.interface';import { EngineRefusedError } from '../../common/errors/engine-refused.error';import { EngineTransportError } from '../../common/errors/engine-transport.error';+import { readCurrentLid } from './wwebjs-contacts';import { InvalidInviteCodeError } from '../../common/errors/invalid-invite-code.error';import { GroupNotFoundError } from '../../common/errors/group-not-found.error';import { LabelNotFoundError } from '../../common/errors/label-not-found.error';@@ -9591,6 +9592,136 @@ describe('WhatsAppWebJsAdapter number check through the library page code', () =});});+/**+ * WhatsApp Web keys a migrated contact's chat by its LID, so the picture lookup by its phone id can come back+ * empty or fail where the LID form answers. The lookup is retried once by the LID the page already holds.+ */+describe('WhatsAppWebJsAdapter profile picture of a migrated contact', () => {+ const PHONE = '[email protected]';+ const LID = '159442138038327@lid';+ const URL = 'https://pps.whatsapp.net/v/avatar.jpg';+ const readyAdapter = (client: unknown): WhatsAppWebJsAdapter => {+ const adapter = new WhatsAppWebJsAdapter({ sessionId: 's', sessionDataPath: './data/sessions', puppeteer: {} });+ (adapter as unknown as { status: EngineStatus }).status = EngineStatus.READY;+ (adapter as unknown as { client: unknown }).client = client;+ return adapter;+ };+ /** A client whose picture lookup answers per id (a value, or an Error to throw), on a page holding `lid`. */+ const clientWith = (answers: Record<string, string | undefined | Error>, lid: string | null = LID) => {+ const getProfilePicUrl = jest.fn((id: string) => {+ const answer = answers[id];+ return answer instanceof Error ? Promise.reject(answer) : Promise.resolve(answer);+ });+ const evaluate = jest.fn().mockResolvedValue(lid);+ return { getProfilePicUrl, pupPage: { evaluate } };+ };++ it('answers the phone form without reading the LID when it works', async () => {+ const client = clientWith({ [PHONE]: URL });+ await expect(readyAdapter(client).getProfilePicture(PHONE)).resolves.toBe(URL);+ expect(client.pupPage.evaluate).not.toHaveBeenCalled();+ expect(client.getProfilePicUrl).toHaveBeenCalledTimes(1);+ });++ it.each([+ ['answers nothing', undefined],+ ['fails in the page', new Error("Cannot read properties of undefined (reading 'id')")],+ ])('retries by the LID when the phone form %s', async (_label, phoneAnswer) => {+ const client = clientWith({ [PHONE]: phoneAnswer, [LID]: URL });+ await expect(readyAdapter(client).getProfilePicture(PHONE)).resolves.toBe(URL);+ expect(client.pupPage.evaluate).toHaveBeenCalledWith(expect.any(Function), PHONE);+ expect(client.getProfilePicUrl.mock.calls).toEqual([[PHONE], [LID]]);+ });++ it.each([+ ['nothing, then nothing', undefined, undefined, null],+ ['nothing, then a failure', undefined, new Error('lid lookup failed'), null],+ ])('answers as before when both forms give %s', async (_label, phoneAnswer, lidAnswer, expected) => {+ const client = clientWith({ [PHONE]: phoneAnswer, [LID]: lidAnswer });+ await expect(readyAdapter(client).getProfilePicture(PHONE)).resolves.toBe(expected);+ expect(client.getProfilePicUrl).toHaveBeenCalledTimes(2);+ });++ it.each([+ ['nothing', undefined],+ ['a failure', new Error('lid lookup failed')],+ ])('answers 503 as before when the phone form fails and the LID form gives %s', async (_label, lidAnswer) => {+ const client = clientWith({ [PHONE]: new Error('phone lookup failed'), [LID]: lidAnswer });+ await expect(readyAdapter(client).getProfilePicture(PHONE)).rejects.toBeInstanceOf(EngineTransportError);+ expect(client.getProfilePicUrl).toHaveBeenCalledTimes(2);+ });++ it('reports a page that dies during the retry and keeps the first answer', async () => {+ const client = clientWith({+ [PHONE]: undefined,+ [LID]: new Error('Protocol error (Runtime.callFunctionOn): Target closed.'),+ });+ const adapter = readyAdapter(client);+ const onDisconnected = jest.fn();+ (adapter as unknown as { callbacks: unknown }).callbacks = { onDisconnected };+ await expect(adapter.getProfilePicture(PHONE)).resolves.toBeNull();+ expect(onDisconnected).toHaveBeenCalledTimes(1);+ });++ it('does not retry when the page holds no LID for the phone', async () => {+ const client = clientWith({ [PHONE]: undefined }, null);+ await expect(readyAdapter(client).getProfilePicture(PHONE)).resolves.toBeNull();+ expect(client.getProfilePicUrl).toHaveBeenCalledTimes(1);+ });++ it('does not retry after a dead page or a protocol timeout', async () => {+ for (const failure of [+ new Error('Protocol error: Connection closed. Target closed'),+ new Error("Runtime.callFunctionOn timed out. Increase the 'protocolTimeout' setting in launch/connect calls"),+ ]) {+ const client = clientWith({ [PHONE]: failure, [LID]: URL });+ await expect(readyAdapter(client).getProfilePicture(PHONE)).rejects.toBeInstanceOf(EngineTransportError);+ expect(client.pupPage.evaluate).not.toHaveBeenCalled();+ }+ });++ it.each([+ ['a group', '[email protected]'],+ ['a LID', LID],+ ])('does not retry for %s', async (_label, id) => {+ const client = clientWith({ [id]: undefined });+ await expect(readyAdapter(client).getProfilePicture(id)).resolves.toBeNull();+ expect(client.pupPage.evaluate).not.toHaveBeenCalled();+ });++ describe('readCurrentLid, the in-page read', () => {+ const g = globalThis as unknown as { window?: unknown };+ afterEach(() => {+ delete g.window;+ });+ const pageHolding = (lid: { _serialized?: string; $1?: string } | null) => {+ const queryWidExists = jest.fn();+ const getCurrentLid = jest.fn(() => lid);+ const modules: Record<string, unknown> = {+ WAWebWidFactory: { createWid: (id: string) => ({ _serialized: id }) },+ WAWebApiContact: { getCurrentLid },+ WAWebQueryExistsJob: { queryWidExists },+ };+ g.window = { require: (name: string) => modules[name] };+ return { getCurrentLid, queryWidExists };+ };++ it('reads the LID the page holds for a phone id, in either property name, and queries nothing', () => {+ const page = pageHolding({ _serialized: LID });+ expect(readCurrentLid(PHONE)).toBe(LID);+ expect(page.getCurrentLid).toHaveBeenCalledWith({ _serialized: PHONE });+ expect(page.queryWidExists).not.toHaveBeenCalled();+ pageHolding({ $1: LID });+ expect(readCurrentLid(PHONE)).toBe(LID);+ });++ it('answers null when the page holds none', () => {+ pageHolding(null);+ expect(readCurrentLid(PHONE)).toBeNull();+ });+ });+});+// A chat, contact or group id belongs to a third party, and a serialized message id embeds the chat JID:// the per-action lines keep them out of info-level output and carry them as debug metadata only.describe('WhatsAppWebJsAdapter per-action log lines', () => {diff --git a/src/engine/adapters/wwebjs-client-teardown.spec.ts b/src/engine/adapters/wwebjs-client-teardown.spec.tsindex fc5e63d25..66c3b0607 100644--- a/src/engine/adapters/wwebjs-client-teardown.spec.ts+++ b/src/engine/adapters/wwebjs-client-teardown.spec.ts@@ -181,7 +181,7 @@ const CASES: Case[] = [run: adapter => adapter.muteChat(CHAT, Date.now() + 60_000),},{- // The phone behind the lid is read after the lookup; contacts has no other read after an await.+ // The phone behind the lid is read after the lookup.name: 'a number check of a migrated contact',build: parked => {const getContactLidAndPhone = jest.fn();@@ -192,6 +192,18 @@ const CASES: Case[] = [},run: adapter => adapter.getNumberId('5511987654321'),},+ {+ // A picture lookup by phone id that came back empty is retried by the LID the page holds.+ name: 'a profile picture read retried by its LID',+ build: parked => {+ const evaluate = jest.fn();+ return {+ client: { getProfilePicUrl: () => parked.park().then(() => undefined), pupPage: { evaluate } },+ unreached: evaluate,+ };+ },+ run: adapter => adapter.getProfilePicture(CHAT),+ },{// The client is read again after the lookup, inside a catch that answers a missing group with null.name: 'a group info read',diff --git a/src/engine/adapters/wwebjs-contacts.ts b/src/engine/adapters/wwebjs-contacts.tsindex 742274b80..8fa3523bf 100644--- a/src/engine/adapters/wwebjs-contacts.ts+++ b/src/engine/adapters/wwebjs-contacts.ts@@ -89,6 +89,20 @@ export async function readLeanContacts(): Promise<LeanContactRead> {return { rows, failed, firstError };}+/**+ * Read IN-PAGE the LID WhatsApp Web already holds for a phone id, or null when it holds none. Local only:+ * unlike `client.getContactLidAndPhone`, which runs an existence query for a phone whose LID the page does+ * not know, this sends nothing to WhatsApp. Self-contained, since Puppeteer ships it to the page as source.+ */+export function readCurrentLid(phoneId: string): string | null {+ type Wid = { _serialized?: string; $1?: string };+ const w = window as unknown as {+ require: (m: string) => { createWid: (id: string) => Wid; getCurrentLid: (wid: Wid) => Wid | null | undefined };+ };+ const lid = w.require('WAWebApiContact').getCurrentLid(w.require('WAWebWidFactory').createWid(phoneId));+ return lid?._serialized || lid?.$1 || null;+}+/*** Contact operations extracted from WhatsAppWebJsAdapter. The adapter keeps the public methods as* thin forwarders and injects the shared host surface (./wwebjs-host) via closures, so the delegate@@ -347,10 +361,18 @@ export class WwebjsContacts {async getProfilePicture(contactId: string): Promise<string | null> {this.host.ensureReady();+ // WhatsApp Web keys a migrated contact's chat by its LID, so the lookup by a phone id can come back empty+ // or fail where the LID answers (the Number Checker asks by the phone id its check returned). It is+ // retried once by the LID the page holds; a dead or unanswering page is not retried, and a retry that+ // gets nothing leaves the first outcome standing.+ const byLid = parseWaId(contactId).kind === 'user';+ let url: string | undefined;try {- const url = await this.client().getProfilePicUrl(contactId);- return url || null;+ url = await this.client().getProfilePicUrl(contactId);} catch (error) {+ const pageDown = this.host.isPageTransportError(error) || isProtocolTimeout(error);+ const viaLid = byLid && !pageDown ? await this.profilePictureByLid(contactId) : undefined;+ if (viaLid) return viaLid;// Nothing reaching here is a statement about the avatar, so nothing reaching here may become// null. Returning null would answer 200 with {"url": null} — byte-identical to the verdict// above — and a caller that caches "no avatar" would record absence for a lookup that never@@ -367,5 +389,27 @@ export class WwebjsContacts {this.host.logger.warn(`Failed to get profile picture for ${contactId}: ${String(error)}`);throw new EngineTransportError(`Could not read the profile picture for ${contactId}: ${String(error)}`);}+ return url || (byLid ? await this.profilePictureByLid(contactId) : undefined) || null;+ }++ /**+ * The picture of a phone id looked up by the LID WhatsApp Web holds for it (no query is sent to find one),+ * or undefined when there is no LID or that lookup also gets nothing. A session torn down meanwhile still+ * answers 409: the client is taken through the readiness check before each page call.+ */+ private async profilePictureByLid(phoneId: string): Promise<string | undefined> {+ try {+ const page = (+ this.client() as unknown as { pupPage?: { evaluate: <T>(fn: (id: string) => T, id: string) => Promise<T> } }+ ).pupPage;+ const lid = await page?.evaluate(readCurrentLid, phoneId);+ if (!lid) return undefined;+ return (await this.client().getProfilePicUrl(lid)) || undefined;+ } catch (error) {+ if (error instanceof EngineNotReadyError) throw error;+ this.host.reportIfPageTransportError(error, 'getProfilePicture');+ this.host.logger.debug('Could not read a profile picture by its LID', { error: String(error) });+ return undefined;+ }}}