Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(status): seed pre-connect statuses from the status-broadcast history

Yudhi Armyndharisa814dabcd353
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index 080d4c707..742eed58f 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -122,6 +122,8 @@ describe('SessionService', () => {
resolveContactPhone: jest.fn().mockResolvedValue('628111222333'),
rejectCall: jest.fn().mockResolvedValue(undefined),
getContactStatuses: jest.fn().mockResolvedValue([]),
+ getChatHistory: jest.fn().mockResolvedValue([]),
+ getContactById: jest.fn().mockResolvedValue(null),
};
engineFactory = {
@@ -2600,31 +2602,67 @@ describe('SessionService', () => {
expect(auth[0][2]).toMatchObject({ sessionId: 'sess-uuid-1', phone: '628123', pushName: 'Alice' });
});
- it('seeds the status store from engine.getContactStatuses() when the engine reports ready', async () => {
+ it('seeds the status store from the status-broadcast chat history when the engine reports ready', async () => {
const callbacks = await startAndCaptureCallbacks();
- mockEngine.getContactStatuses.mockResolvedValue([
- {
+ mockEngine.getChatHistory.mockResolvedValue([
+ makeMessage({
id: 'st-a',
- contact: { id: '[email protected]', name: 'Alice', pushName: 'Ali' },
+ from: 'status@broadcast',
+ chatId: 'status@broadcast',
+ isStatusBroadcast: true,
+ author: '[email protected]',
+ kind: 'status',
type: 'text',
- caption: 'hi',
- backgroundColor: '#fff',
- font: 1,
- timestamp: new Date(1700000000000),
- expiresAt: new Date(1700086400000),
- },
- {
+ body: 'hi',
+ timestamp: 1700000000,
+ contact: { id: '[email protected]', name: 'Alice', pushName: 'Ali' },
+ }),
+ makeMessage({
id: 'st-b',
- contact: { id: '[email protected]' },
+ from: 'status@broadcast',
+ chatId: 'status@broadcast',
+ isStatusBroadcast: true,
+ author: '[email protected]',
+ kind: 'status',
type: 'image',
- timestamp: new Date(1700000001000),
- expiresAt: new Date(1700086401000),
- },
+ body: '',
+ timestamp: 1700000001,
+ }),
+ // Poster resolves to the shared pseudo-JID → buildIncomingStatus returns null → never ingested.
+ makeMessage({
+ id: 'st-self',
+ from: 'status@broadcast',
+ chatId: 'status@broadcast',
+ isStatusBroadcast: true,
+ author: 'status@broadcast',
+ kind: 'status',
+ type: 'text',
+ }),
]);
+ // st-b's message carries no cached contact name; the seed resolves it via getContactById.
+ mockEngine.getContactById.mockImplementation((jid: string) =>
+ Promise.resolve(
+ jid === '[email protected]'
+ ? {
+ name: 'Bob',
+ pushName: 'Bobby',
+ number: '628222',
+ isMyContact: true,
+ isBlocked: false,
+ }
+ : null,
+ ),
+ );
callbacks.onReady!('628123', 'Alice');
await flush();
+ // Reads the status-broadcast chat's own messages (with media), not the near-empty-at-ready
+ // getBroadcasts collection.
+ expect(mockEngine.getChatHistory).toHaveBeenCalledWith('status@broadcast', 50, true);
+ expect(mockEngine.getContactStatuses).not.toHaveBeenCalled();
+ // Two usable statuses ingested; the pseudo-JID poster is filtered out.
expect(statusStore.ingest).toHaveBeenCalledTimes(2);
expect(statusStore.ingest).toHaveBeenNthCalledWith(
1,
@@ -2636,30 +2674,42 @@ describe('SessionService', () => {
contactPushName: 'Ali',
type: 'text',
caption: 'hi',
- backgroundColor: '#fff',
- font: 1,
postedAt: 1700000000000,
}),
);
+ // st-b had no cached name, so the seed backfilled it from getContactById.
expect(statusStore.ingest).toHaveBeenNthCalledWith(
2,
'sess-uuid-1',
- expect.objectContaining({ waStatusId: 'st-b', contactJid: '[email protected]', type: 'image' }),
+ expect.objectContaining({
+ waStatusId: 'st-b',
+ contactJid: '[email protected]',
+ type: 'image',
+ contactName: 'Bob',
+ contactPushName: 'Bobby',
+ }),
);
+ // The lookup runs only for the poster that lacked a name; st-a already had one.
+ expect(mockEngine.getContactById).toHaveBeenCalledWith('[email protected]');
+ expect(mockEngine.getContactById).not.toHaveBeenCalledWith('[email protected]');
});
- it('passes engine-supplied status media through to statusStore.ingest (seeded media renders like live)', async () => {
+ it('seeds status media downloaded with the history so it renders like a live post', async () => {
const callbacks = await startAndCaptureCallbacks();
const media = { mimetype: 'image/png', data: 'QUJD' };
- mockEngine.getContactStatuses.mockResolvedValue([
- {
+ mockEngine.getChatHistory.mockResolvedValue([
+ makeMessage({
id: 'st-c',
- contact: { id: '[email protected]' },
+ from: 'status@broadcast',
+ chatId: 'status@broadcast',
+ isStatusBroadcast: true,
+ author: '[email protected]',
+ kind: 'status',
type: 'image',
- timestamp: new Date(1700000002000),
- expiresAt: new Date(1700086402000),
+ body: '',
+ timestamp: 1700000002,
media,
- },
+ }),
]);
callbacks.onReady!('628123', 'Alice');
@@ -2671,9 +2721,9 @@ describe('SessionService', () => {
);
});
- it('swallows a getContactStatuses failure on ready (e.g. Baileys EngineNotSupportedError) without throwing', async () => {
+ it('swallows a status-history failure on ready (e.g. Baileys has no status chat) without throwing', async () => {
const callbacks = await startAndCaptureCallbacks();
- mockEngine.getContactStatuses.mockRejectedValue(new Error('not supported'));
+ mockEngine.getChatHistory.mockRejectedValue(new Error('not supported'));
expect(() => callbacks.onReady!('628123', 'Alice')).not.toThrow();
await flush();
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index 9591a1c2d..8daa69ea5 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -64,6 +64,12 @@ import {
// history sync) get the omitted marker synthesized at the persistence chokepoints.
const MEDIA_MESSAGE_TYPES = new Set(['image', 'video', 'audio', 'voice', 'sticker', 'document']);
+// How many recent status-broadcast messages the connect-time seed pulls (each with its media).
+// ponytail: fixed ceiling — the most-recent 50 cover a normal account's 24h of stories; anything
+// posted after connect still lands live via onMessage. Make it configurable only if a flood account
+// proves 50 too few.
+const STATUS_SEED_LIMIT = 50;
+
interface ReconnectState {
attempts: number;
timer: NodeJS.Timeout | null;
@@ -658,22 +664,43 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
*/
private async seedStatuses(sessionId: string, engine: IWhatsAppEngine): Promise<void> {
try {
- const statuses = await engine.getContactStatuses();
- for (const s of statuses) {
- await this.statusStore.ingest(sessionId, {
- waStatusId: s.id,
- contactJid: s.contact.id,
- contactName: s.contact.name,
- contactPushName: s.contact.pushName,
- type: s.type,
- caption: s.caption,
- backgroundColor: s.backgroundColor,
- font: s.font,
- // Seed now downloads media the same way the live onMessage path does (collectStatuses calls
- // capInboundMediaFor), so a status active at connect time renders like one that arrives live.
- media: s.media,
- postedAt: s.timestamp.getTime(),
- });
+ // Read the status-broadcast chat's own recent messages rather than getContactStatuses(): on
+ // whatsapp-web.js the latter reads the StatusV3 collection, which loads asynchronously and is
+ // near-empty right after ready, so a status posted before connect would silently never reach the
+ // store. Fetching the chat's messages (the same on-demand fetch the chat-history endpoint uses)
+ // reliably returns the currently-active statuses with downloadable media/video, and each maps
+ // through the very buildIncomingStatus the live onMessage path uses — so a seeded status is
+ // indistinguishable from one that arrives live. No status.received webhook is dispatched here:
+ // this is a backfill of posts that predate the connection, not a live arrival.
+ const messages = await engine.getChatHistory('status@broadcast', STATUS_SEED_LIMIT, true);
+ // getChatHistory maps a message's contact from the sync cache only, so status posters (usually
+ // @lid ids) come back nameless. Resolve each unique poster once via getContactById — the same
+ // lookup the contacts API uses, which maps the @lid to the real contact — so a seeded status
+ // carries the poster's name like a live one does. Cached per JID: one lookup per contact, not
+ // one per status.
+ const contactNames = new Map<string, { name?: string; pushName?: string }>();
+ const resolvePoster = async (jid: string): Promise<{ name?: string; pushName?: string }> => {
+ const cached = contactNames.get(jid);
+ if (cached) return cached;
+ let resolved: { name?: string; pushName?: string } = {};
+ try {
+ const contact = await engine.getContactById(jid);
+ if (contact) resolved = { name: contact.name, pushName: contact.pushName };
+ } catch {
+ // Best-effort: a failed lookup just leaves the status nameless.
+ }
+ contactNames.set(jid, resolved);
+ return resolved;
+ };
+ for (const msg of messages) {
+ const status = buildIncomingStatus(msg);
+ if (!status) continue;
+ if (!status.contactName && !status.contactPushName) {
+ const poster = await resolvePoster(status.contactJid);
+ status.contactName = poster.name;
+ status.contactPushName = poster.pushName;
+ }
+ await this.statusStore.ingest(sessionId, status);
}
} catch (err) {
this.logger.debug('Status seed skipped', {