From 4e45a313b7f0831b38ffdf19e1e8b5160dcfc3aa Mon Sep 17 00:00:00 2001 From: localhost Date: Thu, 20 Aug 2026 18:25:29 +0200 Subject: [PATCH] fix(archive): close metadata websocket on completion --- src/utils/download.ts | 69 +++++++++++++++++++++++++++---------------- 1 file changed, 43 insertions(+), 26 deletions(-) diff --git a/src/utils/download.ts b/src/utils/download.ts index e3f0f62..82d5d41 100644 --- a/src/utils/download.ts +++ b/src/utils/download.ts @@ -1,37 +1,54 @@ -import WebSocket from 'ws'; +import WebSocket from 'ws' -async function downloadVideo(ws: any, id: string): Promise<{ fail: boolean, message: string, size: number }> { - return new Promise(async (resolve, reject) => { - let isDownloading = true - const downloader = new WebSocket(`ws://${(process.env.METADATA!).replace('http://', '')}/download/${id}`) - let size: number = 0 +interface WsLike { + send: (msg: string) => void +} - downloader.on('message', async function message(data: any) { - const text = data.toString() - if (text.startsWith('VIDEOSIZE-')) { - size = parseInt(text.replace('VIDEOSIZE-', '')) - } else if (text == 'done') { - isDownloading = false - return resolve({ - fail: false, - message: '', - size - }) - } else { - ws.send(`DATA - ${text}`) - } - }) - - downloader.on('close', function close() { - if (!isDownloading) return +async function downloadVideo(ws: WsLike, id: string): Promise<{ fail: boolean, message: string, size: number }> { + const { promise, resolve } = Promise.withResolvers<{ fail: boolean, message: string, size: number }>() + let isDownloading = true + const downloader = new WebSocket(`ws://${(process.env.METADATA!).replace('http://', '')}/download/${id}`) + let size = 0 + downloader.on('message', function message(data: unknown) { + const text = String(data) + if (text.startsWith('VIDEOSIZE-')) { + size = parseInt(text.replace('VIDEOSIZE-', '')) + } else if (text === 'done') { + isDownloading = false + downloader.close() return resolve({ - fail: true, - message: 'The metadata server unexpectedly closed the websocket. Please try again.', + fail: false, + message: '', size }) + } else { + ws.send(`DATA - ${text}`) + } + }) + + downloader.on('close', function close() { + if (!isDownloading) return + isDownloading = false + return resolve({ + fail: true, + message: 'The metadata server unexpectedly closed the websocket. Please try again.', + size }) }) + + downloader.on('error', function error(err: Error) { + if (!isDownloading) return + isDownloading = false + downloader.close() + return resolve({ + fail: true, + message: `WebSocket error: ${err?.message || String(err)}`, + size + }) + }) + + return promise } export { downloadVideo } \ No newline at end of file