Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(engine): baileys contact/chat reads via in-memory session store

rmyndharis98780958bb76
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.ts
index 75e4fbb2b..47d1bdc2e 100644
--- a/src/engine/adapters/baileys.adapter.spec.ts
+++ b/src/engine/adapters/baileys.adapter.spec.ts
@@ -30,6 +30,8 @@ class FakeSock extends EventEmitter {
public groupRevokeInvite = jest.fn();
public profilePictureUrl = jest.fn();
public updateBlockStatus = jest.fn().mockResolvedValue(undefined);
+ public readMessages = jest.fn().mockResolvedValue(undefined);
+ public chatModify = jest.fn().mockResolvedValue(undefined);
fire(event: string, arg: unknown): void {
this.emitter.emit(event, arg);
}
@@ -160,9 +162,9 @@ describe('BaileysAdapter lifecycle & status', () => {
});
describe('BaileysAdapter capability gating', () => {
- it('throws EngineNotSupportedError for store-backed methods (e.g. getChats)', async () => {
+ it('throws EngineNotSupportedError for still-gated methods (e.g. sendSeen)', async () => {
const adapter = newAdapter();
- await expect(adapter.getChats()).rejects.toBeInstanceOf(EngineNotSupportedError);
+ await expect(adapter.sendSeen('[email protected]')).rejects.toBeInstanceOf(EngineNotSupportedError);
});
});
@@ -645,3 +647,70 @@ describe('BaileysAdapter profile + block', () => {
expect(fakeSock.updateBlockStatus).toHaveBeenCalledWith('[email protected]', 'unblock');
});
});
+
+describe('BaileysAdapter contact + chat reads', () => {
+ beforeEach(() => {
+ fakeSock.user = { id: '628999:[email protected]', name: 'Me' };
+ jest.clearAllMocks();
+ });
+
+ const ready = async (): Promise<BaileysAdapter> => {
+ const adapter = newAdapter();
+ await adapter.initialize({});
+ fakeSock.fire('connection.update', { connection: 'open' });
+ return adapter;
+ };
+
+ it('populates contacts from contacts.upsert and reads them', async () => {
+ const adapter = await ready();
+ fakeSock.fire('contacts.upsert', [{ id: '[email protected]', notify: 'Al' }]);
+ const contacts = await adapter.getContacts();
+ expect(contacts).toHaveLength(1);
+ expect(contacts[0]).toMatchObject({ id: '[email protected]', pushName: 'Al', number: '628111' });
+ expect((await adapter.getContactById('[email protected]'))?.number).toBe('628111');
+ expect(await adapter.getContactById('[email protected]')).toBeNull();
+ });
+
+ it('populates chats + last message and reads getChats', async () => {
+ const adapter = await ready();
+ fakeSock.fire('chats.upsert', [{ id: '[email protected]', name: 'Alice', unreadCount: 1 }]);
+ fakeSock.fire('messages.upsert', {
+ type: 'notify',
+ messages: [
+ {
+ key: { remoteJid: '[email protected]', fromMe: false, id: 'M1' },
+ message: { conversation: 'hi' },
+ messageTimestamp: 1700000010,
+ },
+ ],
+ });
+ const chats = await adapter.getChats();
+ expect(chats[0]).toEqual({
+ name: 'Alice',
+ isGroup: false,
+ unreadCount: 1,
+ timestamp: 1700000010,
+ lastMessage: 'hi',
+ });
+ });
+
+ it('populates from messaging-history.set incl. lid mappings', async () => {
+ const adapter = await ready();
+ fakeSock.fire('messaging-history.set', {
+ contacts: [{ id: '[email protected]', name: 'Bob' }],
+ chats: [{ id: '[email protected]', name: 'Bob' }],
+ messages: [],
+ lidPnMappings: [{ lid: '111@lid', pn: '[email protected]' }],
+ });
+ expect(await adapter.getContacts()).toHaveLength(1);
+ expect(await adapter.resolveContactPhone('111@lid')).toBe('628999');
+ expect(await adapter.resolveContactPhone('[email protected]')).toBe('628222');
+ });
+
+ it('contact/chat reads reject with EngineNotReadyError before connect', async () => {
+ const adapter = newAdapter();
+ await adapter.initialize({});
+ await expect(adapter.getContacts()).rejects.toBeInstanceOf(EngineNotReadyError);
+ });
+});
diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.ts
index 856ee7660..30669ec0c 100644
--- a/src/engine/adapters/baileys.adapter.ts
+++ b/src/engine/adapters/baileys.adapter.ts
@@ -40,6 +40,7 @@ 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';
import { BaileysAdapterConfig, BaileysLogger } from '../types/baileys.types';
+import { BaileysSessionStore } from './baileys-session-store';
/** Linked-device identity shown in WhatsApp (Settings → Linked Devices). */
const BAILEYS_BROWSER: [string, string, string] = ['OpenWA', 'Chrome', '120.0.0'];
@@ -62,6 +63,7 @@ function createSilentLogger(): BaileysLogger {
export class BaileysAdapter implements IWhatsAppEngine {
private readonly logger = createLogger('BaileysAdapter');
private readonly authPath: string;
+ private readonly sessionStore = new BaileysSessionStore();
private sock: WASocket | null = null;
private status: EngineStatus = EngineStatus.DISCONNECTED;
private qrCode: string | null = null;
@@ -112,6 +114,18 @@ export class BaileysAdapter implements IWhatsAppEngine {
sock.ev.on('connection.update', update => this.handleConnectionUpdate(update));
sock.ev.on('messages.upsert', event => this.handleMessagesUpsert(event));
sock.ev.on('messages.update', updates => this.handleMessagesUpdate(updates));
+ sock.ev.on('contacts.upsert', contacts => this.sessionStore.upsertContacts(contacts));
+ sock.ev.on('contacts.update', updates => this.sessionStore.upsertContacts(updates));
+ sock.ev.on('chats.upsert', chats => this.sessionStore.upsertChats(chats));
+ sock.ev.on('chats.update', updates => this.sessionStore.upsertChats(updates));
+ sock.ev.on('messaging-history.set', history => {
+ this.sessionStore.upsertContacts(history.contacts);
+ this.sessionStore.upsertChats(history.chats);
+ // lidPnMappings is not in the installed @whiskeysockets/[email protected] type definition but
+ // is present at runtime in later protocol versions; cast to access it safely.
+ const lidPnMappings = (history as unknown as { lidPnMappings?: { lid: string; pn: string }[] }).lidPnMappings;
+ this.sessionStore.addLidMappings(lidPnMappings ?? []);
+ });
}
private handleConnectionUpdate(update: {
@@ -433,21 +447,50 @@ export class BaileysAdapter implements IWhatsAppEngine {
await this.sock!.updateBlockStatus(contactId, 'unblock');
}
+ // ----- Contacts & chats -----
+
+ getContacts(): Promise<Contact[]> {
+ try {
+ this.ensureReady();
+ return Promise.resolve(this.sessionStore.listContacts());
+ } catch (e) {
+ return Promise.reject(e as Error);
+ }
+ }
+
+ getContactById(contactId: string): Promise<Contact | null> {
+ try {
+ this.ensureReady();
+ return Promise.resolve(this.sessionStore.findContact(contactId));
+ } catch (e) {
+ return Promise.reject(e as Error);
+ }
+ }
+
+ resolveContactPhone(contactId: string): Promise<string | null> {
+ try {
+ this.ensureReady();
+ return Promise.resolve(this.sessionStore.resolvePhone(contactId));
+ } catch (e) {
+ return Promise.reject(e as Error);
+ }
+ }
+
+ getChats(): Promise<ChatSummary[]> {
+ try {
+ this.ensureReady();
+ return Promise.resolve(this.sessionStore.listChats());
+ } catch (e) {
+ return Promise.reject(e as Error);
+ }
+ }
+
// ----- Gated: not supported by this minimal slice (no store) -----
/* eslint-disable @typescript-eslint/no-unused-vars */
getMessageReactions(_chatId: string, _messageId: string): Promise<MessageReaction[]> {
return this.unsupported('getMessageReactions');
}
- getContacts(): Promise<Contact[]> {
- return this.unsupported('getContacts');
- }
- getContactById(_contactId: string): Promise<Contact | null> {
- return this.unsupported('getContactById');
- }
- resolveContactPhone(_contactId: string): Promise<string | null> {
- return this.unsupported('resolveContactPhone');
- }
getChatHistory(_chatId: string, _limit?: number, _includeMedia?: boolean): Promise<IncomingMessage[]> {
return this.unsupported('getChatHistory');
}
@@ -514,9 +557,6 @@ export class BaileysAdapter implements IWhatsAppEngine {
sendCatalog(_chatId: string, _body?: string): Promise<MessageResult> {
return this.unsupported('sendCatalog');
}
- getChats(): Promise<ChatSummary[]> {
- return this.unsupported('getChats');
- }
sendSeen(_chatId: string): Promise<boolean> {
return this.unsupported('sendSeen');
}
@@ -547,6 +587,7 @@ export class BaileysAdapter implements IWhatsAppEngine {
error: err instanceof Error ? err.message : String(err),
}),
);
+ this.sessionStore.recordMessage(msg);
}
}