Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(api): let a message list caller opt out of inline media

Yudhi Armyndharis49f727744db3
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ed0912897..3b452c36a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
+- `GET /sessions/{sessionId}/messages` accepts `inlineMedia=false`, which omits every inline media
+ payload and leaves each row's `{ omitted, sizeBytes }` marker plus the media endpoint. The budget
+ bounds one response, so a paged walk pulls up to 8 MiB of base64 per page; a client reading many
+ pages can now ask for the rows without the bytes
+ ([#1516](https://github.com/rmyndharis/OpenWA/issues/1516)).
- `GET /sessions/{sessionId}/messages` accepts `after`, a keyset cursor holding the `id` of the last
message of the previous page. It anchors the window to a row instead of a count, so a message
arriving mid-walk can no longer shift it and make a page repeat or skip rows. `offset` keeps
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index 12f99ecaf..3c46eab19 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -1207,13 +1207,14 @@ Get persisted message history for a session from the local DB (paginated, filter
**Query parameters**
-| Name | Type | Required | Default | Description |
-| ------ | ------- | -------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| chatId | string | No | — | Filter by chat ID. Matched across `@c.us` / `@s.whatsapp.net` dialects via the lid-mapping table. |
-| from | string | No | — | Filter by sender. A phone also matches any lid that resolves to it. |
-| limit | integer | No | 50 | Clamped to `[1,100]`; a non-finite value falls back to 50. |
-| offset | integer | No | 0 | Clamped to `>=0`; a non-finite value falls back to 0. |
-| after | string | No | — | Keyset cursor: the `id` of the last message of the previous page. Anchors the window to a row rather than a count, so a message arriving mid-walk cannot shift it. Takes precedence over `offset`. Unknown in this session gives `400`. |
+| Name | Type | Required | Default | Description |
+| ----------- | ------- | -------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| chatId | string | No | — | Filter by chat ID. Matched across `@c.us` / `@s.whatsapp.net` dialects via the lid-mapping table. |
+| from | string | No | — | Filter by sender. A phone also matches any lid that resolves to it. |
+| limit | integer | No | 50 | Clamped to `[1,100]`; a non-finite value falls back to 50. |
+| offset | integer | No | 0 | Clamped to `>=0`; a non-finite value falls back to 0. |
+| after | string | No | — | Keyset cursor: the `id` of the last message of the previous page. Anchors the window to a row rather than a count, so a message arriving mid-walk cannot shift it. Takes precedence over `offset`. Unknown in this session gives `400`. |
+| inlineMedia | boolean | No | true | Set `false` (or `0`) to omit every inline media payload, leaving each row's `{ omitted, sizeBytes }` marker and the media endpoint. The budget below is per response, so a paged walk pulls it afresh on every page. |
**Response** `200`
diff --git a/openapi.json b/openapi.json
index 3b57ac85b..323a41f47 100644
--- a/openapi.json
+++ b/openapi.json
@@ -2306,6 +2306,15 @@
"schema": {
"type": "string"
}
+ },
+ {
+ "name": "inlineMedia",
+ "required": false,
+ "in": "query",
+ "description": "Set false to omit inline media payloads, leaving each row's { omitted, sizeBytes } marker and the media endpoint. The inline-media budget is per response, so a paged walk pulls it afresh on every page; default true.",
+ "schema": {
+ "type": "boolean"
+ }
}
],
"responses": {
diff --git a/sdk/go/types_message.go b/sdk/go/types_message.go
index 5a568fab4..54831e8c0 100644
--- a/sdk/go/types_message.go
+++ b/sdk/go/types_message.go
@@ -172,6 +172,9 @@ type ListMessagesQuery struct {
// After is a keyset cursor: the id of the last message of the previous page. Takes
// precedence over Offset.
After *string
+ // InlineMedia set to false omits inline media payloads. The budget is per response, so a
+ // walk repays it on every page.
+ InlineMedia *bool
}
func (q *ListMessagesQuery) values() url.Values {
@@ -181,6 +184,7 @@ func (q *ListMessagesQuery) values() url.Values {
setInt(v, "limit", q.Limit)
setInt(v, "offset", q.Offset)
setStr(v, "after", q.After)
+ setBool(v, "inlineMedia", q.InlineMedia)
return v
}
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/ListMessagesQuery.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/ListMessagesQuery.java
index bb7b59e1b..96b543ace 100644
--- a/sdk/java/src/main/java/com/rmyndharis/openwa/model/ListMessagesQuery.java
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/ListMessagesQuery.java
@@ -1,7 +1,8 @@
package com.rmyndharis.openwa.model;
/** Query parameters for {@code GET /sessions/:id/messages}. Null fields are omitted. */
-public record ListMessagesQuery(String chatId, String from, Integer limit, Integer offset, String after) {
+public record ListMessagesQuery(
+ String chatId, String from, Integer limit, Integer offset, String after, Boolean inlineMedia) {
public static Builder builder() {
return new Builder();
}
@@ -12,6 +13,7 @@ public record ListMessagesQuery(String chatId, String from, Integer limit, Integ
private Integer limit;
private Integer offset;
private String after;
+ private Boolean inlineMedia;
public Builder chatId(String v) {
this.chatId = v;
@@ -39,8 +41,14 @@ public record ListMessagesQuery(String chatId, String from, Integer limit, Integ
return this;
}
+ /** Set false to omit inline media payloads; the budget is per response, so a walk repays it per page. */
+ public Builder inlineMedia(Boolean v) {
+ this.inlineMedia = v;
+ return this;
+ }
+
public ListMessagesQuery build() {
- return new ListMessagesQuery(chatId, from, limit, offset, after);
+ return new ListMessagesQuery(chatId, from, limit, offset, after, inlineMedia);
}
}
}
diff --git a/sdk/javascript/src/types.ts b/sdk/javascript/src/types.ts
index 7ffe10415..7689864d6 100644
--- a/sdk/javascript/src/types.ts
+++ b/sdk/javascript/src/types.ts
@@ -470,6 +470,8 @@ export interface ListMessagesQuery {
offset?: number;
/** Keyset cursor: the `id` of the last message of the previous page. Takes precedence over `offset`. */
after?: string;
+ /** Set false to omit inline media payloads. The budget is per response, so a walk repays it per page. */
+ inlineMedia?: boolean;
}
export interface MessageHistoryQuery {
diff --git a/sdk/python/openwa/types.py b/sdk/python/openwa/types.py
index e2390ec57..695242d9f 100644
--- a/sdk/python/openwa/types.py
+++ b/sdk/python/openwa/types.py
@@ -455,7 +455,7 @@ class SendPollRequest(TypedDict):
ListMessagesQuery = TypedDict(
"ListMessagesQuery",
# ``after`` is a keyset cursor: the id of the last message of the previous page.
- {"chatId": Jid, "from": Jid, "limit": int, "offset": int, "after": str},
+ {"chatId": Jid, "from": Jid, "limit": int, "offset": int, "after": str, "inlineMedia": bool},
total=False,
)
diff --git a/src/modules/message/message.controller.spec.ts b/src/modules/message/message.controller.spec.ts
index 7a8069025..4cb3575ba 100644
--- a/src/modules/message/message.controller.spec.ts
+++ b/src/modules/message/message.controller.spec.ts
@@ -63,3 +63,31 @@ describe('MessageController — stored media download', () => {
expect(body.getStream().read()).toEqual(Buffer.from('GIF89a'));
});
});
+
+/**
+ * `inlineMedia` is an OPT-OUT, unlike every other boolean on this controller, so the parse reads the
+ * same string pair the other way round. Inverting it would quietly strip media from every default
+ * read, which no other suite would notice: the service takes a boolean and cannot tell who set it.
+ */
+describe('MessageController - inlineMedia is opt-out', () => {
+ const getMessages = jest.fn().mockResolvedValue({ messages: [], total: 0 });
+ const controller = new MessageController(
+ { getMessages } as unknown as MessageService,
+ {} as unknown as BulkMessageService,
+ );
+
+ const inlineMediaFor = async (raw?: string): Promise<boolean> => {
+ getMessages.mockClear();
+ await controller.getMessages('session-1', undefined, undefined, undefined, undefined, undefined, raw);
+ const [, options] = getMessages.mock.calls[0] as [string, { inlineMedia: boolean }];
+ return options.inlineMedia;
+ };
+
+ it.each([undefined, 'true', '1', '', 'no', 'False'])('keeps media inline for %p', async raw => {
+ expect(await inlineMediaFor(raw)).toBe(true);
+ });
+
+ it.each(['false', '0'])('omits media for %p', async raw => {
+ expect(await inlineMediaFor(raw)).toBe(false);
+ });
+});
diff --git a/src/modules/message/message.controller.ts b/src/modules/message/message.controller.ts
index e9ecee4b7..7656dc678 100644
--- a/src/modules/message/message.controller.ts
+++ b/src/modules/message/message.controller.ts
@@ -76,6 +76,15 @@ export class MessageController {
})
@ApiQuery({ name: 'limit', required: false, type: Number, description: 'Max messages to return (default 50)' })
@ApiQuery({ name: 'offset', required: false, type: Number, description: 'Offset for pagination' })
+ @ApiQuery({
+ name: 'inlineMedia',
+ required: false,
+ type: Boolean,
+ description:
+ "Set false to omit inline media payloads, leaving each row's { omitted, sizeBytes } marker and " +
+ 'the media endpoint. The inline-media budget is per response, so a paged walk pulls it afresh on ' +
+ 'every page; default true.',
+ })
@ApiQuery({
name: 'after',
required: false,
@@ -95,6 +104,7 @@ export class MessageController {
@Query('limit') limit?: string,
@Query('offset') offset?: string,
@Query('after') after?: string,
+ @Query('inlineMedia') inlineMedia?: string,
) {
return this.messageService.getMessages(sessionId, {
chatId,
@@ -102,6 +112,9 @@ export class MessageController {
limit: limit ? parseInt(limit, 10) : undefined,
offset: offset ? parseInt(offset, 10) : undefined,
after,
+ // Opt-out, so anything but an explicit false keeps today's behaviour. Same string pair the
+ // opt-in flags on this controller accept, read the other way round.
+ inlineMedia: inlineMedia !== 'false' && inlineMedia !== '0',
});
}
diff --git a/src/modules/message/message.service.spec.ts b/src/modules/message/message.service.spec.ts
index c10ec0d2b..89e1f1d14 100644
--- a/src/modules/message/message.service.spec.ts
+++ b/src/modules/message/message.service.spec.ts
@@ -967,6 +967,38 @@ describe('MessageService', () => {
else process.env.MESSAGE_LIST_INLINE_MEDIA_BUDGET_BYTES = prev;
}
});
+
+ // The budget is per response, so a walk pulls it afresh on every page. `inlineMedia: false` is
+ // how a client reading many pages asks for the rows without the bytes.
+ it('omits every payload when the caller opts out, including the one the allowance would let through', async () => {
+ const rows = Array.from(
+ { length: 3 },
+ (_, i) =>
+ ({
+ id: `m${i}`,
+ metadata: { media: { mimetype: 'image/jpeg', data: 'x'.repeat(10_000) } },
+ }) as unknown as Message,
+ );
+ const builder = {
+ where: jest.fn().mockReturnThis(),
+ andWhere: jest.fn().mockReturnThis(),
+ orderBy: jest.fn().mockReturnThis(),
+ addOrderBy: jest.fn().mockReturnThis(),
+ skip: jest.fn().mockReturnThis(),
+ take: jest.fn().mockReturnThis(),
+ getManyAndCount: jest.fn().mockResolvedValue([rows, 3]),
+ };
+ (repository.createQueryBuilder as unknown as jest.Mock).mockReturnValue(builder);
+
+ const result = await service.getMessages('sess-1', { limit: 100, inlineMedia: false });
+
+ expect(result.messages).toHaveLength(3); // the rows survive, only the payloads go
+ for (const message of result.messages) {
+ const media = (message.metadata as { media: Record<string, unknown> }).media;
+ expect(media.data).toBeUndefined();
+ expect(media).toMatchObject({ mimetype: 'image/jpeg', omitted: true, sizeBytes: 7500 });
+ }
+ });
});
});
diff --git a/src/modules/message/message.service.ts b/src/modules/message/message.service.ts
index 190e16bb3..2922c52c1 100644
--- a/src/modules/message/message.service.ts
+++ b/src/modules/message/message.service.ts
@@ -34,6 +34,12 @@ export interface GetMessagesOptions {
* `offset`, which is left working unchanged for callers that already use it.
*/
after?: string;
+ /**
+ * Set false to omit every inline media payload, leaving each row's `{ omitted, sizeBytes }` marker
+ * and the media endpoint. The budget below is per RESPONSE, so a walk pulls it afresh on every
+ * page; a client reading many pages usually wants the rows, not the bytes. Defaults to true.
+ */
+ inlineMedia?: boolean;
}
/**
@@ -229,7 +235,7 @@ export class MessageService implements PluginMessagePort {
sessionId: string,
options: GetMessagesOptions = {},
): Promise<{ messages: Message[]; total: number }> {
- const { chatId, from, after } = options;
+ const { chatId, from, after, inlineMedia } = options;
// Sanitize pagination: a non-finite limit/offset — e.g. `?limit=abc` -> NaN —
// must never reach TypeORM's take()/skip(). Clamp to sane bounds; fall back to defaults.
const rawLimit = options.limit;
@@ -282,6 +288,10 @@ export class MessageService implements PluginMessagePort {
});
}
+ // A budget of 0 means "never inline" and grants no single-payload allowance, which is exactly
+ // what an opted-out caller asks for, so the flag picks the budget rather than a second code path.
+ const inlineMediaBudget = inlineMedia === false ? 0 : resolveMessageListInlineMediaBudgetBytes();
+
if (after !== undefined) {
// `total` keeps its documented meaning, rows matching the filters, so count before narrowing.
const total = await query.clone().getCount();
@@ -304,14 +314,14 @@ export class MessageService implements PluginMessagePort {
if (messages.length === 0 && !(await this.messageRepository.exists({ where: { id: after, sessionId } }))) {
throw new BadRequestException(`Unknown cursor '${after}' for this session`);
}
- return { messages: spendInlineMediaBudget(messages, resolveMessageListInlineMediaBudgetBytes()), total };
+ return { messages: spendInlineMediaBudget(messages, inlineMediaBudget), total };
}
const [messages, total] = await query.getManyAndCount();
// The 1..100 clamp above bounds the ROW COUNT, not the response: each row carries its inline
// base64 in metadata.media.data. Spent newest-first (the query orders createdAt DESC), so the
// most recently viewed media still arrives inline and the rest keeps its omitted marker.
- return { messages: spendInlineMediaBudget(messages, resolveMessageListInlineMediaBudgetBytes()), total };
+ return { messages: spendInlineMediaBudget(messages, inlineMediaBudget), total };
}
/**