From 242bbfdb144cb2a92b535b13fa9e72046837a25d Mon Sep 17 00:00:00 2001 From: Clansty Date: Sun, 29 Dec 2024 22:03:04 +0800 Subject: [PATCH] chore: uriToLocalFile --- src/common/file.ts | 7 +++---- src/onebot/action/go-cqhttp/DownloadFile.ts | 16 ++++++++-------- 2 files changed, 11 insertions(+), 12 deletions(-) diff --git a/src/common/file.ts b/src/common/file.ts index 6dac529b..2abf0689 100644 --- a/src/common/file.ts +++ b/src/common/file.ts @@ -175,10 +175,9 @@ export async function checkUriType(Uri: string) { return { Uri: Uri, Type: FileUriType.Unknown }; } -export async function uriToLocalFile(dir: string, uri: string): Promise { +export async function uriToLocalFile(dir: string, uri: string, filename: string = randomUUID(), headers?: Record): Promise { const { Uri: HandledUri, Type: UriType } = await checkUriType(uri); - const filename = randomUUID(); const filePath = path.join(dir, filename); switch (UriType) { @@ -191,7 +190,7 @@ export async function uriToLocalFile(dir: string, uri: string): Promise { const isRandomName = !payload.name; const name = payload.name || randomUUID(); - const filePath = joinPath(this.core.NapCatTempPath, name); + let result: Awaited>; if (payload.base64) { - fs.writeFileSync(filePath, payload.base64, 'base64'); - } else if (payload.url?.startsWith('file://')) { - const path = payload.url.substring(7); - fs.copyFileSync(path, filePath); + result = await uriToLocalFile(this.core.NapCatTempPath, `base64://${payload.base64}`, name); } else if (payload.url) { const headers = this.getHeaders(payload.headers); - const buffer = await httpDownload({ url: payload.url, headers: headers }); - fs.writeFileSync(filePath, Buffer.from(buffer), 'binary'); + result = await uriToLocalFile(this.core.NapCatTempPath, payload.url, name, headers); } else { throw new Error('不存在任何文件, 无法下载'); } + if (!result.success) { + throw new Error(result.errMsg); + } + const filePath = result.path; if (fs.existsSync(filePath)) { if (isRandomName) {