diff --git a/extensions/feishu/src/media.ts b/extensions/feishu/src/media.ts index 8f25282981..90a4c5d8c5 100644 --- a/extensions/feishu/src/media.ts +++ b/extensions/feishu/src/media.ts @@ -1,7 +1,8 @@ import fs from "fs"; +import os from "os"; import path from "path"; import { Readable } from "stream"; -import { buildRandomTempFilePath, type ClawdbotConfig } from "openclaw/plugin-sdk"; +import type { ClawdbotConfig } from "openclaw/plugin-sdk"; import { resolveFeishuAccount } from "./accounts.js"; import { createFeishuClient } from "./client.js"; import { getFeishuRuntime } from "./runtime.js"; @@ -19,9 +20,22 @@ export type DownloadMessageResourceResult = { fileName?: string; }; +async function withTempDownloadPath( + prefix: string, + fn: (tmpPath: string) => Promise, +): Promise { + const dir = await fs.promises.mkdtemp(path.join(os.tmpdir(), prefix)); + const tmpPath = path.join(dir, "download.bin"); + try { + return await fn(tmpPath); + } finally { + await fs.promises.rm(dir, { recursive: true, force: true }).catch(() => {}); + } +} + async function readFeishuResponseBuffer(params: { response: unknown; - tmpPath: string; + tmpDirPrefix: string; errorPrefix: string; }): Promise { const { response } = params; @@ -52,10 +66,10 @@ async function readFeishuResponseBuffer(params: { return Buffer.concat(chunks); } if (typeof responseAny.writeFile === "function") { - await responseAny.writeFile(params.tmpPath); - const buffer = await fs.promises.readFile(params.tmpPath); - await fs.promises.unlink(params.tmpPath).catch(() => {}); - return buffer; + return await withTempDownloadPath(params.tmpDirPrefix, async (tmpPath) => { + await responseAny.writeFile(tmpPath); + return await fs.promises.readFile(tmpPath); + }); } if (typeof responseAny[Symbol.asyncIterator] === "function") { const chunks: Buffer[] = []; @@ -98,10 +112,9 @@ export async function downloadImageFeishu(params: { path: { image_key: imageKey }, }); - const tmpPath = buildRandomTempFilePath({ prefix: "feishu_img" }); const buffer = await readFeishuResponseBuffer({ response, - tmpPath, + tmpDirPrefix: "openclaw-feishu-img-", errorPrefix: "Feishu image download failed", }); return { buffer }; @@ -131,10 +144,9 @@ export async function downloadMessageResourceFeishu(params: { params: { type }, }); - const tmpPath = buildRandomTempFilePath({ prefix: "feishu" }); const buffer = await readFeishuResponseBuffer({ response, - tmpPath, + tmpDirPrefix: "openclaw-feishu-resource-", errorPrefix: "Feishu message resource download failed", }); return { buffer };