Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(messages): serve sent-message media from the row's inline copy
Yudhi Armyndhariscafd22371f82
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7fe35f071..e7d4e6d8a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Added++- **The media download route now serves media sent by the account** — `GET /messages/:chatId/:messageId/media` falls back to the inline copy stored on the message row when no archived file exists, which covers outbound messages (never archived) and inbound messages whose archived file retention has purged.+### Changed- **125 routes now document a status they could already answer** — 91 gained the `409` an unconnected session answers, plus `400` on six sends, `403` on six group and channel writes, `404` on eleven, and `501` on eleven more. A generated client had no branch for any of them.diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex bd43e5a8f..2df797215 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -1164,13 +1164,17 @@ Remove a message's pin. Takes no duration.#### GET /api/sessions/:sessionId/messages/:chatId/:messageId/media-Download a message's **archived** media bytes.--This is the read side of chat-media archiving, which is **opt-in and off by default**-(`CHAT_MEDIA_ARCHIVE_ENABLED`). When enabled, each inbound message's media is written to whatever-backs `StorageService` (local disk or S3) in addition to the inline base64 copy the message row-already carries, so it stays retrievable after delivery. With archiving off, this route answers-`404` for every message.+Download a message's **stored** media bytes.++The route serves the chat-media **archive** first, and falls back to the **inline base64 copy** on+the message row when no archived file is servable. Archiving is **opt-in and off by default**+(`CHAT_MEDIA_ARCHIVE_ENABLED`); when enabled, each inbound message's media is written to whatever+backs `StorageService` (local disk or S3) in addition to the inline copy. The inline fallback is+what makes media **sent by this account** downloadable here — outbound messages are never archived,+but their payload is stored inline (base64 API sends persist it on the send path; media composed on+a linked phone is downloaded by the engine for the own-send echo). It also keeps an inbound+message's media downloadable after `CHAT_MEDIA_ARCHIVE_TTL_DAYS` retention purges the archived+file, since retention leaves the inline copy in place.**Auth:** API key@@ -1189,9 +1193,10 @@ mimetype when it is in a conservative inert set (common image/video/audio types)content on the API origin.**Errors:** `401` missing/invalid API key, or key not scoped to this session · `404`-`No archived media for this message` — archiving was off when the message arrived, the message-carries no media, the media was above `CHAT_MEDIA_ARCHIVE_MAX_BYTES`, or-`CHAT_MEDIA_ARCHIVE_TTL_DAYS` retention has since cleared the file+`No media stored for this message` — the message carries no media, `MEDIA_DOWNLOAD_ENABLED=false`+or the media was above `MEDIA_DOWNLOAD_MAX_BYTES` when it was stored (the row holds a size-only+marker), it was a URL-based API send (the gateway fetches those bytes at send time and never stores+them), or the message is not in this gateway's history (e.g. history backfill, which is media-free)Note: this is a three-path-segment route, so it never collides with the two-segment`GET /messages/:chatId/history` regardless of declaration order.diff --git a/docs/07-api-collection.md b/docs/07-api-collection.mdindex 7d1d66370..75137a7e9 100644--- a/docs/07-api-collection.md+++ b/docs/07-api-collection.md@@ -314,8 +314,9 @@ curl -X POST "$BASE/api/sessions/$SESSION_ID/messages/unpin" \#### GET /api/sessions/:sessionId/messages/:chatId/:messageId/media-Download a message's archived media. Requires `CHAT_MEDIA_ARCHIVE_ENABLED=true` to have been set-when the message arrived; `404` otherwise.+Download a message's stored media: the archived file when one exists+(`CHAT_MEDIA_ARCHIVE_ENABLED=true` when the message arrived), else the inline copy on the message+row — which covers media sent by this account; `404` when neither holds bytes.```bashcurl "$BASE/api/sessions/$SESSION_ID/messages/[email protected]/[email protected]_3EB0ABCD/media" \diff --git a/openapi.json b/openapi.jsonindex e86fe5d4e..14d3cb0ad 100644--- a/openapi.json+++ b/openapi.json@@ -2791,7 +2791,7 @@],"responses": {"200": {- "description": "The archived media bytes, served as an attachment.",+ "description": "The media bytes — the archived file when one exists, else the inline copy stored on the message row (which is how media sent by this account is served) — as an attachment.","content": {"application/octet-stream": {"schema": {@@ -2802,10 +2802,10 @@}},"404": {- "description": "Nothing archived for this message — archiving was off when it arrived, the message carries no media, the media was above the archive cap, retention has since cleared it, or the message was sent BY this account (only inbound media is archived)."+ "description": "No stored media for this message — it carries no media, media download was disabled or the payload was over the cap when it was stored (size-only marker), it was a URL-based API send (those bytes are never stored), or the message is not in this gateway’s history."}},- "summary": "Download a message’s archived media",+ "summary": "Download a message’s stored media","tags": ["messages"]diff --git a/sdk/go/messages.go b/sdk/go/messages.goindex e750e8f98..9fb2e6edb 100644--- a/sdk/go/messages.go+++ b/sdk/go/messages.go@@ -173,9 +173,10 @@ func (s *MessagesService) Unpin(ctx context.Context, sessionID string, body Unpireturn &out, nil}-// Media fetches a message's archived media bytes. The server answers 404 when-// nothing is archived for the message (archiving off when it arrived, no media,-// over the archive cap, or cleared by retention).+// Media fetches a message's stored media bytes: the archived file when one+// exists, else the inline copy on the message row — which covers media sent by+// this account. The server answers 404 when neither holds bytes (no media, a+// size-only marker, or a URL-based send whose bytes were never stored).func (s *MessagesService) Media(ctx context.Context, sessionID, chatID, messageID string) (*MessageMedia, error) {path := s.base(sessionID) + "/" + pathEscape(chatID) + "/" + pathEscape(messageID) + "/media"data, contentType, err := s.client.doRaw(ctx, "GET", path, nil, nil)diff --git a/sdk/go/types_message.go b/sdk/go/types_message.goindex 2ce014e5f..d7a2c6116 100644--- a/sdk/go/types_message.go+++ b/sdk/go/types_message.go@@ -331,7 +331,7 @@ type BatchStatusResponse struct {CompletedAt string `json:"completedAt,omitempty"`}-// MessageMedia is a message's archived media: the raw bytes plus the served+// MessageMedia is a message's stored media: the raw bytes plus the served// content type. Non-JSON on the wire, like StatusMedia.type MessageMedia struct {Data []bytediff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/resources/MessagesResource.java b/sdk/java/src/main/java/com/rmyndharis/openwa/resources/MessagesResource.javaindex 4512affb7..5c54d24bc 100644--- a/sdk/java/src/main/java/com/rmyndharis/openwa/resources/MessagesResource.java+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/resources/MessagesResource.java@@ -237,7 +237,8 @@ public final class MessagesResource {}/**- * Fetch a message's archived media bytes (404 when nothing is archived for it).+ * Fetch a message's stored media bytes: the archived file when one exists, else the inline+ * copy on the message row (covers media sent by this account); 404 when neither holds bytes.*/public BinaryResponse media(String sessionId, String chatId, String messageId) {return client.requestBytes(diff --git a/sdk/javascript/src/resources/messages.ts b/sdk/javascript/src/resources/messages.tsindex b21576c9f..b9ee8b114 100644--- a/sdk/javascript/src/resources/messages.ts+++ b/sdk/javascript/src/resources/messages.ts@@ -228,8 +228,8 @@ export class MessagesResource {}/**- * Fetch a message's archived media bytes. Requires chat-media archiving to have been enabled on- * the gateway when the message arrived; 404 otherwise.+ * Fetch a message's stored media bytes: the archived file when one exists, else the inline copy+ * on the message row — which covers media sent by this account; 404 when neither holds bytes.*/media(sessionId: string, chatId: string, messageId: string): Promise<BinaryResponse> {return this.client.requestBytes({diff --git a/sdk/php/src/Resources/MessagesResource.php b/sdk/php/src/Resources/MessagesResource.phpindex 82d5c5275..58e0d6ac6 100644--- a/sdk/php/src/Resources/MessagesResource.php+++ b/sdk/php/src/Resources/MessagesResource.php@@ -208,7 +208,8 @@ class MessagesResource}/**- * Fetch a message's archived media bytes (404 when nothing is archived for it).+ * Fetch a message's stored media bytes: the archived file when one exists, else the inline+ * copy on the message row (covers media sent by this account); 404 when neither holds bytes.** @return array{data: string, contentType: ?string}*/diff --git a/sdk/python/openwa/resources/messages.py b/sdk/python/openwa/resources/messages.pyindex 9391c44bf..d90fccef6 100644--- a/sdk/python/openwa/resources/messages.py+++ b/sdk/python/openwa/resources/messages.py@@ -128,7 +128,9 @@ class MessagesResource:return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/messages/unpin", body=body)def media(self, session_id: str, chat_id: str, message_id: str) -> MessageMedia:- """Fetch a message's archived media bytes (404 when nothing is archived for it)."""+ """Fetch a message's stored media bytes: the archived file when one exists, else the+ inline copy on the message row (covers media sent by this account); 404 when neither+ holds bytes."""data, content_type = self._http.request_bytes("GET",f"/api/sessions/{quote_segment(session_id)}/messages/{quote_segment(chat_id)}/{quote_segment(message_id)}/media",diff --git a/sdk/python/openwa/types.py b/sdk/python/openwa/types.pyindex 5d3b4ed52..7e5d3179b 100644--- a/sdk/python/openwa/types.py+++ b/sdk/python/openwa/types.py@@ -838,7 +838,7 @@ class UnpinMessageRequest(TypedDict):class MessageMedia(TypedDict):- """A message's archived media file: raw bytes plus the served content type."""+ """A message's stored media: raw bytes plus the served content type."""data: bytescontentType: str | Nonediff --git a/src/modules/message/message.controller.ts b/src/modules/message/message.controller.tsindex df7706da7..dcfe62587 100644--- a/src/modules/message/message.controller.ts+++ b/src/modules/message/message.controller.ts@@ -417,21 +417,23 @@ export class MessageController {// Three path segments, so it never collides with `:chatId/history` (two) regardless of// declaration order — Nest/Express match on segment count first.@Get(':chatId/:messageId/media')- @ApiOperation({ summary: 'Download a message’s archived media' })+ @ApiOperation({ summary: 'Download a message’s stored media' })@ApiParam({ name: 'sessionId', description: 'Session ID' })@ApiParam({ name: 'chatId', description: 'Chat ID containing the message' })@ApiParam({ name: 'messageId', description: 'WhatsApp message ID whose media to download' })@ApiResponse({status: 200,- description: 'The archived media bytes, served as an attachment.',+ description:+ 'The media bytes — the archived file when one exists, else the inline copy stored on the ' ++ 'message row (which is how media sent by this account is served) — as an attachment.',content: { 'application/octet-stream': { schema: { type: 'string', format: 'binary' } } },})@ApiResponse({status: 404,description:- 'Nothing archived for this message — archiving was off when it arrived, the message carries no ' +- 'media, the media was above the archive cap, retention has since cleared it, or the message ' +- 'was sent BY this account (only inbound media is archived).',+ 'No stored media for this message — it carries no media, media download was disabled or the ' ++ 'payload was over the cap when it was stored (size-only marker), it was a URL-based API send ' ++ '(those bytes are never stored), or the message is not in this gateway’s history.',})async getChatMedia(@Param('sessionId') sessionId: string,diff --git a/src/modules/message/message.service.spec.ts b/src/modules/message/message.service.spec.tsindex 723b98f71..08b734c43 100644--- a/src/modules/message/message.service.spec.ts+++ b/src/modules/message/message.service.spec.ts@@ -1633,5 +1633,70 @@ describe('MessageService', () => {const svc = build(archived('image/png'), { getFile: jest.fn().mockRejectedValue(new Error('S3 500')) });await expect(svc.getChatMedia('sess-1', '[email protected]', 'wa-1')).rejects.toThrow('S3 500');});++ // ── inline fallback (sent-message media, #1165) ──────────────────++ const inlineRow = (media: Record<string, unknown>) => ({ id: 'msg-uuid-1', metadata: { media } });+ const noArchive = () => ({ getMedia: jest.fn().mockResolvedValue(null) });++ it('serves the inline row copy when nothing is archived', async () => {+ (repository.findOne as jest.Mock).mockResolvedValue(+ inlineRow({ mimetype: 'image/jpeg', data: Buffer.from('INLINE').toString('base64') }),+ );+ const svc = build(noArchive(), storage());+ await expect(svc.getChatMedia('sess-1', '[email protected]', 'wa-1')).resolves.toEqual({+ buffer: Buffer.from('INLINE'),+ mimetype: 'image/jpeg',+ });+ expect(repository.findOne).toHaveBeenCalledWith({+ where: { sessionId: 'sess-1', chatId: '[email protected]', waMessageId: 'wa-1' },+ });+ });++ it('downgrades an active inline mimetype to octet-stream, matching the archive path', async () => {+ (repository.findOne as jest.Mock).mockResolvedValue(+ inlineRow({ mimetype: 'text/html', data: Buffer.from('<img>').toString('base64') }),+ );+ const svc = build(noArchive(), storage());+ const { mimetype: served } = await svc.getChatMedia('sess-1', '[email protected]', 'wa-1');+ expect(served).toBe('application/octet-stream');+ });++ it.each([+ // A URL-based send persists the URL STRING in metadata.media.data (buildMediaInput:+ // `data: base64 || dto.url!`) — decoding it as base64 would serve garbage bytes.+ ['a URL string from a url-based send', { mimetype: 'image/png', data: 'https://example.com/cat.png' }],+ ['the omitted marker', { mimetype: 'image/png', omitted: true, sizeBytes: 99 }],+ ['a payload with no mimetype', { data: Buffer.from('X').toString('base64') }],+ ['a media object with no data', { mimetype: 'image/png' }],+ ])('404s when the inline copy is %s', async (_label, media) => {+ (repository.findOne as jest.Mock).mockResolvedValue(inlineRow(media));+ const svc = build(noArchive(), storage());+ await expect(svc.getChatMedia('sess-1', '[email protected]', 'wa-1')).rejects.toThrow(NotFoundException);+ });++ it('falls back to the inline copy when the archived file was purged by retention', async () => {+ (repository.findOne as jest.Mock).mockResolvedValue(+ inlineRow({ mimetype: 'image/jpeg', data: Buffer.from('STILL-HERE').toString('base64') }),+ );+ const svc = build(archived('image/jpeg'), {+ getFile: jest.fn().mockRejectedValue(Object.assign(new Error('missing'), { code: 'ENOENT' })),+ });+ await expect(svc.getChatMedia('sess-1', '[email protected]', 'wa-1')).resolves.toEqual({+ buffer: Buffer.from('STILL-HERE'),+ mimetype: 'image/jpeg',+ });+ });++ it('serves the inline copy when no storage backend is configured', async () => {+ (repository.findOne as jest.Mock).mockResolvedValue(+ inlineRow({ mimetype: 'image/jpeg', data: Buffer.from('INLINE').toString('base64') }),+ );+ const svc = build(archived('image/jpeg'), undefined);+ await expect(svc.getChatMedia('sess-1', '[email protected]', 'wa-1')).resolves.toEqual({+ buffer: Buffer.from('INLINE'),+ mimetype: 'image/jpeg',+ });+ });});});diff --git a/src/modules/message/message.service.ts b/src/modules/message/message.service.tsindex ae8a29356..abf14ec95 100644--- a/src/modules/message/message.service.ts+++ b/src/modules/message/message.service.ts@@ -761,7 +761,12 @@ export class MessageService {}/**- * Read a message's archived media back out of the file store.+ * 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.** 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@@ -774,20 +779,35 @@ export class MessageService {messageId: string,): Promise<{ buffer: Buffer; mimetype: string }> {const media = await this.chatMediaArchive?.getMedia(sessionId, chatId, messageId);- if (!media || !this.storageService) {- throw new NotFoundException('No archived media for this message');- }- try {- const buffer = await this.storageService.getFile(media.path);- return { buffer, mimetype: inertMimetype(media.mimetype) };- } catch (error) {- // The row outlived its file: the retention purge (or a concurrent delete) removed it between- // the DB read and this read. That's "gone", not a server fault — surface a 404.- if (isMissingObjectError(error)) {- throw new NotFoundException('No archived media for this message');+ if (media && this.storageService) {+ try {+ return { buffer: await this.storageService.getFile(media.path), mimetype: inertMimetype(media.mimetype) };+ } catch (error) {+ // The row outlived its file: the retention purge (or a concurrent delete) removed it+ // between the DB read and this read. Not a server fault — try the inline copy instead.+ if (!isMissingObjectError(error)) {+ throw error;+ }}- throw error;}++ const row = await this.messageRepository.findOne({ where: { sessionId, chatId, waMessageId: messageId } });+ const inline = (row?.metadata as { media?: { data?: unknown; mimetype?: unknown; omitted?: unknown } })?.media;+ if (+ !inline ||+ inline.omitted ||+ typeof inline.data !== 'string' ||+ !inline.data ||+ typeof inline.mimetype !== 'string' ||+ !inline.mimetype ||+ // A URL-based send persists the URL STRING as `data` (buildMediaInput: `data: base64 ||+ // dto.url!`) — the bytes were fetched at send time and never stored. Decoding the URL as+ // base64 would serve garbage, so report it as absent. Same discriminator as the send path.+ /^https?:\/\//i.test(inline.data)+ ) {+ throw new NotFoundException('No media stored for this message');+ }+ return { buffer: Buffer.from(inline.data, 'base64'), mimetype: inertMimetype(inline.mimetype) };}/** Maximum messages a single getChatHistory call may request from the engine. */