Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(messages): match the media fallback across chatId dialects

Yudhi Armyndharisa673726868f5
diff --git a/.env.example b/.env.example
index 685074307..87a9161c5 100644
--- a/.env.example
+++ b/.env.example
@@ -452,10 +452,12 @@ WEBHOOK_SSRF_PROTECT=true
# it is deleted. Non-positive/garbage values fall back to the defaults.
# STATUS_ORPHAN_SWEEP_INTERVAL_MS=3600000 # default 1h
# STATUS_ORPHAN_GRACE_MS=3600000 # default 1h
-# Chat-media archiving (opt-in). When enabled, each message's media is also written to the file
-# store (local or S3) and served by GET /sessions/:id/messages/:chatId/:messageId/media, so it stays
-# retrievable after delivery. The inline base64 copy on the message row is KEPT, so archiving
-# roughly doubles storage for media under the cap — hence off by default.
+# Chat-media archiving (opt-in). When enabled, each inbound message's media is also written to the
+# file store (local or S3) as a durable copy with its own lifecycle (S3 portability, TTL retention).
+# The media download route GET /sessions/:id/messages/:chatId/:messageId/media serves the archived
+# file first and falls back to the inline base64 copy on the message row, so retrievability does not
+# require archiving. The inline copy is KEPT, so archiving roughly doubles storage for media under
+# the cap — hence off by default.
# CHAT_MEDIA_ARCHIVE_ENABLED=false # default false
# Per-file cap on archived chat media. Media above it is simply not archived; the message row and
# its inline copy are unaffected. A non-positive/garbage value falls back.
diff --git a/src/modules/message/message.service.spec.ts b/src/modules/message/message.service.spec.ts
index 08b734c43..1aa32260e 100644
--- a/src/modules/message/message.service.spec.ts
+++ b/src/modules/message/message.service.spec.ts
@@ -1,6 +1,6 @@
import { Test, TestingModule } from '@nestjs/testing';
import { getRepositoryToken } from '@nestjs/typeorm';
-import { Repository } from 'typeorm';
+import { In, Repository } from 'typeorm';
import { BadRequestException, NotFoundException, PayloadTooLargeException } from '@nestjs/common';
import { MessageService } from './message.service';
import { Message, MessageDirection, MessageStatus } from './entities/message.entity';
@@ -1649,7 +1649,36 @@ describe('MessageService', () => {
mimetype: 'image/jpeg',
});
expect(repository.findOne).toHaveBeenCalledWith({
- where: { sessionId: 'sess-1', chatId: '[email protected]', waMessageId: 'wa-1' },
+ where: { sessionId: 'sess-1', chatId: In(['[email protected]', '[email protected]']), waMessageId: 'wa-1' },
+ });
+ });
+
+ it('looks the row up across chatId dialects — outbound rows store the literal or the neutral form by race', async () => {
+ (repository.findOne as jest.Mock).mockResolvedValue(
+ inlineRow({ mimetype: 'image/jpeg', data: Buffer.from('SENT').toString('base64') }),
+ );
+ const svc = build(noArchive(), storage());
+ await expect(svc.getChatMedia('sess-1', '[email protected]', 'wa-1')).resolves.toEqual({
+ buffer: Buffer.from('SENT'),
+ mimetype: 'image/jpeg',
+ });
+ expect(repository.findOne).toHaveBeenCalledWith({
+ where: {
+ sessionId: 'sess-1',
+ waMessageId: 'wa-1',
+ },
+ });
+ });
+
+ it('prefers the archived file over the inline copy when both exist', async () => {
+ (repository.findOne as jest.Mock).mockResolvedValue(
+ inlineRow({ mimetype: 'image/png', data: Buffer.from('INLINE').toString('base64') }),
+ );
+ const svc = build(archived('image/png'), storage(Buffer.from('ARCHIVE-BYTES')));
+ await expect(svc.getChatMedia('sess-1', '[email protected]', 'wa-1')).resolves.toEqual({
+ buffer: Buffer.from('ARCHIVE-BYTES'),
+ mimetype: 'image/png',
});
});
diff --git a/src/modules/message/message.service.ts b/src/modules/message/message.service.ts
index abf14ec95..159e4f6d6 100644
--- a/src/modules/message/message.service.ts
+++ b/src/modules/message/message.service.ts
@@ -1,7 +1,7 @@
import { Injectable, BadRequestException, NotFoundException, Optional } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { InjectRepository } from '@nestjs/typeorm';
-import { Repository } from 'typeorm';
+import { In, Repository } from 'typeorm';
import { QueryDeepPartialEntity } from 'typeorm';
import { SessionService } from '../session/session.service';
import { EngineRegistry } from '../../engine/engine-registry.service';
@@ -84,8 +84,8 @@ export class MessageService {
private readonly pacing: SendPacingService,
@Optional()
private readonly configService?: ConfigService,
- // Optional so the existing standalone constructions keep working; absent means the archive
- // read endpoint reports "nothing archived", which is also what a disabled archive reports.
+ // Optional so the existing standalone constructions keep working; absent (like a disabled
+ // archive) means the media read endpoint serves only the inline row copy, never archived files.
@Optional()
private readonly chatMediaArchive?: ChatMediaArchiveService,
@Optional()
@@ -763,10 +763,11 @@ export class MessageService {
/**
* Read a message's media: the archived file when one exists, else the inline copy persisted on
* the message row. The fallback is what makes media sent BY the account retrievable here — the
- * archive is written only on the inbound path, but outbound rows carry the payload inline
- * (the REST send persists it, and both engines download it for the own-send echo) — #1165. It
- * also serves an inbound message whose archived file was purged by retention while the inline
- * copy lives on.
+ * archive is written only on the inbound path, but outbound rows carry the payload inline: the
+ * REST send persists it, wwjs downloads it for the own-send echo, and Baileys downloads it for
+ * phone-composed fromMe messages (the Baileys API-send echo alone carries only a marker, which
+ * the REST-persisted copy covers) — #1165. It also serves an inbound message whose archived file
+ * was purged by retention while the inline copy lives on.
*
* Unlike status media (only ever an image or video), chat media includes documents a sender chose
* the type of — so the declared mimetype is echoed back only when it is inert, and the caller
@@ -791,7 +792,12 @@ export class MessageService {
}
}
- const row = await this.messageRepository.findOne({ where: { sessionId, chatId, waMessageId: messageId } });
+ // Match across dialects like getMessages does: an outbound row stores the caller's literal
+ // chatId (REST persist) or the engine-neutral form (own-send echo) depending on which writer
+ // won the persist race, so a literal match would 404 on half the rows this fallback exists for.
+ const row = await this.messageRepository.findOne({
+ where: { sessionId, chatId: In(this.resolveJidCandidates(chatId)), waMessageId: messageId },
+ });
const inline = (row?.metadata as { media?: { data?: unknown; mimetype?: unknown; omitted?: unknown } })?.media;
if (
!inline ||