Skip to content

Commit 2d10b3c

Browse files
committed
refactor(zalouser): move inbound media helpers to a dedicated module
knip --production flags exports that only tests import. Move the pure helpers extractInboundMedia and resolveInboundImageContentType into inbound-media.ts so production code imports them across modules, and drop the unused testing/__testing re-export.
1 parent ed501ce commit 2d10b3c

5 files changed

Lines changed: 76 additions & 118 deletions

File tree

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
import type { ZaloInboundMedia } from "./types.js";
2+
3+
/**
4+
* Detect whether an inbound zca-js message carries a photo attachment, and
5+
* extract its CDN URL + thumbnail if so. zca-js delivers photos as
6+
* `TAttachmentContent` objects with `{type:"photo", href, thumb, ...}` -
7+
* see src/models/Message.ts in the zca-js repo. The `href` field is a
8+
* public Zalo CDN URL that does not require auth to GET.
9+
*
10+
* Returns null for plain-text or non-photo content (links, files, stickers
11+
* etc.) - those flow through `normalizeMessageContent` as text. Photo
12+
* detection is intentionally inclusive: explicit `type === "photo"` wins,
13+
* but a missing type with a recognisable image extension in the href OR a
14+
* non-empty `thumb` field (only photos carry thumbs in zca-js) also matches.
15+
* Defensive about the inclusive path because some clients send photos with
16+
* type omitted; better to surface a photo as media than as JSON-stringified
17+
* text.
18+
*/
19+
export function extractInboundMedia(content: unknown): ZaloInboundMedia | null {
20+
if (!content || typeof content !== "object") {
21+
return null;
22+
}
23+
const record = content as Record<string, unknown>;
24+
const href = typeof record.href === "string" ? record.href.trim() : "";
25+
if (!href) {
26+
return null;
27+
}
28+
const type = typeof record.type === "string" ? record.type : "";
29+
const thumbUrl = typeof record.thumb === "string" ? record.thumb.trim() : "";
30+
const looksLikeImage =
31+
type === "photo" || /\.(jpe?g|png|gif|webp|bmp)(\?|$)/i.test(href) || thumbUrl.length > 0;
32+
if (!looksLikeImage) {
33+
return null;
34+
}
35+
return {
36+
kind: "image",
37+
url: href,
38+
thumbUrl: thumbUrl || undefined,
39+
};
40+
}
41+
42+
/**
43+
* Resolve a real `image/*` MIME for an inbound Zalo photo even when the CDN
44+
* returns `application/octet-stream`. Picks from the URL extension first,
45+
* falls back to `image/jpeg` (most common Zalo photo format).
46+
*/
47+
export function resolveInboundImageContentType(detected: string | undefined, url: string): string {
48+
if (detected && detected.startsWith("image/")) {
49+
return detected;
50+
}
51+
const match = url.match(/\.([a-z]+)(?:\?|$)/i);
52+
const ext = (match?.[1] ?? "jpg").toLowerCase();
53+
const extMap: Record<string, string> = {
54+
jpg: "image/jpeg",
55+
jpeg: "image/jpeg",
56+
png: "image/png",
57+
gif: "image/gif",
58+
webp: "image/webp",
59+
bmp: "image/bmp",
60+
};
61+
return extMap[ext] ?? "image/jpeg";
62+
}

‎extensions/zalouser/src/monitor.media.test.ts‎

Lines changed: 9 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { describe, expect, it } from "vitest";
2-
import { resolveInboundImageContentType } from "./monitor.js";
2+
import { resolveInboundImageContentType } from "./inbound-media.js";
33

44
describe("resolveInboundImageContentType", () => {
55
it("trusts a detected image/* MIME from saveRemoteMedia", () => {
@@ -19,29 +19,24 @@ describe("resolveInboundImageContentType", () => {
1919
"https://photo-stal-22.zdn.vn/gr/abc/photo.jpg",
2020
),
2121
).toBe("image/jpeg");
22-
expect(
23-
resolveInboundImageContentType("application/octet-stream", "https://x/y.png"),
24-
).toBe("image/png");
25-
expect(
26-
resolveInboundImageContentType("application/octet-stream", "https://x/y.WEBP"),
27-
).toBe("image/webp");
22+
expect(resolveInboundImageContentType("application/octet-stream", "https://x/y.png")).toBe(
23+
"image/png",
24+
);
25+
expect(resolveInboundImageContentType("application/octet-stream", "https://x/y.WEBP")).toBe(
26+
"image/webp",
27+
);
2828
});
2929

3030
it("falls back to image/jpeg when both detected MIME and URL extension are absent", () => {
3131
expect(resolveInboundImageContentType(undefined, "https://x/path/no-extension")).toBe(
3232
"image/jpeg",
3333
);
34-
expect(resolveInboundImageContentType("", "https://x/path/no-extension")).toBe(
35-
"image/jpeg",
36-
);
34+
expect(resolveInboundImageContentType("", "https://x/path/no-extension")).toBe("image/jpeg");
3735
});
3836

3937
it("ignores query string when parsing URL extension", () => {
4038
expect(
41-
resolveInboundImageContentType(
42-
"application/octet-stream",
43-
"https://x/y.png?token=abc&v=1",
44-
),
39+
resolveInboundImageContentType("application/octet-stream", "https://x/y.png?token=abc&v=1"),
4540
).toBe("image/png");
4641
});
4742

‎extensions/zalouser/src/monitor.ts‎

Lines changed: 2 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import { isDangerousNameMatchingEnabled } from "openclaw/plugin-sdk/dangerous-na
1212
// Zalouser plugin module implements monitor behavior.
1313
import { expectDefined } from "openclaw/plugin-sdk/expect-runtime";
1414
import { createDeferred } from "openclaw/plugin-sdk/extension-shared";
15+
import { saveRemoteMedia } from "openclaw/plugin-sdk/media-runtime";
1516
import {
1617
DEFAULT_GROUP_HISTORY_LIMIT,
1718
type HistoryEntry,
@@ -22,7 +23,6 @@ import {
2223
resolveSendableOutboundReplyParts,
2324
type OutboundReplyPayload,
2425
} from "openclaw/plugin-sdk/reply-payload";
25-
import { saveRemoteMedia } from "openclaw/plugin-sdk/media-runtime";
2626
import type { RuntimeEnv } from "openclaw/plugin-sdk/runtime";
2727
import {
2828
resolveDefaultGroupPolicy,
@@ -39,6 +39,7 @@ import {
3939
findZalouserGroupEntry,
4040
isZalouserGroupEntryAllowed,
4141
} from "./group-policy.js";
42+
import { resolveInboundImageContentType } from "./inbound-media.js";
4243
import { createZalouserIngressMonitor, type ZalouserIngressLifecycle } from "./ingress.js";
4344
import { formatZalouserMessageSidFull, resolveZalouserMessageSid } from "./message-sid.js";
4445
import { getZalouserRuntime } from "./runtime.js";
@@ -982,39 +983,6 @@ export async function monitorZalouserProvider(
982983
return { stop };
983984
}
984985

985-
export const testing = {
986-
processMessage: async (params: {
987-
message: ZaloInboundMessage;
988-
account: ResolvedZalouserAccount;
989-
config: OpenClawConfig;
990-
runtime: RuntimeEnv;
991-
historyState?: {
992-
historyLimit?: number;
993-
groupHistories?: Map<string, HistoryEntry[]>;
994-
};
995-
statusSink?: (patch: { lastInboundAt?: number; lastOutboundAt?: number }) => void;
996-
}) => {
997-
const historyLimit = Math.max(
998-
0,
999-
params.historyState?.historyLimit ??
1000-
params.account.config.historyLimit ??
1001-
params.config.messages?.groupChat?.historyLimit ??
1002-
DEFAULT_GROUP_HISTORY_LIMIT,
1003-
);
1004-
const groupHistories = params.historyState?.groupHistories ?? new Map<string, HistoryEntry[]>();
1005-
await processMessage(
1006-
params.message,
1007-
params.account,
1008-
params.config,
1009-
getZalouserRuntime(),
1010-
params.runtime,
1011-
{ historyLimit, groupHistories },
1012-
params.statusSink,
1013-
);
1014-
},
1015-
};
1016-
export { testing as __testing };
1017-
1018986
/**
1019987
* Download an inbound Zalo photo attachment to a local file via
1020988
* `saveRemoteMedia` so the kernel media pipeline can build the standard
@@ -1065,32 +1033,6 @@ async function resolveInboundMediaFacts(params: {
10651033
}
10661034
}
10671035

1068-
/**
1069-
* Resolve a real `image/*` MIME for an inbound Zalo photo even when the CDN
1070-
* returns `application/octet-stream`. Picks from the URL extension first,
1071-
* falls back to `image/jpeg` (most common Zalo photo format).
1072-
*
1073-
* Exported via __testing only; not part of the public plugin surface.
1074-
*/
1075-
export function resolveInboundImageContentType(detected: string | undefined, url: string): string {
1076-
if (detected && detected.startsWith("image/")) {
1077-
return detected;
1078-
}
1079-
const match = url.match(/\.([a-z]+)(?:\?|$)/i);
1080-
const ext = (match?.[1] ?? "jpg").toLowerCase();
1081-
const extMap: Record<string, string> = {
1082-
jpg: "image/jpeg",
1083-
jpeg: "image/jpeg",
1084-
png: "image/png",
1085-
gif: "image/gif",
1086-
webp: "image/webp",
1087-
bmp: "image/bmp",
1088-
};
1089-
return extMap[ext] ?? "image/jpeg";
1090-
}
1091-
1092-
// Re-export internal helper for unit tests only - keep out of public surface
1093-
// by attaching to the testing namespace.
10941036
type InboundMediaFact = ReturnType<typeof toInboundMediaFacts>[number];
10951037

10961038
/* oxlint-disable max-lines -- TODO: split this grandfathered oversized file. */

‎extensions/zalouser/src/zalo-js.media.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { describe, expect, it } from "vitest";
2-
import { extractInboundMedia } from "./zalo-js.js";
2+
import { extractInboundMedia } from "./inbound-media.js";
33

44
describe("extractInboundMedia", () => {
55
it("returns null for plain string content (text message)", () => {
@@ -29,7 +29,7 @@ describe("extractInboundMedia", () => {
2929
).toBeNull();
3030
});
3131

32-
it("extracts media when content.type === \"photo\"", () => {
32+
it('extracts media when content.type === "photo"', () => {
3333
const result = extractInboundMedia({
3434
type: "photo",
3535
href: "https://photo-stal-1.zdn.vn/abc/def.jpg",

‎extensions/zalouser/src/zalo-js.ts‎

Lines changed: 1 addition & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import {
2020
normalizeOptionalString,
2121
} from "openclaw/plugin-sdk/string-coerce-runtime";
2222
import { sleep, truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
23+
import { extractInboundMedia } from "./inbound-media.js";
2324
import { normalizeZaloReactionIcon } from "./reaction.js";
2425
import { createZalouserSendReceipt } from "./send-receipt.js";
2526
import {
@@ -35,7 +36,6 @@ import type {
3536
ZaloGroupContext,
3637
ZaloGroup,
3738
ZaloGroupMember,
38-
ZaloInboundMedia,
3939
ZaloInboundMessage,
4040
ZaloSendOptions,
4141
ZaloSendResult,
@@ -217,47 +217,6 @@ function normalizeMessageContent(content: unknown): string {
217217
}
218218
}
219219

220-
/**
221-
* Detect whether an inbound zca-js message carries a photo attachment, and
222-
* extract its CDN URL + thumbnail if so. zca-js delivers photos as
223-
* `TAttachmentContent` objects with `{type:"photo", href, thumb, ...}` -
224-
* see src/models/Message.ts in the zca-js repo. The `href` field is a
225-
* public Zalo CDN URL that does not require auth to GET.
226-
*
227-
* Returns null for plain-text or non-photo content (links, files, stickers
228-
* etc.) - those flow through `normalizeMessageContent` as text. Photo
229-
* detection is intentionally inclusive: explicit `type === "photo"` wins,
230-
* but a missing type with a recognisable image extension in the href OR a
231-
* non-empty `thumb` field (only photos carry thumbs in zca-js) also matches.
232-
* Defensive about the inclusive path because some clients send photos with
233-
* type omitted; better to surface a photo as media than as JSON-stringified
234-
* text.
235-
*/
236-
export function extractInboundMedia(content: unknown): ZaloInboundMedia | null {
237-
if (!content || typeof content !== "object") {
238-
return null;
239-
}
240-
const record = content as Record<string, unknown>;
241-
const href = typeof record.href === "string" ? record.href.trim() : "";
242-
if (!href) {
243-
return null;
244-
}
245-
const type = typeof record.type === "string" ? record.type : "";
246-
const thumbUrl = typeof record.thumb === "string" ? record.thumb.trim() : "";
247-
const looksLikeImage =
248-
type === "photo" ||
249-
/\.(jpe?g|png|gif|webp|bmp)(\?|$)/i.test(href) ||
250-
thumbUrl.length > 0;
251-
if (!looksLikeImage) {
252-
return null;
253-
}
254-
return {
255-
kind: "image",
256-
url: href,
257-
thumbUrl: thumbUrl || undefined,
258-
};
259-
}
260-
261220
function resolveInboundTimestamp(rawTs: unknown): number {
262221
const fallbackTimestamp = () => asDateTimestampMs(Date.now()) ?? 0;
263222
const parsed =

0 commit comments

Comments
 (0)